diff --git a/.jshintrc b/.jshintrc deleted file mode 100644 index 436c0a2..0000000 --- a/.jshintrc +++ /dev/null @@ -1,8 +0,0 @@ -{ - "browser": true, - "proto": true, - "loopfunc": true, - "trailing": false, - "latedef": true, - "curly": false -} diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 51edbe6..0000000 --- a/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -script: grunt test -node_js: -- '0.10' -language: node_js -env: - global: - - secure: el1KTyBdyspsSRGPYt9QU+ZV8elIpTU2j/6z2v7aUgAQ0OWU4wZVFXtJdFisOSqWvqzzFyPcAB33ZudiSfRrQIS3OV+gXU7kheTiNMzr10e3UArjRzOyefBE0YUcj5j5+tbXoGzCMdyGtMpJx0laIXAy0fRk1ZL8q1Y3QMijgYU= - - secure: AjubcPJLsDzOpIvqBRR7ESJ+To93V/wZ5hJJ8NDKC0EXK6iccgLCBhUdq53Wa5ZGP3dMVziB2XX+IqRxOouuXMZDHzIf9hA06s1+yl2n5FriXK3Owwuw2B0Xt1pHnjaG+f/v5u4A/YmeTL5+PqQTWThdutMPhAHmsqvw0aEGp4s= - - secure: MbhoqeDNWZjoUY4evgpRX1+wfq+4FcGAEyhLt3NEfX8TqlIzMwcb8yVuCkoO+5uMmAw6Twn3zTyHNg5fteuczQmUBi69LuGlwy2r/VMNRwnpD7rDpd9XkCqA6pGHXMTV5qMTdPHxP+UOEgsPlGcK+urbmMemg0zFh2ZhkJsFMlQ= - - secure: RLrifbDTT8258v2Xp907Co65t50YFgZ+Dm1nhkicQBWLk1qIEmz7YCdzQhjgDnn8ZwSUq7VPClj3Oh7sBCkByhD3om1647gWScTIl7hKGOmUaz+lH3cl99l8/o9SNhlnoJUTcG0ijMIAKeGAxu+ec1+qoOfA4g+e2Q5O35PoJWc= diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..71ef0fa --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "cSpell.words": [ + "exts", + "firstpaint" + ] +} \ No newline at end of file diff --git a/Gruntfile.js b/Gruntfile.js deleted file mode 100644 index 7fbc72d..0000000 --- a/Gruntfile.js +++ /dev/null @@ -1,135 +0,0 @@ -module.exports = function (grunt) { - 'use strict'; - - var browsers = [{ - browserName: "firefox", - version: "14", - platform: "XP" - }, - { - browserName: "firefox", - version: "26", - platform: "XP" - },{ - browserName: "chrome", - version: "26", - platform: "XP" - },{ - browserName: "chrome", - version: "32", - platform: "Windows 8.1" - } - ]; - - // Project configuration. - grunt.initConfig({ - meta : { - src : 'src/**/*.js', - specs : 'spec/**/*.js' - }, - jshint: { - all: [ - 'Gruntfile.js', - '<%= meta.src %>', - '<%= meta.specs %>' - ], - options: { - jshintrc: '.jshintrc' - } - }, - concat: { - raw:{ - src:['src/core.js'], - dest: 'dist/x-tag-no-polyfills.js' - }, - core:{ - src:[ - 'lib/DOMTokenList.js', - 'lib/webcomponents-lite.js', - 'lib/pep.js', - 'src/core.js' - ], - dest: 'dist/x-tag-core.js' - }, - full:{ - src:[ - 'lib/DOMTokenList.js', - 'lib/webcomponents.js', - 'lib/pep.js', - 'src/core.js' - ], - dest: 'dist/x-tag-core-with-shadowdom.js' - } - }, - uglify: { - raw: { - files: { - 'dist/x-tag-no-polyfills.min.js': ['src/core.js'] - } - }, - core: { - files: { - 'dist/x-tag-core.min.js': ['dist/x-tag-core.js'] - } - }, - full: { - files: { - 'dist/x-tag-core-with-shadowdom.min.js': ['dist/x-tag-core-with-shadowdom.js'] - } - } - }, - bumpup: ['bower.json', 'package.json'], - tagrelease: { - file: 'package.json', - prefix: '', - commit: true - }, - connect: { - test:{ - options:{ - port: 9999, - base: '.' - } - }, - dev:{ - options:{ - port: 9000, - base: '.', - keepalive: true - } - } - }, - 'saucelabs-jasmine': { - all: { - options: { - urls: ["http://127.0.0.1:9999/test/index.html"], - tunnelTimeout: 5, - build: process.env.TRAVIS_JOB_ID, - concurrency: 3, - browsers: browsers, - testname: "x-tag-core tests", - tags: ["master"], - onTestComplete: function(result){ - return JSON.stringify(result); - } - } - } - } - }); - - grunt.loadNpmTasks('grunt-contrib-connect'); - grunt.loadNpmTasks('grunt-bumpup'); - grunt.loadNpmTasks('grunt-tagrelease'); - grunt.loadNpmTasks('grunt-contrib-concat'); - grunt.loadNpmTasks('grunt-contrib-uglify'); - grunt.loadNpmTasks('grunt-contrib-jshint'); - grunt.loadNpmTasks('grunt-saucelabs'); - - grunt.registerTask('test', ['']); - - // Default task. - grunt.registerTask('default', ['test']); - grunt.registerTask('test', ['jshint','connect:test', 'saucelabs-jasmine']); - grunt.registerTask('compress', ['concat:raw', 'concat:core', 'concat:full']); - grunt.registerTask('build', ['concat:raw', 'concat:core', 'concat:full', 'uglify']); -}; diff --git a/README.md b/README.md index 196c37f..0b2851c 100644 --- a/README.md +++ b/README.md @@ -2,19 +2,17 @@ [![Join the chat at https://gitter.im/x-tag/core](https://badges.gitter.im/x-tag/core.svg)](https://gitter.im/x-tag/core?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![Bower version](https://badge.fury.io/bo/x-tag-core.svg)](http://badge.fury.io/bo/x-tag-core) - [![NPM version](https://badge.fury.io/js/x-tag.svg)](https://badge.fury.io/js/x-tag) [![CDNJS](https://img.shields.io/cdnjs/v/x-tag.svg)](https://cdnjs.com/libraries/x-tag) **This is the repository for the core [X-Tag](http://x-tag.github.io/) library.** -X-Tag is a Microsoft supported, open source, JavaScript library that wraps the W3C standard Web Components family of APIs to provide a compact, feature-rich interface for rapid component development. While X-Tag offers feature hooks for all Web Component APIs (Custom Elements, Shadow DOM, Templates, and HTML Imports), it only requires [Custom Element][1] support to operate. In the absence of native Custom Element support, X-Tag uses a set of polyfills shared with Google's Polymer framework. +X-Tag is a Microsoft supported, open source, JavaScript library that wraps the W3C standard Web Components family of APIs to provide a compact, feature-rich interface for rapid component development. While X-Tag offers feature hooks for all Web Component APIs (Custom Elements, Shadow DOM, HTML Templates), it only requires [Custom Element][1] support to operate. In the absence of native Custom Element support, X-Tag relies on the same set of polyfills Google's Polymer framework uses. You can find out more about what X-Tag does, where it works, and how to use it, on the project page: [x-tag.github.io](http://x-tag.github.io/). - [1]: https://dvcs.w3.org/hg/webcomponents/raw-file/tip/explainer/index.html "W3 Web Components Spec (Draft)" + [1]: http://w3c.github.io/webcomponents/spec/custom/ "W3 Web Components Spec (Draft)" ## Snag X-Tag from NPM @@ -30,11 +28,9 @@ To get started hacking on X-Tag core: git clone https://github.com/x-tag/core x-tag-core --recursive cd x-tag-core npm install # installs all the required dependencies using package.json -grunt build # outputs x-tag-core.js and x-tag-core.min.js to ./dist +gulp all # outputs x-tag-core.js and x-tag-core.min.js to ./dist ```` -If you are interested in building your own custom elements, you can use our [web-component-stub](https://github.com/x-tag/web-component-stub) as a starting point. - ## Updating If you already cloned the library and want to update your build with changes to Core, do: @@ -43,14 +39,14 @@ If you already cloned the library and want to update your build with changes to cd x-tag-core git pull origin master npm install -grunt build +gulp all ```` This assumes you just cloned the library and its remote repository is labelled `origin`. Suppose you had your own fork where your own remote is `origin`; you should add another remote origin and label it as `upstream`. Then your `git pull` line would need to be `git pull upstream master` instead. ## Tests -We use Jasmine to test the library, and you can verify it works as expected by opening [test/index.html](test/index.html) in your browser to run the tests. +We use Jasmine to test the library, and you can verify it works as expected by opening [tests/core/index.html](tests/core/index.html) in your browser to run the tests. ## Regenerating the distributable build @@ -60,16 +56,12 @@ In the interest of not reinventing the wheel, X-Tag core uses a few existing lib If you make changes on the library and want to regenerate the build, just run ````bash -grunt build +gulp all ```` -and both `x-tag-core.js` and `x-tag-core.min.js` will be rebuilt and placed in the `./dist` directory. - - -## Creating your own web components +and both `x-tag-raw.js` and `x-tag-polyfilled.js` will be rebuilt, minified, and placed in the `./dist` directory. -To learn more about X-Tags visit [x-tag.github.io/docs](http://x-tag.github.io/docs). -To create your own component, use our [web-component-stub](https://github.com/x-tag/web-component-stub). +## Creating your own Web Components -Share your components by adding them to the [Custom Elements Registry](http://customelements.io/) or Bower. +To learn more about X-Tags visit [x-tag.github.io/docs](http://x-tag.github.io/docs). \ No newline at end of file diff --git a/bower.json b/bower.json index 68ec5fe..ec07cd1 100644 --- a/bower.json +++ b/bower.json @@ -1,7 +1,7 @@ { "name": "x-tag-core", "description": "X-Tag core library for creating custom elements as defined by the w3c Web Components spec.", - "version": "1.5.11", + "version": "2.0.3-beta", "keywords": [ "web-components", "core", @@ -9,6 +9,6 @@ "x-tag" ], "main": [ - "dist/x-tag-core.js" + "dist/x-tag-polyfilled.js" ] } \ No newline at end of file diff --git a/dist/plugins/attributes/src.js b/dist/plugins/attributes/src.js new file mode 100644 index 0000000..df1b0cd --- /dev/null +++ b/dist/plugins/attributes/src.js @@ -0,0 +1 @@ +xtag.extensions.src={mixin:e=>(class extends e{set"src::attr"(e){var t=new XMLHttpRequest;t.open("GET",e,!0),t.onload=(()=>xtag.fireEvent(this,"load",{detail:t.response})),t.onerror=(()=>xtag.fireEvent(this,"error",{detail:t.response})),t.send(null)}})}; \ No newline at end of file diff --git a/dist/plugins/events/tap.js b/dist/plugins/events/tap.js new file mode 100644 index 0000000..61ee398 --- /dev/null +++ b/dist/plugins/events/tap.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.PointerEventsPolyfill=e()}(this,function(){"use strict";function t(t,e){e=e||Object.create(null);var n=document.createEvent("Event");n.initEvent(t,e.bubbles||!1,e.cancelable||!1);for(var i,r=2;r=Math.abs(i["client"+o]-this.firstXY[o])}return this.firstXY=null,e}},findTouch:function(t,e){for(var n,i=0,r=t.length;i=e.length){var n=[];k.forEach(function(t,i){if(1!==i&&!this.findTouch(e,i-2)){var r=t.out;n.push(r)}},this),n.forEach(this.cancelOut,this)}},touchstart:function(t){this.vacuumTouches(t),this.setPrimaryTouch(t.changedTouches[0]),this.dedupSynthMouse(t),this.scrolling||(this.clickCount++,this.processTouches(t,this.overDown))},overDown:function(t){k.set(t.pointerId,{target:t.target,out:t,outTarget:t.target}),m.enterOver(t),m.down(t)},touchmove:function(t){this.scrolling||(this.shouldScroll(t)?(this.scrolling=!0,this.touchcancel(t)):(t.preventDefault(),this.processTouches(t,this.moveOverOut)))},moveOverOut:function(t){var e=t,n=k.get(e.pointerId);if(n){var i=n.out,r=n.outTarget;m.move(e),i&&r!==e.target&&(i.relatedTarget=e.target,e.relatedTarget=r,i.target=r,e.target?(m.leaveOut(i),m.enterOver(e)):(e.target=r,e.relatedTarget=null,this.cancelOut(e))),n.out=e,n.outTarget=e.target}},touchend:function(t){this.dedupSynthMouse(t),this.processTouches(t,this.upOut)},upOut:function(t){this.scrolling||(m.up(t),m.leaveOut(t)),this.cleanUpPointer(t)},touchcancel:function(t){this.processTouches(t,this.cancelOut)},cancelOut:function(t){m.cancel(t),m.leaveOut(t),this.cleanUpPointer(t)},cleanUpPointer:function(t){k.delete(t.pointerId),this.removePrimaryPointer(t)},dedupSynthMouse:function(t){var e=_.lastTouches,n=t.changedTouches[0];if(this.isPrimaryTouch(n)){var i={x:n.clientX,y:n.clientY};e.push(i);var r=function(t,e){var n=t.indexOf(e);n>-1&&t.splice(n,1)}.bind(null,e,i);setTimeout(r,2500)}}};N=new n(F.elementAdded,F.elementRemoved,F.elementChanged,F);var x,K,j,B=m.pointermap,U=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,z={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(t){m.listen(t,this.events)},unregister:function(t){m.unlisten(t,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(t){var e=t;return U&&((e=m.cloneEvent(t)).pointerType=this.POINTER_TYPES[t.pointerType]),e},cleanup:function(t){B.delete(t)},MSPointerDown:function(t){B.set(t.pointerId,t);var e=this.prepareEvent(t);m.down(e)},MSPointerMove:function(t){var e=this.prepareEvent(t);m.move(e)},MSPointerUp:function(t){var e=this.prepareEvent(t);m.up(e),this.cleanup(t.pointerId)},MSPointerOut:function(t){var e=this.prepareEvent(t);m.leaveOut(e)},MSPointerOver:function(t){var e=this.prepareEvent(t);m.enterOver(e)},MSPointerCancel:function(t){var e=this.prepareEvent(t);m.cancel(e),this.cleanup(t.pointerId)},MSLostPointerCapture:function(t){var e=m.makeEvent("lostpointercapture",t);m.dispatchEvent(e)},MSGotPointerCapture:function(t){var e=m.makeEvent("gotpointercapture",t);m.dispatchEvent(e)}};return window.navigator.msPointerEnabled?(x=function(t){a(t),s(this),u(t)&&(m.setCapture(t,this,!0),this.msSetPointerCapture(t))},K=function(t){a(t),m.releaseCapture(t,!0),this.msReleasePointerCapture(t)}):(x=function(t){a(t),s(this),u(t)&&m.setCapture(t,this)},K=function(t){a(t),m.releaseCapture(t)}),j=function(t){return!!m.captureInfo[t]},function(){if(I){S.forEach(function(t){String(t)===t?(O+=r(t)+o(t)+"\n",M&&(O+=i(t)+o(t)+"\n")):(O+=t.selectors.map(r)+o(t.rule)+"\n",M&&(O+=t.selectors.map(i)+o(t.rule)+"\n"))});var t=document.createElement("style");t.textContent=O,document.head.appendChild(t)}}(),function(){if(!window.PointerEvent){if(window.PointerEvent=t,window.navigator.msPointerEnabled){var e=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:e,enumerable:!0}),m.registerSource("ms",z)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),m.registerSource("mouse",_),void 0!==window.ontouchstart&&m.registerSource("touch",F);m.register(document)}}(),window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:x},releasePointerCapture:{value:K},hasPointerCapture:{value:j}}),{dispatcher:m,Installer:n,PointerEvent:t,PointerMap:h,targetFinding:E}}); +xtag.events.tap={attach:["pointerdown","pointerup"],onFilter(t,a,n,e){var r=n.data;"pointerdown"==a.type?(r.startX=a.clientX,r.startY=a.clientY):0===a.button&&Math.abs(r.startX-a.clientX)<10&&Math.abs(r.startY-a.clientY)<10&&e()}}; \ No newline at end of file diff --git a/dist/plugins/rendering/hyperHTML.js b/dist/plugins/rendering/hyperHTML.js new file mode 100644 index 0000000..12c0cd2 --- /dev/null +++ b/dist/plugins/rendering/hyperHTML.js @@ -0,0 +1,2 @@ +var hyperHTML=function(e){"use strict";function t(){}function n(e){this.childNodes=e,this.length=e.length,this.first=e[0],this.last=e[this.length-1]}function r(){}function i(e){var t=Ce.get(this);return t&&t.template===X(e)?o.apply(t.updates,arguments):function(e){e=X(e);var t=je.get(e)||function(e){var t=[],n=e.join(p).replace(Ae,Se),r=J(this,n);xe.find(r,t,e.slice());var i={fragment:r,paths:t};return je.set(e,i),i}.call(this,e),n=Q(this.ownerDocument,t.fragment),r=xe.create(n,t.paths);Ce.set(this,{template:e,updates:r}),o.apply(r,arguments),this.textContent="",this.appendChild(n)}.apply(this,arguments),this}function o(){for(var e=arguments.length,t=1;t\"'=]+",$="<([A-Za-z]+[A-Za-z0-9:_-]*)((?:",B="(?:=(?:'[^']*?'|\"[^\"]*?\"|<[^>]*?>|[^ \\f\\n\\r\\t\\/>\"'=]+))?)",R=new RegExp($+P+B+"+)([ "+D+"]*/?>)","g"),H=new RegExp($+P+B+"*)([ "+D+"]*/>)","g"),_=O(document),F="append"in _,Z="content"in L(document,"template");_.appendChild(M(_,"g")),_.appendChild(M(_,""));var z=1===_.cloneNode(!0).childNodes.length,V="importNode"in document,G=F?function(e,t){e.append.apply(e,t)}:function(e,t){for(var n=t.length,r=0;r"+t+"",G(r,U.call(n.querySelectorAll(i)))}else n.innerHTML=t,G(r,U.call(n.childNodes));return r},te=Z?function(e,t){var n=O(e),r=k(e).createElementNS(s,"svg");return r.innerHTML=t,G(n,U.call(r.childNodes)),n}:function(e,t){var n=O(e),r=L(e,"div");return r.innerHTML=''+t+"",G(n,U.call(r.firstChild.childNodes)),n};n.prototype.insert=function(){var e=O(this.first);return G(e,this.childNodes),e},n.prototype.remove=function(){var e=this.first,t=this.last;if(2===this.length)t.parentNode.removeChild(t);else{var n=k(e).createRange();n.setStartBefore(this.childNodes[1]),n.setEndAfter(t),n.deleteContents()}return e};var ne=function(e,t,n){e.unshift(e.indexOf.call(t.childNodes,n))},re=function(e,t,n){return{type:e,name:n,node:t,path:function(e){var t=[],n=void 0;switch(e.nodeType){case l:case 11:n=e;break;case 8:n=e.parentNode,ne(t,n,e);break;default:n=e.ownerElement}for(e=n;n=n.parentNode;e=n)ne(t,n,e);return t}(t)}},ie=function(e,t){for(var n=t.length,r=0;rc){var m=n[d+1],b=null==m?a:o(m,0);if(l===d)e.insertBefore(o(n[l],1),b);else{for(var w=e.ownerDocument.createDocumentFragment();l<=d;)w.appendChild(o(n[l++],1));e.insertBefore(w,b)}}else if(null==t[u]&&u++,u===c)e.removeChild(o(t[u],-1));else{var y=e.ownerDocument.createRange();y.setStartBefore(o(t[u],-1)),y.setEndAfter(o(t[c],-1)),y.deleteContents()}return n},de=new w;r.prototype=Object.create(null);var he=function(e){return{html:e}},ve=function e(t,r){return"ELEMENT_NODE"in t?t:t.constructor===n?1/r<0?r?t.remove():t.last:r?t.insert():t.first:e(t.render(),r)},pe=function(e){return"ELEMENT_NODE"in e||e instanceof n||e instanceof t},ge=function(e,t,n){for(var i=new r,o=e.attributes,a=U.call(o),u=[],l=a.length,c=0;c"},Te=new b,Le=function(e){var t=void 0,n=void 0,r=void 0,o=void 0,a=void 0;return function(u){u=X(u);var l=o!==u;return l&&(o=u,r=O(document),n="svg"===e?document.createElementNS(s,"svg"):r,a=i.bind(n)),a.apply(null,arguments),l&&("svg"===e&&G(r,U.call(n.childNodes)),t=Oe(r)),t}},ke=function(e,t){var n=t.indexOf(":"),r=Te.get(e),i=t;return-1(class extends e{_render(e,r){e._hyper?(e.call(this,hyperHTML.bind),this._XTagRender=null,r.resolve&&r.resolve(this)):super._render(e,r)}}),onParse:(e,r,n,s)=>(s.value._hyper=!0,e.getOptions("templates")[r||"default"]=s.value,!1),onReady(e,r,n,s){s[0]&&("ready"===s[0]?e.render(n):e.rxn("firstpaint",()=>e.render(n))),r()}}; \ No newline at end of file diff --git a/dist/x-tag-core-with-shadowdom.js b/dist/x-tag-core-with-shadowdom.js deleted file mode 100644 index 81f1ce2..0000000 --- a/dist/x-tag-core-with-shadowdom.js +++ /dev/null @@ -1,9601 +0,0 @@ -// DOMTokenList polyfill for IE9 -(function () { - -if (typeof window.Element === "undefined" || "classList" in document.documentElement) return; - -var prototype = Array.prototype, - indexOf = prototype.indexOf, - slice = prototype.slice, - push = prototype.push, - splice = prototype.splice, - join = prototype.join; - -function DOMTokenList(el) { - this._element = el; - if (el.className != this._classCache) { - this._classCache = el.className; - - if (!this._classCache) return; - - // The className needs to be trimmed and split on whitespace - // to retrieve a list of classes. - var classes = this._classCache.replace(/^\s+|\s+$/g,'').split(/\s+/), - i; - for (i = 0; i < classes.length; i++) { - push.call(this, classes[i]); - } - } -}; - -function setToClassName(el, classes) { - el.className = classes.join(' '); -} - -DOMTokenList.prototype = { - add: function(token) { - if(this.contains(token)) return; - push.call(this, token); - setToClassName(this._element, slice.call(this, 0)); - }, - contains: function(token) { - return indexOf.call(this, token) !== -1; - }, - item: function(index) { - return this[index] || null; - }, - remove: function(token) { - var i = indexOf.call(this, token); - if (i === -1) { - return; - } - splice.call(this, i, 1); - setToClassName(this._element, slice.call(this, 0)); - }, - toString: function() { - return join.call(this, ' '); - }, - toggle: function(token) { - if (indexOf.call(this, token) === -1) { - this.add(token); - } else { - this.remove(token); - } - } -}; - -window.DOMTokenList = DOMTokenList; - -function defineElementGetter (obj, prop, getter) { - if (Object.defineProperty) { - Object.defineProperty(obj, prop,{ - get : getter - }) - } else { - obj.__defineGetter__(prop, getter); - } -} - -defineElementGetter(Element.prototype, 'classList', function () { - return new DOMTokenList(this); -}); - -})(); - - -/** - * @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.20 -(function() { - window.WebComponents = window.WebComponents || { - flags: {} - }; - var file = "webcomponents.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 = {}; - } - } - flags.shadow = flags.shadow || flags.shadowdom || flags.polyfill; - if (flags.shadow === "native") { - flags.shadow = false; - } else { - flags.shadow = flags.shadow || !HTMLElement.prototype.createShadowRoot; - } - if (flags.register) { - window.CustomElements = window.CustomElements || { - flags: {} - }; - window.CustomElements.flags.register = flags.register; - } - WebComponents.flags = flags; -})(); - -if (WebComponents.flags.shadow) { - 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; - })(); - } - window.ShadowDOMPolyfill = {}; - (function(scope) { - "use strict"; - var constructorTable = new WeakMap(); - var nativePrototypeTable = new WeakMap(); - var wrappers = Object.create(null); - function detectEval() { - if (typeof chrome !== "undefined" && chrome.app && chrome.app.runtime) { - return false; - } - if (navigator.getDeviceStorage) { - return false; - } - try { - var f = new Function("return true;"); - return f(); - } catch (ex) { - return false; - } - } - var hasEval = detectEval(); - function assert(b) { - if (!b) throw new Error("Assertion failed"); - } - var defineProperty = Object.defineProperty; - var getOwnPropertyNames = Object.getOwnPropertyNames; - var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - function mixin(to, from) { - var names = getOwnPropertyNames(from); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - defineProperty(to, name, getOwnPropertyDescriptor(from, name)); - } - return to; - } - function mixinStatics(to, from) { - var names = getOwnPropertyNames(from); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - switch (name) { - case "arguments": - case "caller": - case "length": - case "name": - case "prototype": - case "toString": - continue; - } - defineProperty(to, name, getOwnPropertyDescriptor(from, name)); - } - return to; - } - function oneOf(object, propertyNames) { - for (var i = 0; i < propertyNames.length; i++) { - if (propertyNames[i] in object) return propertyNames[i]; - } - } - var nonEnumerableDataDescriptor = { - value: undefined, - configurable: true, - enumerable: false, - writable: true - }; - function defineNonEnumerableDataProperty(object, name, value) { - nonEnumerableDataDescriptor.value = value; - defineProperty(object, name, nonEnumerableDataDescriptor); - } - getOwnPropertyNames(window); - function getWrapperConstructor(node, opt_instance) { - var nativePrototype = node.__proto__ || Object.getPrototypeOf(node); - if (isFirefox) { - try { - getOwnPropertyNames(nativePrototype); - } catch (error) { - nativePrototype = nativePrototype.__proto__; - } - } - var wrapperConstructor = constructorTable.get(nativePrototype); - if (wrapperConstructor) return wrapperConstructor; - var parentWrapperConstructor = getWrapperConstructor(nativePrototype); - var GeneratedWrapper = createWrapperConstructor(parentWrapperConstructor); - registerInternal(nativePrototype, GeneratedWrapper, opt_instance); - return GeneratedWrapper; - } - function addForwardingProperties(nativePrototype, wrapperPrototype) { - installProperty(nativePrototype, wrapperPrototype, true); - } - function registerInstanceProperties(wrapperPrototype, instanceObject) { - installProperty(instanceObject, wrapperPrototype, false); - } - var isFirefox = /Firefox/.test(navigator.userAgent); - var dummyDescriptor = { - get: function() {}, - set: function(v) {}, - configurable: true, - enumerable: true - }; - function isEventHandlerName(name) { - return /^on[a-z]+$/.test(name); - } - function isIdentifierName(name) { - return /^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(name); - } - function getGetter(name) { - return hasEval && isIdentifierName(name) ? new Function("return this.__impl4cf1e782hg__." + name) : function() { - return this.__impl4cf1e782hg__[name]; - }; - } - function getSetter(name) { - return hasEval && isIdentifierName(name) ? new Function("v", "this.__impl4cf1e782hg__." + name + " = v") : function(v) { - this.__impl4cf1e782hg__[name] = v; - }; - } - function getMethod(name) { - return hasEval && isIdentifierName(name) ? new Function("return this.__impl4cf1e782hg__." + name + ".apply(this.__impl4cf1e782hg__, arguments)") : function() { - return this.__impl4cf1e782hg__[name].apply(this.__impl4cf1e782hg__, arguments); - }; - } - function getDescriptor(source, name) { - try { - return Object.getOwnPropertyDescriptor(source, name); - } catch (ex) { - return dummyDescriptor; - } - } - var isBrokenSafari = function() { - var descr = Object.getOwnPropertyDescriptor(Node.prototype, "nodeType"); - return descr && !descr.get && !descr.set; - }(); - function installProperty(source, target, allowMethod, opt_blacklist) { - var names = getOwnPropertyNames(source); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - if (name === "polymerBlackList_") continue; - if (name in target) continue; - if (source.polymerBlackList_ && source.polymerBlackList_[name]) continue; - if (isFirefox) { - source.__lookupGetter__(name); - } - var descriptor = getDescriptor(source, name); - var getter, setter; - if (typeof descriptor.value === "function") { - if (allowMethod) { - target[name] = getMethod(name); - } - continue; - } - var isEvent = isEventHandlerName(name); - if (isEvent) getter = scope.getEventHandlerGetter(name); else getter = getGetter(name); - if (descriptor.writable || descriptor.set || isBrokenSafari) { - if (isEvent) setter = scope.getEventHandlerSetter(name); else setter = getSetter(name); - } - var configurable = isBrokenSafari || descriptor.configurable; - defineProperty(target, name, { - get: getter, - set: setter, - configurable: configurable, - enumerable: descriptor.enumerable - }); - } - } - function register(nativeConstructor, wrapperConstructor, opt_instance) { - if (nativeConstructor == null) { - return; - } - var nativePrototype = nativeConstructor.prototype; - registerInternal(nativePrototype, wrapperConstructor, opt_instance); - mixinStatics(wrapperConstructor, nativeConstructor); - } - function registerInternal(nativePrototype, wrapperConstructor, opt_instance) { - var wrapperPrototype = wrapperConstructor.prototype; - assert(constructorTable.get(nativePrototype) === undefined); - constructorTable.set(nativePrototype, wrapperConstructor); - nativePrototypeTable.set(wrapperPrototype, nativePrototype); - addForwardingProperties(nativePrototype, wrapperPrototype); - if (opt_instance) registerInstanceProperties(wrapperPrototype, opt_instance); - defineNonEnumerableDataProperty(wrapperPrototype, "constructor", wrapperConstructor); - wrapperConstructor.prototype = wrapperPrototype; - } - function isWrapperFor(wrapperConstructor, nativeConstructor) { - return constructorTable.get(nativeConstructor.prototype) === wrapperConstructor; - } - function registerObject(object) { - var nativePrototype = Object.getPrototypeOf(object); - var superWrapperConstructor = getWrapperConstructor(nativePrototype); - var GeneratedWrapper = createWrapperConstructor(superWrapperConstructor); - registerInternal(nativePrototype, GeneratedWrapper, object); - return GeneratedWrapper; - } - function createWrapperConstructor(superWrapperConstructor) { - function GeneratedWrapper(node) { - superWrapperConstructor.call(this, node); - } - var p = Object.create(superWrapperConstructor.prototype); - p.constructor = GeneratedWrapper; - GeneratedWrapper.prototype = p; - return GeneratedWrapper; - } - function isWrapper(object) { - return object && object.__impl4cf1e782hg__; - } - function isNative(object) { - return !isWrapper(object); - } - function wrap(impl) { - if (impl === null) return null; - assert(isNative(impl)); - var wrapper = impl.__wrapper8e3dd93a60__; - if (wrapper != null) { - return wrapper; - } - return impl.__wrapper8e3dd93a60__ = new (getWrapperConstructor(impl, impl))(impl); - } - function unwrap(wrapper) { - if (wrapper === null) return null; - assert(isWrapper(wrapper)); - return wrapper.__impl4cf1e782hg__; - } - function unsafeUnwrap(wrapper) { - return wrapper.__impl4cf1e782hg__; - } - function setWrapper(impl, wrapper) { - wrapper.__impl4cf1e782hg__ = impl; - impl.__wrapper8e3dd93a60__ = wrapper; - } - function unwrapIfNeeded(object) { - return object && isWrapper(object) ? unwrap(object) : object; - } - function wrapIfNeeded(object) { - return object && !isWrapper(object) ? wrap(object) : object; - } - function rewrap(node, wrapper) { - if (wrapper === null) return; - assert(isNative(node)); - assert(wrapper === undefined || isWrapper(wrapper)); - node.__wrapper8e3dd93a60__ = wrapper; - } - var getterDescriptor = { - get: undefined, - configurable: true, - enumerable: true - }; - function defineGetter(constructor, name, getter) { - getterDescriptor.get = getter; - defineProperty(constructor.prototype, name, getterDescriptor); - } - function defineWrapGetter(constructor, name) { - defineGetter(constructor, name, function() { - return wrap(this.__impl4cf1e782hg__[name]); - }); - } - function forwardMethodsToWrapper(constructors, names) { - constructors.forEach(function(constructor) { - names.forEach(function(name) { - constructor.prototype[name] = function() { - var w = wrapIfNeeded(this); - return w[name].apply(w, arguments); - }; - }); - }); - } - scope.addForwardingProperties = addForwardingProperties; - scope.assert = assert; - scope.constructorTable = constructorTable; - scope.defineGetter = defineGetter; - scope.defineWrapGetter = defineWrapGetter; - scope.forwardMethodsToWrapper = forwardMethodsToWrapper; - scope.isIdentifierName = isIdentifierName; - scope.isWrapper = isWrapper; - scope.isWrapperFor = isWrapperFor; - scope.mixin = mixin; - scope.nativePrototypeTable = nativePrototypeTable; - scope.oneOf = oneOf; - scope.registerObject = registerObject; - scope.registerWrapper = register; - scope.rewrap = rewrap; - scope.setWrapper = setWrapper; - scope.unsafeUnwrap = unsafeUnwrap; - scope.unwrap = unwrap; - scope.unwrapIfNeeded = unwrapIfNeeded; - scope.wrap = wrap; - scope.wrapIfNeeded = wrapIfNeeded; - scope.wrappers = wrappers; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - function newSplice(index, removed, addedCount) { - return { - index: index, - removed: removed, - addedCount: addedCount - }; - } - var EDIT_LEAVE = 0; - var EDIT_UPDATE = 1; - var EDIT_ADD = 2; - var EDIT_DELETE = 3; - function ArraySplice() {} - ArraySplice.prototype = { - calcEditDistances: function(current, currentStart, currentEnd, old, oldStart, oldEnd) { - var rowCount = oldEnd - oldStart + 1; - var columnCount = currentEnd - currentStart + 1; - var distances = new Array(rowCount); - for (var i = 0; i < rowCount; i++) { - distances[i] = new Array(columnCount); - distances[i][0] = i; - } - for (var j = 0; j < columnCount; j++) distances[0][j] = j; - for (var i = 1; i < rowCount; i++) { - for (var j = 1; j < columnCount; j++) { - if (this.equals(current[currentStart + j - 1], old[oldStart + i - 1])) distances[i][j] = distances[i - 1][j - 1]; else { - var north = distances[i - 1][j] + 1; - var west = distances[i][j - 1] + 1; - distances[i][j] = north < west ? north : west; - } - } - } - return distances; - }, - spliceOperationsFromEditDistances: function(distances) { - var i = distances.length - 1; - var j = distances[0].length - 1; - var current = distances[i][j]; - var edits = []; - while (i > 0 || j > 0) { - if (i == 0) { - edits.push(EDIT_ADD); - j--; - continue; - } - if (j == 0) { - edits.push(EDIT_DELETE); - i--; - continue; - } - var northWest = distances[i - 1][j - 1]; - var west = distances[i - 1][j]; - var north = distances[i][j - 1]; - var min; - if (west < north) min = west < northWest ? west : northWest; else min = north < northWest ? north : northWest; - if (min == northWest) { - if (northWest == current) { - edits.push(EDIT_LEAVE); - } else { - edits.push(EDIT_UPDATE); - current = northWest; - } - i--; - j--; - } else if (min == west) { - edits.push(EDIT_DELETE); - i--; - current = west; - } else { - edits.push(EDIT_ADD); - j--; - current = north; - } - } - edits.reverse(); - return edits; - }, - calcSplices: function(current, currentStart, currentEnd, old, oldStart, oldEnd) { - var prefixCount = 0; - var suffixCount = 0; - var minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart); - if (currentStart == 0 && oldStart == 0) prefixCount = this.sharedPrefix(current, old, minLength); - if (currentEnd == current.length && oldEnd == old.length) suffixCount = this.sharedSuffix(current, old, minLength - prefixCount); - currentStart += prefixCount; - oldStart += prefixCount; - currentEnd -= suffixCount; - oldEnd -= suffixCount; - if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0) return []; - if (currentStart == currentEnd) { - var splice = newSplice(currentStart, [], 0); - while (oldStart < oldEnd) splice.removed.push(old[oldStart++]); - return [ splice ]; - } else if (oldStart == oldEnd) return [ newSplice(currentStart, [], currentEnd - currentStart) ]; - var ops = this.spliceOperationsFromEditDistances(this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd)); - var splice = undefined; - var splices = []; - var index = currentStart; - var oldIndex = oldStart; - for (var i = 0; i < ops.length; i++) { - switch (ops[i]) { - case EDIT_LEAVE: - if (splice) { - splices.push(splice); - splice = undefined; - } - index++; - oldIndex++; - break; - - case EDIT_UPDATE: - if (!splice) splice = newSplice(index, [], 0); - splice.addedCount++; - index++; - splice.removed.push(old[oldIndex]); - oldIndex++; - break; - - case EDIT_ADD: - if (!splice) splice = newSplice(index, [], 0); - splice.addedCount++; - index++; - break; - - case EDIT_DELETE: - if (!splice) splice = newSplice(index, [], 0); - splice.removed.push(old[oldIndex]); - oldIndex++; - break; - } - } - if (splice) { - splices.push(splice); - } - return splices; - }, - sharedPrefix: function(current, old, searchLength) { - for (var i = 0; i < searchLength; i++) if (!this.equals(current[i], old[i])) return i; - return searchLength; - }, - sharedSuffix: function(current, old, searchLength) { - var index1 = current.length; - var index2 = old.length; - var count = 0; - while (count < searchLength && this.equals(current[--index1], old[--index2])) count++; - return count; - }, - calculateSplices: function(current, previous) { - return this.calcSplices(current, 0, current.length, previous, 0, previous.length); - }, - equals: function(currentValue, previousValue) { - return currentValue === previousValue; - } - }; - scope.ArraySplice = ArraySplice; - })(window.ShadowDOMPolyfill); - (function(context) { - "use strict"; - var OriginalMutationObserver = window.MutationObserver; - var callbacks = []; - var pending = false; - var timerFunc; - function handle() { - pending = false; - var copies = callbacks.slice(0); - callbacks = []; - for (var i = 0; i < copies.length; i++) { - (0, copies[i])(); - } - } - if (OriginalMutationObserver) { - var counter = 1; - var observer = new OriginalMutationObserver(handle); - var textNode = document.createTextNode(counter); - observer.observe(textNode, { - characterData: true - }); - timerFunc = function() { - counter = (counter + 1) % 2; - textNode.data = counter; - }; - } else { - timerFunc = window.setTimeout; - } - function setEndOfMicrotask(func) { - callbacks.push(func); - if (pending) return; - pending = true; - timerFunc(handle, 0); - } - context.setEndOfMicrotask = setEndOfMicrotask; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var setEndOfMicrotask = scope.setEndOfMicrotask; - var wrapIfNeeded = scope.wrapIfNeeded; - var wrappers = scope.wrappers; - var registrationsTable = new WeakMap(); - var globalMutationObservers = []; - var isScheduled = false; - function scheduleCallback(observer) { - if (observer.scheduled_) return; - observer.scheduled_ = true; - globalMutationObservers.push(observer); - if (isScheduled) return; - setEndOfMicrotask(notifyObservers); - isScheduled = true; - } - function notifyObservers() { - isScheduled = false; - while (globalMutationObservers.length) { - var notifyList = globalMutationObservers; - globalMutationObservers = []; - notifyList.sort(function(x, y) { - return x.uid_ - y.uid_; - }); - for (var i = 0; i < notifyList.length; i++) { - var mo = notifyList[i]; - mo.scheduled_ = false; - var queue = mo.takeRecords(); - removeTransientObserversFor(mo); - if (queue.length) { - mo.callback_(queue, mo); - } - } - } - } - function MutationRecord(type, target) { - this.type = type; - this.target = target; - this.addedNodes = new wrappers.NodeList(); - this.removedNodes = new wrappers.NodeList(); - this.previousSibling = null; - this.nextSibling = null; - this.attributeName = null; - this.attributeNamespace = null; - this.oldValue = null; - } - function registerTransientObservers(ancestor, node) { - for (;ancestor; ancestor = ancestor.parentNode) { - var registrations = registrationsTable.get(ancestor); - if (!registrations) continue; - for (var i = 0; i < registrations.length; i++) { - var registration = registrations[i]; - if (registration.options.subtree) registration.addTransientObserver(node); - } - } - } - function removeTransientObserversFor(observer) { - for (var i = 0; i < observer.nodes_.length; i++) { - var node = observer.nodes_[i]; - var registrations = registrationsTable.get(node); - if (!registrations) return; - for (var j = 0; j < registrations.length; j++) { - var registration = registrations[j]; - if (registration.observer === observer) registration.removeTransientObservers(); - } - } - } - function enqueueMutation(target, type, data) { - var interestedObservers = Object.create(null); - var associatedStrings = Object.create(null); - for (var node = target; node; node = node.parentNode) { - var registrations = registrationsTable.get(node); - if (!registrations) continue; - for (var j = 0; j < registrations.length; j++) { - var registration = registrations[j]; - var options = registration.options; - if (node !== target && !options.subtree) continue; - if (type === "attributes" && !options.attributes) continue; - if (type === "attributes" && options.attributeFilter && (data.namespace !== null || options.attributeFilter.indexOf(data.name) === -1)) { - continue; - } - if (type === "characterData" && !options.characterData) continue; - if (type === "childList" && !options.childList) continue; - var observer = registration.observer; - interestedObservers[observer.uid_] = observer; - if (type === "attributes" && options.attributeOldValue || type === "characterData" && options.characterDataOldValue) { - associatedStrings[observer.uid_] = data.oldValue; - } - } - } - for (var uid in interestedObservers) { - var observer = interestedObservers[uid]; - var record = new MutationRecord(type, target); - if ("name" in data && "namespace" in data) { - record.attributeName = data.name; - record.attributeNamespace = data.namespace; - } - if (data.addedNodes) record.addedNodes = data.addedNodes; - if (data.removedNodes) record.removedNodes = data.removedNodes; - if (data.previousSibling) record.previousSibling = data.previousSibling; - if (data.nextSibling) record.nextSibling = data.nextSibling; - if (associatedStrings[uid] !== undefined) record.oldValue = associatedStrings[uid]; - scheduleCallback(observer); - observer.records_.push(record); - } - } - var slice = Array.prototype.slice; - function MutationObserverOptions(options) { - this.childList = !!options.childList; - this.subtree = !!options.subtree; - if (!("attributes" in options) && ("attributeOldValue" in options || "attributeFilter" in options)) { - this.attributes = true; - } else { - this.attributes = !!options.attributes; - } - if ("characterDataOldValue" in options && !("characterData" in options)) this.characterData = true; else this.characterData = !!options.characterData; - if (!this.attributes && (options.attributeOldValue || "attributeFilter" in options) || !this.characterData && options.characterDataOldValue) { - throw new TypeError(); - } - this.characterData = !!options.characterData; - this.attributeOldValue = !!options.attributeOldValue; - this.characterDataOldValue = !!options.characterDataOldValue; - if ("attributeFilter" in options) { - if (options.attributeFilter == null || typeof options.attributeFilter !== "object") { - throw new TypeError(); - } - this.attributeFilter = slice.call(options.attributeFilter); - } else { - this.attributeFilter = null; - } - } - var uidCounter = 0; - function MutationObserver(callback) { - this.callback_ = callback; - this.nodes_ = []; - this.records_ = []; - this.uid_ = ++uidCounter; - this.scheduled_ = false; - } - MutationObserver.prototype = { - constructor: MutationObserver, - observe: function(target, options) { - target = wrapIfNeeded(target); - var newOptions = new MutationObserverOptions(options); - var registration; - var registrations = registrationsTable.get(target); - if (!registrations) registrationsTable.set(target, registrations = []); - for (var i = 0; i < registrations.length; i++) { - if (registrations[i].observer === this) { - registration = registrations[i]; - registration.removeTransientObservers(); - registration.options = newOptions; - } - } - if (!registration) { - registration = new Registration(this, target, newOptions); - registrations.push(registration); - this.nodes_.push(target); - } - }, - 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) { - registrations.splice(i, 1); - break; - } - } - }, this); - this.records_ = []; - }, - takeRecords: function() { - var copyOfRecords = this.records_; - this.records_ = []; - return copyOfRecords; - } - }; - function Registration(observer, target, options) { - this.observer = observer; - this.target = target; - this.options = options; - this.transientObservedNodes = []; - } - Registration.prototype = { - addTransientObserver: function(node) { - if (node === this.target) return; - scheduleCallback(this.observer); - 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 = []; - for (var i = 0; i < transientObservedNodes.length; i++) { - var node = transientObservedNodes[i]; - var registrations = registrationsTable.get(node); - for (var j = 0; j < registrations.length; j++) { - if (registrations[j] === this) { - registrations.splice(j, 1); - break; - } - } - } - } - }; - scope.enqueueMutation = enqueueMutation; - scope.registerTransientObservers = registerTransientObservers; - scope.wrappers.MutationObserver = MutationObserver; - scope.wrappers.MutationRecord = MutationRecord; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - function TreeScope(root, parent) { - this.root = root; - this.parent = parent; - } - TreeScope.prototype = { - get renderer() { - if (this.root instanceof scope.wrappers.ShadowRoot) { - return scope.getRendererForHost(this.root.host); - } - return null; - }, - contains: function(treeScope) { - for (;treeScope; treeScope = treeScope.parent) { - if (treeScope === this) return true; - } - return false; - } - }; - function setTreeScope(node, treeScope) { - if (node.treeScope_ !== treeScope) { - node.treeScope_ = treeScope; - for (var sr = node.shadowRoot; sr; sr = sr.olderShadowRoot) { - sr.treeScope_.parent = treeScope; - } - for (var child = node.firstChild; child; child = child.nextSibling) { - setTreeScope(child, treeScope); - } - } - } - function getTreeScope(node) { - if (node instanceof scope.wrappers.Window) { - debugger; - } - if (node.treeScope_) return node.treeScope_; - var parent = node.parentNode; - var treeScope; - if (parent) treeScope = getTreeScope(parent); else treeScope = new TreeScope(node, null); - return node.treeScope_ = treeScope; - } - scope.TreeScope = TreeScope; - scope.getTreeScope = getTreeScope; - scope.setTreeScope = setTreeScope; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var forwardMethodsToWrapper = scope.forwardMethodsToWrapper; - var getTreeScope = scope.getTreeScope; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var wrappers = scope.wrappers; - var wrappedFuns = new WeakMap(); - var listenersTable = new WeakMap(); - var handledEventsTable = new WeakMap(); - var currentlyDispatchingEvents = new WeakMap(); - var targetTable = new WeakMap(); - var currentTargetTable = new WeakMap(); - var relatedTargetTable = new WeakMap(); - var eventPhaseTable = new WeakMap(); - var stopPropagationTable = new WeakMap(); - var stopImmediatePropagationTable = new WeakMap(); - var eventHandlersTable = new WeakMap(); - var eventPathTable = new WeakMap(); - function isShadowRoot(node) { - return node instanceof wrappers.ShadowRoot; - } - function rootOfNode(node) { - return getTreeScope(node).root; - } - function getEventPath(node, event) { - var path = []; - var current = node; - path.push(current); - while (current) { - var destinationInsertionPoints = getDestinationInsertionPoints(current); - if (destinationInsertionPoints && destinationInsertionPoints.length > 0) { - for (var i = 0; i < destinationInsertionPoints.length; i++) { - var insertionPoint = destinationInsertionPoints[i]; - if (isShadowInsertionPoint(insertionPoint)) { - var shadowRoot = rootOfNode(insertionPoint); - var olderShadowRoot = shadowRoot.olderShadowRoot; - if (olderShadowRoot) path.push(olderShadowRoot); - } - path.push(insertionPoint); - } - current = destinationInsertionPoints[destinationInsertionPoints.length - 1]; - } else { - if (isShadowRoot(current)) { - if (inSameTree(node, current) && eventMustBeStopped(event)) { - break; - } - current = current.host; - path.push(current); - } else { - current = current.parentNode; - if (current) path.push(current); - } - } - } - return path; - } - function eventMustBeStopped(event) { - if (!event) return false; - switch (event.type) { - case "abort": - case "error": - case "select": - case "change": - case "load": - case "reset": - case "resize": - case "scroll": - case "selectstart": - return true; - } - return false; - } - function isShadowInsertionPoint(node) { - return node instanceof HTMLShadowElement; - } - function getDestinationInsertionPoints(node) { - return scope.getDestinationInsertionPoints(node); - } - function eventRetargetting(path, currentTarget) { - if (path.length === 0) return currentTarget; - if (currentTarget instanceof wrappers.Window) currentTarget = currentTarget.document; - var currentTargetTree = getTreeScope(currentTarget); - var originalTarget = path[0]; - var originalTargetTree = getTreeScope(originalTarget); - var relativeTargetTree = lowestCommonInclusiveAncestor(currentTargetTree, originalTargetTree); - for (var i = 0; i < path.length; i++) { - var node = path[i]; - if (getTreeScope(node) === relativeTargetTree) return node; - } - return path[path.length - 1]; - } - function getTreeScopeAncestors(treeScope) { - var ancestors = []; - for (;treeScope; treeScope = treeScope.parent) { - ancestors.push(treeScope); - } - return ancestors; - } - function lowestCommonInclusiveAncestor(tsA, tsB) { - var ancestorsA = getTreeScopeAncestors(tsA); - var ancestorsB = getTreeScopeAncestors(tsB); - var result = null; - while (ancestorsA.length > 0 && ancestorsB.length > 0) { - var a = ancestorsA.pop(); - var b = ancestorsB.pop(); - if (a === b) result = a; else break; - } - return result; - } - function getTreeScopeRoot(ts) { - if (!ts.parent) return ts; - return getTreeScopeRoot(ts.parent); - } - function relatedTargetResolution(event, currentTarget, relatedTarget) { - if (currentTarget instanceof wrappers.Window) currentTarget = currentTarget.document; - var currentTargetTree = getTreeScope(currentTarget); - var relatedTargetTree = getTreeScope(relatedTarget); - var relatedTargetEventPath = getEventPath(relatedTarget, event); - var lowestCommonAncestorTree; - var lowestCommonAncestorTree = lowestCommonInclusiveAncestor(currentTargetTree, relatedTargetTree); - if (!lowestCommonAncestorTree) lowestCommonAncestorTree = relatedTargetTree.root; - for (var commonAncestorTree = lowestCommonAncestorTree; commonAncestorTree; commonAncestorTree = commonAncestorTree.parent) { - var adjustedRelatedTarget; - for (var i = 0; i < relatedTargetEventPath.length; i++) { - var node = relatedTargetEventPath[i]; - if (getTreeScope(node) === commonAncestorTree) return node; - } - } - return null; - } - function inSameTree(a, b) { - return getTreeScope(a) === getTreeScope(b); - } - var NONE = 0; - var CAPTURING_PHASE = 1; - var AT_TARGET = 2; - var BUBBLING_PHASE = 3; - var pendingError; - function dispatchOriginalEvent(originalEvent) { - if (handledEventsTable.get(originalEvent)) return; - handledEventsTable.set(originalEvent, true); - dispatchEvent(wrap(originalEvent), wrap(originalEvent.target)); - if (pendingError) { - var err = pendingError; - pendingError = null; - throw err; - } - } - function isLoadLikeEvent(event) { - switch (event.type) { - case "load": - case "beforeunload": - case "unload": - return true; - } - return false; - } - function dispatchEvent(event, originalWrapperTarget) { - if (currentlyDispatchingEvents.get(event)) throw new Error("InvalidStateError"); - currentlyDispatchingEvents.set(event, true); - scope.renderAllPending(); - var eventPath; - var overrideTarget; - var win; - if (isLoadLikeEvent(event) && !event.bubbles) { - var doc = originalWrapperTarget; - if (doc instanceof wrappers.Document && (win = doc.defaultView)) { - overrideTarget = doc; - eventPath = []; - } - } - if (!eventPath) { - if (originalWrapperTarget instanceof wrappers.Window) { - win = originalWrapperTarget; - eventPath = []; - } else { - eventPath = getEventPath(originalWrapperTarget, event); - if (!isLoadLikeEvent(event)) { - var doc = eventPath[eventPath.length - 1]; - if (doc instanceof wrappers.Document) win = doc.defaultView; - } - } - } - eventPathTable.set(event, eventPath); - if (dispatchCapturing(event, eventPath, win, overrideTarget)) { - if (dispatchAtTarget(event, eventPath, win, overrideTarget)) { - dispatchBubbling(event, eventPath, win, overrideTarget); - } - } - eventPhaseTable.set(event, NONE); - currentTargetTable.delete(event, null); - currentlyDispatchingEvents.delete(event); - return event.defaultPrevented; - } - function dispatchCapturing(event, eventPath, win, overrideTarget) { - var phase = CAPTURING_PHASE; - if (win) { - if (!invoke(win, event, phase, eventPath, overrideTarget)) return false; - } - for (var i = eventPath.length - 1; i > 0; i--) { - if (!invoke(eventPath[i], event, phase, eventPath, overrideTarget)) return false; - } - return true; - } - function dispatchAtTarget(event, eventPath, win, overrideTarget) { - var phase = AT_TARGET; - var currentTarget = eventPath[0] || win; - return invoke(currentTarget, event, phase, eventPath, overrideTarget); - } - function dispatchBubbling(event, eventPath, win, overrideTarget) { - var phase = BUBBLING_PHASE; - for (var i = 1; i < eventPath.length; i++) { - if (!invoke(eventPath[i], event, phase, eventPath, overrideTarget)) return; - } - if (win && eventPath.length > 0) { - invoke(win, event, phase, eventPath, overrideTarget); - } - } - function invoke(currentTarget, event, phase, eventPath, overrideTarget) { - var listeners = listenersTable.get(currentTarget); - if (!listeners) return true; - var target = overrideTarget || eventRetargetting(eventPath, currentTarget); - if (target === currentTarget) { - if (phase === CAPTURING_PHASE) return true; - if (phase === BUBBLING_PHASE) phase = AT_TARGET; - } else if (phase === BUBBLING_PHASE && !event.bubbles) { - return true; - } - if ("relatedTarget" in event) { - var originalEvent = unwrap(event); - var unwrappedRelatedTarget = originalEvent.relatedTarget; - if (unwrappedRelatedTarget) { - if (unwrappedRelatedTarget instanceof Object && unwrappedRelatedTarget.addEventListener) { - var relatedTarget = wrap(unwrappedRelatedTarget); - var adjusted = relatedTargetResolution(event, currentTarget, relatedTarget); - if (adjusted === target) return true; - } else { - adjusted = null; - } - relatedTargetTable.set(event, adjusted); - } - } - eventPhaseTable.set(event, phase); - var type = event.type; - var anyRemoved = false; - targetTable.set(event, target); - currentTargetTable.set(event, currentTarget); - listeners.depth++; - for (var i = 0, len = listeners.length; i < len; i++) { - var listener = listeners[i]; - if (listener.removed) { - anyRemoved = true; - continue; - } - if (listener.type !== type || !listener.capture && phase === CAPTURING_PHASE || listener.capture && phase === BUBBLING_PHASE) { - continue; - } - try { - if (typeof listener.handler === "function") listener.handler.call(currentTarget, event); else listener.handler.handleEvent(event); - if (stopImmediatePropagationTable.get(event)) return false; - } catch (ex) { - if (!pendingError) pendingError = ex; - } - } - listeners.depth--; - if (anyRemoved && listeners.depth === 0) { - var copy = listeners.slice(); - listeners.length = 0; - for (var i = 0; i < copy.length; i++) { - if (!copy[i].removed) listeners.push(copy[i]); - } - } - return !stopPropagationTable.get(event); - } - function Listener(type, handler, capture) { - this.type = type; - this.handler = handler; - this.capture = Boolean(capture); - } - Listener.prototype = { - equals: function(that) { - return this.handler === that.handler && this.type === that.type && this.capture === that.capture; - }, - get removed() { - return this.handler === null; - }, - remove: function() { - this.handler = null; - } - }; - var OriginalEvent = window.Event; - OriginalEvent.prototype.polymerBlackList_ = { - returnValue: true, - keyLocation: true - }; - function Event(type, options) { - if (type instanceof OriginalEvent) { - var impl = type; - if (!OriginalBeforeUnloadEvent && impl.type === "beforeunload" && !(this instanceof BeforeUnloadEvent)) { - return new BeforeUnloadEvent(impl); - } - setWrapper(impl, this); - } else { - return wrap(constructEvent(OriginalEvent, "Event", type, options)); - } - } - Event.prototype = { - get target() { - return targetTable.get(this); - }, - get currentTarget() { - return currentTargetTable.get(this); - }, - get eventPhase() { - return eventPhaseTable.get(this); - }, - get path() { - var eventPath = eventPathTable.get(this); - if (!eventPath) return []; - return eventPath.slice(); - }, - stopPropagation: function() { - stopPropagationTable.set(this, true); - }, - stopImmediatePropagation: function() { - stopPropagationTable.set(this, true); - stopImmediatePropagationTable.set(this, true); - } - }; - var supportsDefaultPrevented = function() { - var e = document.createEvent("Event"); - e.initEvent("test", true, true); - e.preventDefault(); - return e.defaultPrevented; - }(); - if (!supportsDefaultPrevented) { - Event.prototype.preventDefault = function() { - if (!this.cancelable) return; - unsafeUnwrap(this).preventDefault(); - Object.defineProperty(this, "defaultPrevented", { - get: function() { - return true; - }, - configurable: true - }); - }; - } - registerWrapper(OriginalEvent, Event, document.createEvent("Event")); - function unwrapOptions(options) { - if (!options || !options.relatedTarget) return options; - return Object.create(options, { - relatedTarget: { - value: unwrap(options.relatedTarget) - } - }); - } - function registerGenericEvent(name, SuperEvent, prototype) { - var OriginalEvent = window[name]; - var GenericEvent = function(type, options) { - if (type instanceof OriginalEvent) setWrapper(type, this); else return wrap(constructEvent(OriginalEvent, name, type, options)); - }; - GenericEvent.prototype = Object.create(SuperEvent.prototype); - if (prototype) mixin(GenericEvent.prototype, prototype); - if (OriginalEvent) { - try { - registerWrapper(OriginalEvent, GenericEvent, new OriginalEvent("temp")); - } catch (ex) { - registerWrapper(OriginalEvent, GenericEvent, document.createEvent(name)); - } - } - return GenericEvent; - } - var UIEvent = registerGenericEvent("UIEvent", Event); - var CustomEvent = registerGenericEvent("CustomEvent", Event); - var relatedTargetProto = { - get relatedTarget() { - var relatedTarget = relatedTargetTable.get(this); - if (relatedTarget !== undefined) return relatedTarget; - return wrap(unwrap(this).relatedTarget); - } - }; - function getInitFunction(name, relatedTargetIndex) { - return function() { - arguments[relatedTargetIndex] = unwrap(arguments[relatedTargetIndex]); - var impl = unwrap(this); - impl[name].apply(impl, arguments); - }; - } - var mouseEventProto = mixin({ - initMouseEvent: getInitFunction("initMouseEvent", 14) - }, relatedTargetProto); - var focusEventProto = mixin({ - initFocusEvent: getInitFunction("initFocusEvent", 5) - }, relatedTargetProto); - var MouseEvent = registerGenericEvent("MouseEvent", UIEvent, mouseEventProto); - var FocusEvent = registerGenericEvent("FocusEvent", UIEvent, focusEventProto); - var defaultInitDicts = Object.create(null); - var supportsEventConstructors = function() { - try { - new window.FocusEvent("focus"); - } catch (ex) { - return false; - } - return true; - }(); - function constructEvent(OriginalEvent, name, type, options) { - if (supportsEventConstructors) return new OriginalEvent(type, unwrapOptions(options)); - var event = unwrap(document.createEvent(name)); - var defaultDict = defaultInitDicts[name]; - var args = [ type ]; - Object.keys(defaultDict).forEach(function(key) { - var v = options != null && key in options ? options[key] : defaultDict[key]; - if (key === "relatedTarget") v = unwrap(v); - args.push(v); - }); - event["init" + name].apply(event, args); - return event; - } - if (!supportsEventConstructors) { - var configureEventConstructor = function(name, initDict, superName) { - if (superName) { - var superDict = defaultInitDicts[superName]; - initDict = mixin(mixin({}, superDict), initDict); - } - defaultInitDicts[name] = initDict; - }; - configureEventConstructor("Event", { - bubbles: false, - cancelable: false - }); - configureEventConstructor("CustomEvent", { - detail: null - }, "Event"); - configureEventConstructor("UIEvent", { - view: null, - detail: 0 - }, "Event"); - configureEventConstructor("MouseEvent", { - screenX: 0, - screenY: 0, - clientX: 0, - clientY: 0, - ctrlKey: false, - altKey: false, - shiftKey: false, - metaKey: false, - button: 0, - relatedTarget: null - }, "UIEvent"); - configureEventConstructor("FocusEvent", { - relatedTarget: null - }, "UIEvent"); - } - var OriginalBeforeUnloadEvent = window.BeforeUnloadEvent; - function BeforeUnloadEvent(impl) { - Event.call(this, impl); - } - BeforeUnloadEvent.prototype = Object.create(Event.prototype); - mixin(BeforeUnloadEvent.prototype, { - get returnValue() { - return unsafeUnwrap(this).returnValue; - }, - set returnValue(v) { - unsafeUnwrap(this).returnValue = v; - } - }); - if (OriginalBeforeUnloadEvent) registerWrapper(OriginalBeforeUnloadEvent, BeforeUnloadEvent); - function isValidListener(fun) { - if (typeof fun === "function") return true; - return fun && fun.handleEvent; - } - function isMutationEvent(type) { - switch (type) { - case "DOMAttrModified": - case "DOMAttributeNameChanged": - case "DOMCharacterDataModified": - case "DOMElementNameChanged": - case "DOMNodeInserted": - case "DOMNodeInsertedIntoDocument": - case "DOMNodeRemoved": - case "DOMNodeRemovedFromDocument": - case "DOMSubtreeModified": - return true; - } - return false; - } - var OriginalEventTarget = window.EventTarget; - function EventTarget(impl) { - setWrapper(impl, this); - } - var methodNames = [ "addEventListener", "removeEventListener", "dispatchEvent" ]; - [ Node, Window ].forEach(function(constructor) { - var p = constructor.prototype; - methodNames.forEach(function(name) { - Object.defineProperty(p, name + "_", { - value: p[name] - }); - }); - }); - function getTargetToListenAt(wrapper) { - if (wrapper instanceof wrappers.ShadowRoot) wrapper = wrapper.host; - return unwrap(wrapper); - } - EventTarget.prototype = { - addEventListener: function(type, fun, capture) { - if (!isValidListener(fun) || isMutationEvent(type)) return; - var listener = new Listener(type, fun, capture); - var listeners = listenersTable.get(this); - if (!listeners) { - listeners = []; - listeners.depth = 0; - listenersTable.set(this, listeners); - } else { - for (var i = 0; i < listeners.length; i++) { - if (listener.equals(listeners[i])) return; - } - } - listeners.push(listener); - var target = getTargetToListenAt(this); - target.addEventListener_(type, dispatchOriginalEvent, true); - }, - removeEventListener: function(type, fun, capture) { - capture = Boolean(capture); - var listeners = listenersTable.get(this); - if (!listeners) return; - var count = 0, found = false; - for (var i = 0; i < listeners.length; i++) { - if (listeners[i].type === type && listeners[i].capture === capture) { - count++; - if (listeners[i].handler === fun) { - found = true; - listeners[i].remove(); - } - } - } - if (found && count === 1) { - var target = getTargetToListenAt(this); - target.removeEventListener_(type, dispatchOriginalEvent, true); - } - }, - dispatchEvent: function(event) { - var nativeEvent = unwrap(event); - var eventType = nativeEvent.type; - handledEventsTable.set(nativeEvent, false); - scope.renderAllPending(); - var tempListener; - if (!hasListenerInAncestors(this, eventType)) { - tempListener = function() {}; - this.addEventListener(eventType, tempListener, true); - } - try { - return unwrap(this).dispatchEvent_(nativeEvent); - } finally { - if (tempListener) this.removeEventListener(eventType, tempListener, true); - } - } - }; - function hasListener(node, type) { - var listeners = listenersTable.get(node); - if (listeners) { - for (var i = 0; i < listeners.length; i++) { - if (!listeners[i].removed && listeners[i].type === type) return true; - } - } - return false; - } - function hasListenerInAncestors(target, type) { - for (var node = unwrap(target); node; node = node.parentNode) { - if (hasListener(wrap(node), type)) return true; - } - return false; - } - if (OriginalEventTarget) registerWrapper(OriginalEventTarget, EventTarget); - function wrapEventTargetMethods(constructors) { - forwardMethodsToWrapper(constructors, methodNames); - } - var originalElementFromPoint = document.elementFromPoint; - function elementFromPoint(self, document, x, y) { - scope.renderAllPending(); - var element = wrap(originalElementFromPoint.call(unsafeUnwrap(document), x, y)); - if (!element) return null; - var path = getEventPath(element, null); - var idx = path.lastIndexOf(self); - if (idx == -1) return null; else path = path.slice(0, idx); - return eventRetargetting(path, self); - } - function getEventHandlerGetter(name) { - return function() { - var inlineEventHandlers = eventHandlersTable.get(this); - return inlineEventHandlers && inlineEventHandlers[name] && inlineEventHandlers[name].value || null; - }; - } - function getEventHandlerSetter(name) { - var eventType = name.slice(2); - return function(value) { - var inlineEventHandlers = eventHandlersTable.get(this); - if (!inlineEventHandlers) { - inlineEventHandlers = Object.create(null); - eventHandlersTable.set(this, inlineEventHandlers); - } - var old = inlineEventHandlers[name]; - if (old) this.removeEventListener(eventType, old.wrapped, false); - if (typeof value === "function") { - var wrapped = function(e) { - var rv = value.call(this, e); - if (rv === false) e.preventDefault(); else if (name === "onbeforeunload" && typeof rv === "string") e.returnValue = rv; - }; - this.addEventListener(eventType, wrapped, false); - inlineEventHandlers[name] = { - value: value, - wrapped: wrapped - }; - } - }; - } - scope.elementFromPoint = elementFromPoint; - scope.getEventHandlerGetter = getEventHandlerGetter; - scope.getEventHandlerSetter = getEventHandlerSetter; - scope.wrapEventTargetMethods = wrapEventTargetMethods; - scope.wrappers.BeforeUnloadEvent = BeforeUnloadEvent; - scope.wrappers.CustomEvent = CustomEvent; - scope.wrappers.Event = Event; - scope.wrappers.EventTarget = EventTarget; - scope.wrappers.FocusEvent = FocusEvent; - scope.wrappers.MouseEvent = MouseEvent; - scope.wrappers.UIEvent = UIEvent; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var UIEvent = scope.wrappers.UIEvent; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrap = scope.wrap; - var OriginalTouchEvent = window.TouchEvent; - if (!OriginalTouchEvent) return; - var nativeEvent; - try { - nativeEvent = document.createEvent("TouchEvent"); - } catch (ex) { - return; - } - var nonEnumDescriptor = { - enumerable: false - }; - function nonEnum(obj, prop) { - Object.defineProperty(obj, prop, nonEnumDescriptor); - } - function Touch(impl) { - setWrapper(impl, this); - } - Touch.prototype = { - get target() { - return wrap(unsafeUnwrap(this).target); - } - }; - var descr = { - configurable: true, - enumerable: true, - get: null - }; - [ "clientX", "clientY", "screenX", "screenY", "pageX", "pageY", "identifier", "webkitRadiusX", "webkitRadiusY", "webkitRotationAngle", "webkitForce" ].forEach(function(name) { - descr.get = function() { - return unsafeUnwrap(this)[name]; - }; - Object.defineProperty(Touch.prototype, name, descr); - }); - function TouchList() { - this.length = 0; - nonEnum(this, "length"); - } - TouchList.prototype = { - item: function(index) { - return this[index]; - } - }; - function wrapTouchList(nativeTouchList) { - var list = new TouchList(); - for (var i = 0; i < nativeTouchList.length; i++) { - list[i] = new Touch(nativeTouchList[i]); - } - list.length = i; - return list; - } - function TouchEvent(impl) { - UIEvent.call(this, impl); - } - TouchEvent.prototype = Object.create(UIEvent.prototype); - mixin(TouchEvent.prototype, { - get touches() { - return wrapTouchList(unsafeUnwrap(this).touches); - }, - get targetTouches() { - return wrapTouchList(unsafeUnwrap(this).targetTouches); - }, - get changedTouches() { - return wrapTouchList(unsafeUnwrap(this).changedTouches); - }, - initTouchEvent: function() { - throw new Error("Not implemented"); - } - }); - registerWrapper(OriginalTouchEvent, TouchEvent, nativeEvent); - scope.wrappers.Touch = Touch; - scope.wrappers.TouchEvent = TouchEvent; - scope.wrappers.TouchList = TouchList; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrap = scope.wrap; - var nonEnumDescriptor = { - enumerable: false - }; - function nonEnum(obj, prop) { - Object.defineProperty(obj, prop, nonEnumDescriptor); - } - function NodeList() { - this.length = 0; - nonEnum(this, "length"); - } - NodeList.prototype = { - item: function(index) { - return this[index]; - } - }; - nonEnum(NodeList.prototype, "item"); - function wrapNodeList(list) { - if (list == null) return list; - var wrapperList = new NodeList(); - for (var i = 0, length = list.length; i < length; i++) { - wrapperList[i] = wrap(list[i]); - } - wrapperList.length = length; - return wrapperList; - } - function addWrapNodeListMethod(wrapperConstructor, name) { - wrapperConstructor.prototype[name] = function() { - return wrapNodeList(unsafeUnwrap(this)[name].apply(unsafeUnwrap(this), arguments)); - }; - } - scope.wrappers.NodeList = NodeList; - scope.addWrapNodeListMethod = addWrapNodeListMethod; - scope.wrapNodeList = wrapNodeList; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - scope.wrapHTMLCollection = scope.wrapNodeList; - scope.wrappers.HTMLCollection = scope.wrappers.NodeList; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var EventTarget = scope.wrappers.EventTarget; - var NodeList = scope.wrappers.NodeList; - var TreeScope = scope.TreeScope; - var assert = scope.assert; - var defineWrapGetter = scope.defineWrapGetter; - var enqueueMutation = scope.enqueueMutation; - var getTreeScope = scope.getTreeScope; - var isWrapper = scope.isWrapper; - var mixin = scope.mixin; - var registerTransientObservers = scope.registerTransientObservers; - var registerWrapper = scope.registerWrapper; - var setTreeScope = scope.setTreeScope; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var wrapIfNeeded = scope.wrapIfNeeded; - var wrappers = scope.wrappers; - function assertIsNodeWrapper(node) { - assert(node instanceof Node); - } - function createOneElementNodeList(node) { - var nodes = new NodeList(); - nodes[0] = node; - nodes.length = 1; - return nodes; - } - var surpressMutations = false; - function enqueueRemovalForInsertedNodes(node, parent, nodes) { - enqueueMutation(parent, "childList", { - removedNodes: nodes, - previousSibling: node.previousSibling, - nextSibling: node.nextSibling - }); - } - function enqueueRemovalForInsertedDocumentFragment(df, nodes) { - enqueueMutation(df, "childList", { - removedNodes: nodes - }); - } - function collectNodes(node, parentNode, previousNode, nextNode) { - if (node instanceof DocumentFragment) { - var nodes = collectNodesForDocumentFragment(node); - surpressMutations = true; - for (var i = nodes.length - 1; i >= 0; i--) { - node.removeChild(nodes[i]); - nodes[i].parentNode_ = parentNode; - } - surpressMutations = false; - for (var i = 0; i < nodes.length; i++) { - nodes[i].previousSibling_ = nodes[i - 1] || previousNode; - nodes[i].nextSibling_ = nodes[i + 1] || nextNode; - } - if (previousNode) previousNode.nextSibling_ = nodes[0]; - if (nextNode) nextNode.previousSibling_ = nodes[nodes.length - 1]; - return nodes; - } - var nodes = createOneElementNodeList(node); - var oldParent = node.parentNode; - if (oldParent) { - oldParent.removeChild(node); - } - node.parentNode_ = parentNode; - node.previousSibling_ = previousNode; - node.nextSibling_ = nextNode; - if (previousNode) previousNode.nextSibling_ = node; - if (nextNode) nextNode.previousSibling_ = node; - return nodes; - } - function collectNodesNative(node) { - if (node instanceof DocumentFragment) return collectNodesForDocumentFragment(node); - var nodes = createOneElementNodeList(node); - var oldParent = node.parentNode; - if (oldParent) enqueueRemovalForInsertedNodes(node, oldParent, nodes); - return nodes; - } - function collectNodesForDocumentFragment(node) { - var nodes = new NodeList(); - var i = 0; - for (var child = node.firstChild; child; child = child.nextSibling) { - nodes[i++] = child; - } - nodes.length = i; - enqueueRemovalForInsertedDocumentFragment(node, nodes); - return nodes; - } - function snapshotNodeList(nodeList) { - return nodeList; - } - function nodeWasAdded(node, treeScope) { - setTreeScope(node, treeScope); - node.nodeIsInserted_(); - } - function nodesWereAdded(nodes, parent) { - var treeScope = getTreeScope(parent); - for (var i = 0; i < nodes.length; i++) { - nodeWasAdded(nodes[i], treeScope); - } - } - function nodeWasRemoved(node) { - setTreeScope(node, new TreeScope(node, null)); - } - function nodesWereRemoved(nodes) { - for (var i = 0; i < nodes.length; i++) { - nodeWasRemoved(nodes[i]); - } - } - function ensureSameOwnerDocument(parent, child) { - var ownerDoc = parent.nodeType === Node.DOCUMENT_NODE ? parent : parent.ownerDocument; - if (ownerDoc !== child.ownerDocument) ownerDoc.adoptNode(child); - } - function adoptNodesIfNeeded(owner, nodes) { - if (!nodes.length) return; - var ownerDoc = owner.ownerDocument; - if (ownerDoc === nodes[0].ownerDocument) return; - for (var i = 0; i < nodes.length; i++) { - scope.adoptNodeNoRemove(nodes[i], ownerDoc); - } - } - function unwrapNodesForInsertion(owner, nodes) { - adoptNodesIfNeeded(owner, nodes); - var length = nodes.length; - if (length === 1) return unwrap(nodes[0]); - var df = unwrap(owner.ownerDocument.createDocumentFragment()); - for (var i = 0; i < length; i++) { - df.appendChild(unwrap(nodes[i])); - } - return df; - } - function clearChildNodes(wrapper) { - if (wrapper.firstChild_ !== undefined) { - var child = wrapper.firstChild_; - while (child) { - var tmp = child; - child = child.nextSibling_; - tmp.parentNode_ = tmp.previousSibling_ = tmp.nextSibling_ = undefined; - } - } - wrapper.firstChild_ = wrapper.lastChild_ = undefined; - } - function removeAllChildNodes(wrapper) { - if (wrapper.invalidateShadowRenderer()) { - var childWrapper = wrapper.firstChild; - while (childWrapper) { - assert(childWrapper.parentNode === wrapper); - var nextSibling = childWrapper.nextSibling; - var childNode = unwrap(childWrapper); - var parentNode = childNode.parentNode; - if (parentNode) originalRemoveChild.call(parentNode, childNode); - childWrapper.previousSibling_ = childWrapper.nextSibling_ = childWrapper.parentNode_ = null; - childWrapper = nextSibling; - } - wrapper.firstChild_ = wrapper.lastChild_ = null; - } else { - var node = unwrap(wrapper); - var child = node.firstChild; - var nextSibling; - while (child) { - nextSibling = child.nextSibling; - originalRemoveChild.call(node, child); - child = nextSibling; - } - } - } - function invalidateParent(node) { - var p = node.parentNode; - return p && p.invalidateShadowRenderer(); - } - function cleanupNodes(nodes) { - for (var i = 0, n; i < nodes.length; i++) { - n = nodes[i]; - n.parentNode.removeChild(n); - } - } - var originalImportNode = document.importNode; - var originalCloneNode = window.Node.prototype.cloneNode; - function cloneNode(node, deep, opt_doc) { - var clone; - if (opt_doc) clone = wrap(originalImportNode.call(opt_doc, unsafeUnwrap(node), false)); else clone = wrap(originalCloneNode.call(unsafeUnwrap(node), false)); - if (deep) { - for (var child = node.firstChild; child; child = child.nextSibling) { - clone.appendChild(cloneNode(child, true, opt_doc)); - } - if (node instanceof wrappers.HTMLTemplateElement) { - var cloneContent = clone.content; - for (var child = node.content.firstChild; child; child = child.nextSibling) { - cloneContent.appendChild(cloneNode(child, true, opt_doc)); - } - } - } - return clone; - } - function contains(self, child) { - if (!child || getTreeScope(self) !== getTreeScope(child)) return false; - for (var node = child; node; node = node.parentNode) { - if (node === self) return true; - } - return false; - } - var OriginalNode = window.Node; - function Node(original) { - assert(original instanceof OriginalNode); - EventTarget.call(this, original); - this.parentNode_ = undefined; - this.firstChild_ = undefined; - this.lastChild_ = undefined; - this.nextSibling_ = undefined; - this.previousSibling_ = undefined; - this.treeScope_ = undefined; - } - var OriginalDocumentFragment = window.DocumentFragment; - var originalAppendChild = OriginalNode.prototype.appendChild; - var originalCompareDocumentPosition = OriginalNode.prototype.compareDocumentPosition; - var originalIsEqualNode = OriginalNode.prototype.isEqualNode; - var originalInsertBefore = OriginalNode.prototype.insertBefore; - var originalRemoveChild = OriginalNode.prototype.removeChild; - var originalReplaceChild = OriginalNode.prototype.replaceChild; - var isIEOrEdge = /Trident|Edge/.test(navigator.userAgent); - var removeChildOriginalHelper = isIEOrEdge ? function(parent, child) { - try { - originalRemoveChild.call(parent, child); - } catch (ex) { - if (!(parent instanceof OriginalDocumentFragment)) throw ex; - } - } : function(parent, child) { - originalRemoveChild.call(parent, child); - }; - Node.prototype = Object.create(EventTarget.prototype); - mixin(Node.prototype, { - appendChild: function(childWrapper) { - return this.insertBefore(childWrapper, null); - }, - insertBefore: function(childWrapper, refWrapper) { - assertIsNodeWrapper(childWrapper); - var refNode; - if (refWrapper) { - if (isWrapper(refWrapper)) { - refNode = unwrap(refWrapper); - } else { - refNode = refWrapper; - refWrapper = wrap(refNode); - } - } else { - refWrapper = null; - refNode = null; - } - refWrapper && assert(refWrapper.parentNode === this); - var nodes; - var previousNode = refWrapper ? refWrapper.previousSibling : this.lastChild; - var useNative = !this.invalidateShadowRenderer() && !invalidateParent(childWrapper); - if (useNative) nodes = collectNodesNative(childWrapper); else nodes = collectNodes(childWrapper, this, previousNode, refWrapper); - if (useNative) { - ensureSameOwnerDocument(this, childWrapper); - clearChildNodes(this); - originalInsertBefore.call(unsafeUnwrap(this), unwrap(childWrapper), refNode); - } else { - if (!previousNode) this.firstChild_ = nodes[0]; - if (!refWrapper) { - this.lastChild_ = nodes[nodes.length - 1]; - if (this.firstChild_ === undefined) this.firstChild_ = this.firstChild; - } - var parentNode = refNode ? refNode.parentNode : unsafeUnwrap(this); - if (parentNode) { - originalInsertBefore.call(parentNode, unwrapNodesForInsertion(this, nodes), refNode); - } else { - adoptNodesIfNeeded(this, nodes); - } - } - enqueueMutation(this, "childList", { - addedNodes: nodes, - nextSibling: refWrapper, - previousSibling: previousNode - }); - nodesWereAdded(nodes, this); - return childWrapper; - }, - removeChild: function(childWrapper) { - assertIsNodeWrapper(childWrapper); - if (childWrapper.parentNode !== this) { - var found = false; - var childNodes = this.childNodes; - for (var ieChild = this.firstChild; ieChild; ieChild = ieChild.nextSibling) { - if (ieChild === childWrapper) { - found = true; - break; - } - } - if (!found) { - throw new Error("NotFoundError"); - } - } - var childNode = unwrap(childWrapper); - var childWrapperNextSibling = childWrapper.nextSibling; - var childWrapperPreviousSibling = childWrapper.previousSibling; - if (this.invalidateShadowRenderer()) { - var thisFirstChild = this.firstChild; - var thisLastChild = this.lastChild; - var parentNode = childNode.parentNode; - if (parentNode) removeChildOriginalHelper(parentNode, childNode); - if (thisFirstChild === childWrapper) this.firstChild_ = childWrapperNextSibling; - if (thisLastChild === childWrapper) this.lastChild_ = childWrapperPreviousSibling; - if (childWrapperPreviousSibling) childWrapperPreviousSibling.nextSibling_ = childWrapperNextSibling; - if (childWrapperNextSibling) { - childWrapperNextSibling.previousSibling_ = childWrapperPreviousSibling; - } - childWrapper.previousSibling_ = childWrapper.nextSibling_ = childWrapper.parentNode_ = undefined; - } else { - clearChildNodes(this); - removeChildOriginalHelper(unsafeUnwrap(this), childNode); - } - if (!surpressMutations) { - enqueueMutation(this, "childList", { - removedNodes: createOneElementNodeList(childWrapper), - nextSibling: childWrapperNextSibling, - previousSibling: childWrapperPreviousSibling - }); - } - registerTransientObservers(this, childWrapper); - return childWrapper; - }, - replaceChild: function(newChildWrapper, oldChildWrapper) { - assertIsNodeWrapper(newChildWrapper); - var oldChildNode; - if (isWrapper(oldChildWrapper)) { - oldChildNode = unwrap(oldChildWrapper); - } else { - oldChildNode = oldChildWrapper; - oldChildWrapper = wrap(oldChildNode); - } - if (oldChildWrapper.parentNode !== this) { - throw new Error("NotFoundError"); - } - var nextNode = oldChildWrapper.nextSibling; - var previousNode = oldChildWrapper.previousSibling; - var nodes; - var useNative = !this.invalidateShadowRenderer() && !invalidateParent(newChildWrapper); - if (useNative) { - nodes = collectNodesNative(newChildWrapper); - } else { - if (nextNode === newChildWrapper) nextNode = newChildWrapper.nextSibling; - nodes = collectNodes(newChildWrapper, this, previousNode, nextNode); - } - if (!useNative) { - if (this.firstChild === oldChildWrapper) this.firstChild_ = nodes[0]; - if (this.lastChild === oldChildWrapper) this.lastChild_ = nodes[nodes.length - 1]; - oldChildWrapper.previousSibling_ = oldChildWrapper.nextSibling_ = oldChildWrapper.parentNode_ = undefined; - if (oldChildNode.parentNode) { - originalReplaceChild.call(oldChildNode.parentNode, unwrapNodesForInsertion(this, nodes), oldChildNode); - } - } else { - ensureSameOwnerDocument(this, newChildWrapper); - clearChildNodes(this); - originalReplaceChild.call(unsafeUnwrap(this), unwrap(newChildWrapper), oldChildNode); - } - enqueueMutation(this, "childList", { - addedNodes: nodes, - removedNodes: createOneElementNodeList(oldChildWrapper), - nextSibling: nextNode, - previousSibling: previousNode - }); - nodeWasRemoved(oldChildWrapper); - nodesWereAdded(nodes, this); - return oldChildWrapper; - }, - nodeIsInserted_: function() { - for (var child = this.firstChild; child; child = child.nextSibling) { - child.nodeIsInserted_(); - } - }, - hasChildNodes: function() { - return this.firstChild !== null; - }, - get parentNode() { - return this.parentNode_ !== undefined ? this.parentNode_ : wrap(unsafeUnwrap(this).parentNode); - }, - get firstChild() { - return this.firstChild_ !== undefined ? this.firstChild_ : wrap(unsafeUnwrap(this).firstChild); - }, - get lastChild() { - return this.lastChild_ !== undefined ? this.lastChild_ : wrap(unsafeUnwrap(this).lastChild); - }, - get nextSibling() { - return this.nextSibling_ !== undefined ? this.nextSibling_ : wrap(unsafeUnwrap(this).nextSibling); - }, - get previousSibling() { - return this.previousSibling_ !== undefined ? this.previousSibling_ : wrap(unsafeUnwrap(this).previousSibling); - }, - get parentElement() { - var p = this.parentNode; - while (p && p.nodeType !== Node.ELEMENT_NODE) { - p = p.parentNode; - } - return p; - }, - get textContent() { - var s = ""; - for (var child = this.firstChild; child; child = child.nextSibling) { - if (child.nodeType != Node.COMMENT_NODE) { - s += child.textContent; - } - } - return s; - }, - set textContent(textContent) { - if (textContent == null) textContent = ""; - var removedNodes = snapshotNodeList(this.childNodes); - if (this.invalidateShadowRenderer()) { - removeAllChildNodes(this); - if (textContent !== "") { - var textNode = unsafeUnwrap(this).ownerDocument.createTextNode(textContent); - this.appendChild(textNode); - } - } else { - clearChildNodes(this); - unsafeUnwrap(this).textContent = textContent; - } - var addedNodes = snapshotNodeList(this.childNodes); - enqueueMutation(this, "childList", { - addedNodes: addedNodes, - removedNodes: removedNodes - }); - nodesWereRemoved(removedNodes); - nodesWereAdded(addedNodes, this); - }, - get childNodes() { - var wrapperList = new NodeList(); - var i = 0; - for (var child = this.firstChild; child; child = child.nextSibling) { - wrapperList[i++] = child; - } - wrapperList.length = i; - return wrapperList; - }, - cloneNode: function(deep) { - return cloneNode(this, deep); - }, - contains: function(child) { - return contains(this, wrapIfNeeded(child)); - }, - compareDocumentPosition: function(otherNode) { - return originalCompareDocumentPosition.call(unsafeUnwrap(this), unwrapIfNeeded(otherNode)); - }, - isEqualNode: function(otherNode) { - return originalIsEqualNode.call(unsafeUnwrap(this), unwrapIfNeeded(otherNode)); - }, - normalize: function() { - var nodes = snapshotNodeList(this.childNodes); - var remNodes = []; - var s = ""; - var modNode; - for (var i = 0, n; i < nodes.length; i++) { - n = nodes[i]; - if (n.nodeType === Node.TEXT_NODE) { - if (!modNode && !n.data.length) this.removeChild(n); else if (!modNode) modNode = n; else { - s += n.data; - remNodes.push(n); - } - } else { - if (modNode && remNodes.length) { - modNode.data += s; - cleanupNodes(remNodes); - } - remNodes = []; - s = ""; - modNode = null; - if (n.childNodes.length) n.normalize(); - } - } - if (modNode && remNodes.length) { - modNode.data += s; - cleanupNodes(remNodes); - } - } - }); - defineWrapGetter(Node, "ownerDocument"); - registerWrapper(OriginalNode, Node, document.createDocumentFragment()); - delete Node.prototype.querySelector; - delete Node.prototype.querySelectorAll; - Node.prototype = mixin(Object.create(EventTarget.prototype), Node.prototype); - scope.cloneNode = cloneNode; - scope.nodeWasAdded = nodeWasAdded; - scope.nodeWasRemoved = nodeWasRemoved; - scope.nodesWereAdded = nodesWereAdded; - scope.nodesWereRemoved = nodesWereRemoved; - scope.originalInsertBefore = originalInsertBefore; - scope.originalRemoveChild = originalRemoveChild; - scope.snapshotNodeList = snapshotNodeList; - scope.wrappers.Node = Node; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLCollection = scope.wrappers.HTMLCollection; - var NodeList = scope.wrappers.NodeList; - var getTreeScope = scope.getTreeScope; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrap = scope.wrap; - var originalDocumentQuerySelector = document.querySelector; - var originalElementQuerySelector = document.documentElement.querySelector; - var originalDocumentQuerySelectorAll = document.querySelectorAll; - var originalElementQuerySelectorAll = document.documentElement.querySelectorAll; - var originalDocumentGetElementsByTagName = document.getElementsByTagName; - var originalElementGetElementsByTagName = document.documentElement.getElementsByTagName; - var originalDocumentGetElementsByTagNameNS = document.getElementsByTagNameNS; - var originalElementGetElementsByTagNameNS = document.documentElement.getElementsByTagNameNS; - var OriginalElement = window.Element; - var OriginalDocument = window.HTMLDocument || window.Document; - function filterNodeList(list, index, result, deep) { - var wrappedItem = null; - var root = null; - for (var i = 0, length = list.length; i < length; i++) { - wrappedItem = wrap(list[i]); - if (!deep && (root = getTreeScope(wrappedItem).root)) { - if (root instanceof scope.wrappers.ShadowRoot) { - continue; - } - } - result[index++] = wrappedItem; - } - return index; - } - function shimSelector(selector) { - return String(selector).replace(/\/deep\/|::shadow|>>>/g, " "); - } - function shimMatchesSelector(selector) { - return String(selector).replace(/:host\(([^\s]+)\)/g, "$1").replace(/([^\s]):host/g, "$1").replace(":host", "*").replace(/\^|\/shadow\/|\/shadow-deep\/|::shadow|\/deep\/|::content|>>>/g, " "); - } - function findOne(node, selector) { - var m, el = node.firstElementChild; - while (el) { - if (el.matches(selector)) return el; - m = findOne(el, selector); - if (m) return m; - el = el.nextElementSibling; - } - return null; - } - function matchesSelector(el, selector) { - return el.matches(selector); - } - var XHTML_NS = "http://www.w3.org/1999/xhtml"; - function matchesTagName(el, localName, localNameLowerCase) { - var ln = el.localName; - return ln === localName || ln === localNameLowerCase && el.namespaceURI === XHTML_NS; - } - function matchesEveryThing() { - return true; - } - function matchesLocalNameOnly(el, ns, localName) { - return el.localName === localName; - } - function matchesNameSpace(el, ns) { - return el.namespaceURI === ns; - } - function matchesLocalNameNS(el, ns, localName) { - return el.namespaceURI === ns && el.localName === localName; - } - function findElements(node, index, result, p, arg0, arg1) { - var el = node.firstElementChild; - while (el) { - if (p(el, arg0, arg1)) result[index++] = el; - index = findElements(el, index, result, p, arg0, arg1); - el = el.nextElementSibling; - } - return index; - } - function querySelectorAllFiltered(p, index, result, selector, deep) { - var target = unsafeUnwrap(this); - var list; - var root = getTreeScope(this).root; - if (root instanceof scope.wrappers.ShadowRoot) { - return findElements(this, index, result, p, selector, null); - } else if (target instanceof OriginalElement) { - list = originalElementQuerySelectorAll.call(target, selector); - } else if (target instanceof OriginalDocument) { - list = originalDocumentQuerySelectorAll.call(target, selector); - } else { - return findElements(this, index, result, p, selector, null); - } - return filterNodeList(list, index, result, deep); - } - var SelectorsInterface = { - querySelector: function(selector) { - var shimmed = shimSelector(selector); - var deep = shimmed !== selector; - selector = shimmed; - var target = unsafeUnwrap(this); - var wrappedItem; - var root = getTreeScope(this).root; - if (root instanceof scope.wrappers.ShadowRoot) { - return findOne(this, selector); - } else if (target instanceof OriginalElement) { - wrappedItem = wrap(originalElementQuerySelector.call(target, selector)); - } else if (target instanceof OriginalDocument) { - wrappedItem = wrap(originalDocumentQuerySelector.call(target, selector)); - } else { - return findOne(this, selector); - } - if (!wrappedItem) { - return wrappedItem; - } else if (!deep && (root = getTreeScope(wrappedItem).root)) { - if (root instanceof scope.wrappers.ShadowRoot) { - return findOne(this, selector); - } - } - return wrappedItem; - }, - querySelectorAll: function(selector) { - var shimmed = shimSelector(selector); - var deep = shimmed !== selector; - selector = shimmed; - var result = new NodeList(); - result.length = querySelectorAllFiltered.call(this, matchesSelector, 0, result, selector, deep); - return result; - } - }; - var MatchesInterface = { - matches: function(selector) { - selector = shimMatchesSelector(selector); - return scope.originalMatches.call(unsafeUnwrap(this), selector); - } - }; - function getElementsByTagNameFiltered(p, index, result, localName, lowercase) { - var target = unsafeUnwrap(this); - var list; - var root = getTreeScope(this).root; - if (root instanceof scope.wrappers.ShadowRoot) { - return findElements(this, index, result, p, localName, lowercase); - } else if (target instanceof OriginalElement) { - list = originalElementGetElementsByTagName.call(target, localName, lowercase); - } else if (target instanceof OriginalDocument) { - list = originalDocumentGetElementsByTagName.call(target, localName, lowercase); - } else { - return findElements(this, index, result, p, localName, lowercase); - } - return filterNodeList(list, index, result, false); - } - function getElementsByTagNameNSFiltered(p, index, result, ns, localName) { - var target = unsafeUnwrap(this); - var list; - var root = getTreeScope(this).root; - if (root instanceof scope.wrappers.ShadowRoot) { - return findElements(this, index, result, p, ns, localName); - } else if (target instanceof OriginalElement) { - list = originalElementGetElementsByTagNameNS.call(target, ns, localName); - } else if (target instanceof OriginalDocument) { - list = originalDocumentGetElementsByTagNameNS.call(target, ns, localName); - } else { - return findElements(this, index, result, p, ns, localName); - } - return filterNodeList(list, index, result, false); - } - var GetElementsByInterface = { - getElementsByTagName: function(localName) { - var result = new HTMLCollection(); - var match = localName === "*" ? matchesEveryThing : matchesTagName; - result.length = getElementsByTagNameFiltered.call(this, match, 0, result, localName, localName.toLowerCase()); - return result; - }, - getElementsByClassName: function(className) { - return this.querySelectorAll("." + className); - }, - getElementsByTagNameNS: function(ns, localName) { - var result = new HTMLCollection(); - var match = null; - if (ns === "*") { - match = localName === "*" ? matchesEveryThing : matchesLocalNameOnly; - } else { - match = localName === "*" ? matchesNameSpace : matchesLocalNameNS; - } - result.length = getElementsByTagNameNSFiltered.call(this, match, 0, result, ns || null, localName); - return result; - } - }; - scope.GetElementsByInterface = GetElementsByInterface; - scope.SelectorsInterface = SelectorsInterface; - scope.MatchesInterface = MatchesInterface; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var NodeList = scope.wrappers.NodeList; - function forwardElement(node) { - while (node && node.nodeType !== Node.ELEMENT_NODE) { - node = node.nextSibling; - } - return node; - } - function backwardsElement(node) { - while (node && node.nodeType !== Node.ELEMENT_NODE) { - node = node.previousSibling; - } - return node; - } - var ParentNodeInterface = { - get firstElementChild() { - return forwardElement(this.firstChild); - }, - get lastElementChild() { - return backwardsElement(this.lastChild); - }, - get childElementCount() { - var count = 0; - for (var child = this.firstElementChild; child; child = child.nextElementSibling) { - count++; - } - return count; - }, - get children() { - var wrapperList = new NodeList(); - var i = 0; - for (var child = this.firstElementChild; child; child = child.nextElementSibling) { - wrapperList[i++] = child; - } - wrapperList.length = i; - return wrapperList; - }, - remove: function() { - var p = this.parentNode; - if (p) p.removeChild(this); - } - }; - var ChildNodeInterface = { - get nextElementSibling() { - return forwardElement(this.nextSibling); - }, - get previousElementSibling() { - return backwardsElement(this.previousSibling); - } - }; - var NonElementParentNodeInterface = { - getElementById: function(id) { - if (/[ \t\n\r\f]/.test(id)) return null; - return this.querySelector('[id="' + id + '"]'); - } - }; - scope.ChildNodeInterface = ChildNodeInterface; - scope.NonElementParentNodeInterface = NonElementParentNodeInterface; - scope.ParentNodeInterface = ParentNodeInterface; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var ChildNodeInterface = scope.ChildNodeInterface; - var Node = scope.wrappers.Node; - var enqueueMutation = scope.enqueueMutation; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var OriginalCharacterData = window.CharacterData; - function CharacterData(node) { - Node.call(this, node); - } - CharacterData.prototype = Object.create(Node.prototype); - mixin(CharacterData.prototype, { - get nodeValue() { - return this.data; - }, - set nodeValue(data) { - this.data = data; - }, - get textContent() { - return this.data; - }, - set textContent(value) { - this.data = value; - }, - get data() { - return unsafeUnwrap(this).data; - }, - set data(value) { - var oldValue = unsafeUnwrap(this).data; - enqueueMutation(this, "characterData", { - oldValue: oldValue - }); - unsafeUnwrap(this).data = value; - } - }); - mixin(CharacterData.prototype, ChildNodeInterface); - registerWrapper(OriginalCharacterData, CharacterData, document.createTextNode("")); - scope.wrappers.CharacterData = CharacterData; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var CharacterData = scope.wrappers.CharacterData; - var enqueueMutation = scope.enqueueMutation; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - function toUInt32(x) { - return x >>> 0; - } - var OriginalText = window.Text; - function Text(node) { - CharacterData.call(this, node); - } - Text.prototype = Object.create(CharacterData.prototype); - mixin(Text.prototype, { - splitText: function(offset) { - offset = toUInt32(offset); - var s = this.data; - if (offset > s.length) throw new Error("IndexSizeError"); - var head = s.slice(0, offset); - var tail = s.slice(offset); - this.data = head; - var newTextNode = this.ownerDocument.createTextNode(tail); - if (this.parentNode) this.parentNode.insertBefore(newTextNode, this.nextSibling); - return newTextNode; - } - }); - registerWrapper(OriginalText, Text, document.createTextNode("")); - scope.wrappers.Text = Text; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - if (!window.DOMTokenList) { - console.warn("Missing DOMTokenList prototype, please include a " + "compatible classList polyfill such as http://goo.gl/uTcepH."); - return; - } - var unsafeUnwrap = scope.unsafeUnwrap; - var enqueueMutation = scope.enqueueMutation; - function getClass(el) { - return unsafeUnwrap(el).getAttribute("class"); - } - function enqueueClassAttributeChange(el, oldValue) { - enqueueMutation(el, "attributes", { - name: "class", - namespace: null, - oldValue: oldValue - }); - } - function invalidateClass(el) { - scope.invalidateRendererBasedOnAttribute(el, "class"); - } - function changeClass(tokenList, method, args) { - var ownerElement = tokenList.ownerElement_; - if (ownerElement == null) { - return method.apply(tokenList, args); - } - var oldValue = getClass(ownerElement); - var retv = method.apply(tokenList, args); - if (getClass(ownerElement) !== oldValue) { - enqueueClassAttributeChange(ownerElement, oldValue); - invalidateClass(ownerElement); - } - return retv; - } - var oldAdd = DOMTokenList.prototype.add; - DOMTokenList.prototype.add = function() { - changeClass(this, oldAdd, arguments); - }; - var oldRemove = DOMTokenList.prototype.remove; - DOMTokenList.prototype.remove = function() { - changeClass(this, oldRemove, arguments); - }; - var oldToggle = DOMTokenList.prototype.toggle; - DOMTokenList.prototype.toggle = function() { - return changeClass(this, oldToggle, arguments); - }; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var ChildNodeInterface = scope.ChildNodeInterface; - var GetElementsByInterface = scope.GetElementsByInterface; - var Node = scope.wrappers.Node; - var ParentNodeInterface = scope.ParentNodeInterface; - var SelectorsInterface = scope.SelectorsInterface; - var MatchesInterface = scope.MatchesInterface; - var addWrapNodeListMethod = scope.addWrapNodeListMethod; - var enqueueMutation = scope.enqueueMutation; - var mixin = scope.mixin; - var oneOf = scope.oneOf; - var registerWrapper = scope.registerWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrappers = scope.wrappers; - var OriginalElement = window.Element; - var matchesNames = [ "matches", "mozMatchesSelector", "msMatchesSelector", "webkitMatchesSelector" ].filter(function(name) { - return OriginalElement.prototype[name]; - }); - var matchesName = matchesNames[0]; - var originalMatches = OriginalElement.prototype[matchesName]; - function invalidateRendererBasedOnAttribute(element, name) { - var p = element.parentNode; - if (!p || !p.shadowRoot) return; - var renderer = scope.getRendererForHost(p); - if (renderer.dependsOnAttribute(name)) renderer.invalidate(); - } - function enqueAttributeChange(element, name, oldValue) { - enqueueMutation(element, "attributes", { - name: name, - namespace: null, - oldValue: oldValue - }); - } - var classListTable = new WeakMap(); - function Element(node) { - Node.call(this, node); - } - Element.prototype = Object.create(Node.prototype); - mixin(Element.prototype, { - createShadowRoot: function() { - var newShadowRoot = new wrappers.ShadowRoot(this); - unsafeUnwrap(this).polymerShadowRoot_ = newShadowRoot; - var renderer = scope.getRendererForHost(this); - renderer.invalidate(); - return newShadowRoot; - }, - get shadowRoot() { - return unsafeUnwrap(this).polymerShadowRoot_ || null; - }, - setAttribute: function(name, value) { - var oldValue = unsafeUnwrap(this).getAttribute(name); - unsafeUnwrap(this).setAttribute(name, value); - enqueAttributeChange(this, name, oldValue); - invalidateRendererBasedOnAttribute(this, name); - }, - removeAttribute: function(name) { - var oldValue = unsafeUnwrap(this).getAttribute(name); - unsafeUnwrap(this).removeAttribute(name); - enqueAttributeChange(this, name, oldValue); - invalidateRendererBasedOnAttribute(this, name); - }, - get classList() { - var list = classListTable.get(this); - if (!list) { - list = unsafeUnwrap(this).classList; - if (!list) return; - list.ownerElement_ = this; - classListTable.set(this, list); - } - return list; - }, - get className() { - return unsafeUnwrap(this).className; - }, - set className(v) { - this.setAttribute("class", v); - }, - get id() { - return unsafeUnwrap(this).id; - }, - set id(v) { - this.setAttribute("id", v); - } - }); - matchesNames.forEach(function(name) { - if (name !== "matches") { - Element.prototype[name] = function(selector) { - return this.matches(selector); - }; - } - }); - if (OriginalElement.prototype.webkitCreateShadowRoot) { - Element.prototype.webkitCreateShadowRoot = Element.prototype.createShadowRoot; - } - mixin(Element.prototype, ChildNodeInterface); - mixin(Element.prototype, GetElementsByInterface); - mixin(Element.prototype, ParentNodeInterface); - mixin(Element.prototype, SelectorsInterface); - mixin(Element.prototype, MatchesInterface); - registerWrapper(OriginalElement, Element, document.createElementNS(null, "x")); - scope.invalidateRendererBasedOnAttribute = invalidateRendererBasedOnAttribute; - scope.matchesNames = matchesNames; - scope.originalMatches = originalMatches; - scope.wrappers.Element = Element; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var Element = scope.wrappers.Element; - var defineGetter = scope.defineGetter; - var enqueueMutation = scope.enqueueMutation; - var mixin = scope.mixin; - var nodesWereAdded = scope.nodesWereAdded; - var nodesWereRemoved = scope.nodesWereRemoved; - var registerWrapper = scope.registerWrapper; - var snapshotNodeList = scope.snapshotNodeList; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var wrappers = scope.wrappers; - var escapeAttrRegExp = /[&\u00A0"]/g; - var escapeDataRegExp = /[&\u00A0<>]/g; - function escapeReplace(c) { - switch (c) { - case "&": - return "&"; - - case "<": - return "<"; - - case ">": - return ">"; - - case '"': - return """; - - case " ": - return " "; - } - } - function escapeAttr(s) { - return s.replace(escapeAttrRegExp, escapeReplace); - } - function escapeData(s) { - return s.replace(escapeDataRegExp, escapeReplace); - } - function makeSet(arr) { - var set = {}; - for (var i = 0; i < arr.length; i++) { - set[arr[i]] = true; - } - return set; - } - var voidElements = makeSet([ "area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr" ]); - var plaintextParents = makeSet([ "style", "script", "xmp", "iframe", "noembed", "noframes", "plaintext", "noscript" ]); - var XHTML_NS = "http://www.w3.org/1999/xhtml"; - function needsSelfClosingSlash(node) { - if (node.namespaceURI !== XHTML_NS) return true; - var doctype = node.ownerDocument.doctype; - return doctype && doctype.publicId && doctype.systemId; - } - function getOuterHTML(node, parentNode) { - switch (node.nodeType) { - case Node.ELEMENT_NODE: - var tagName = node.tagName.toLowerCase(); - var s = "<" + tagName; - var attrs = node.attributes; - for (var i = 0, attr; attr = attrs[i]; i++) { - s += " " + attr.name + '="' + escapeAttr(attr.value) + '"'; - } - if (voidElements[tagName]) { - if (needsSelfClosingSlash(node)) s += "/"; - return s + ">"; - } - return s + ">" + getInnerHTML(node) + ""; - - case Node.TEXT_NODE: - var data = node.data; - if (parentNode && plaintextParents[parentNode.localName]) return data; - return escapeData(data); - - case Node.COMMENT_NODE: - return ""; - - default: - console.error(node); - throw new Error("not implemented"); - } - } - function getInnerHTML(node) { - if (node instanceof wrappers.HTMLTemplateElement) node = node.content; - var s = ""; - for (var child = node.firstChild; child; child = child.nextSibling) { - s += getOuterHTML(child, node); - } - return s; - } - function setInnerHTML(node, value, opt_tagName) { - var tagName = opt_tagName || "div"; - node.textContent = ""; - var tempElement = unwrap(node.ownerDocument.createElement(tagName)); - tempElement.innerHTML = value; - var firstChild; - while (firstChild = tempElement.firstChild) { - node.appendChild(wrap(firstChild)); - } - } - var oldIe = /MSIE/.test(navigator.userAgent); - var OriginalHTMLElement = window.HTMLElement; - var OriginalHTMLTemplateElement = window.HTMLTemplateElement; - function HTMLElement(node) { - Element.call(this, node); - } - HTMLElement.prototype = Object.create(Element.prototype); - mixin(HTMLElement.prototype, { - get innerHTML() { - return getInnerHTML(this); - }, - set innerHTML(value) { - if (oldIe && plaintextParents[this.localName]) { - this.textContent = value; - return; - } - var removedNodes = snapshotNodeList(this.childNodes); - if (this.invalidateShadowRenderer()) { - if (this instanceof wrappers.HTMLTemplateElement) setInnerHTML(this.content, value); else setInnerHTML(this, value, this.tagName); - } else if (!OriginalHTMLTemplateElement && this instanceof wrappers.HTMLTemplateElement) { - setInnerHTML(this.content, value); - } else { - unsafeUnwrap(this).innerHTML = value; - } - var addedNodes = snapshotNodeList(this.childNodes); - enqueueMutation(this, "childList", { - addedNodes: addedNodes, - removedNodes: removedNodes - }); - nodesWereRemoved(removedNodes); - nodesWereAdded(addedNodes, this); - }, - get outerHTML() { - return getOuterHTML(this, this.parentNode); - }, - set outerHTML(value) { - var p = this.parentNode; - if (p) { - p.invalidateShadowRenderer(); - var df = frag(p, value); - p.replaceChild(df, this); - } - }, - insertAdjacentHTML: function(position, text) { - var contextElement, refNode; - switch (String(position).toLowerCase()) { - case "beforebegin": - contextElement = this.parentNode; - refNode = this; - break; - - case "afterend": - contextElement = this.parentNode; - refNode = this.nextSibling; - break; - - case "afterbegin": - contextElement = this; - refNode = this.firstChild; - break; - - case "beforeend": - contextElement = this; - refNode = null; - break; - - default: - return; - } - var df = frag(contextElement, text); - contextElement.insertBefore(df, refNode); - }, - get hidden() { - return this.hasAttribute("hidden"); - }, - set hidden(v) { - if (v) { - this.setAttribute("hidden", ""); - } else { - this.removeAttribute("hidden"); - } - } - }); - function frag(contextElement, html) { - var p = unwrap(contextElement.cloneNode(false)); - p.innerHTML = html; - var df = unwrap(document.createDocumentFragment()); - var c; - while (c = p.firstChild) { - df.appendChild(c); - } - return wrap(df); - } - function getter(name) { - return function() { - scope.renderAllPending(); - return unsafeUnwrap(this)[name]; - }; - } - function getterRequiresRendering(name) { - defineGetter(HTMLElement, name, getter(name)); - } - [ "clientHeight", "clientLeft", "clientTop", "clientWidth", "offsetHeight", "offsetLeft", "offsetTop", "offsetWidth", "scrollHeight", "scrollWidth" ].forEach(getterRequiresRendering); - function getterAndSetterRequiresRendering(name) { - Object.defineProperty(HTMLElement.prototype, name, { - get: getter(name), - set: function(v) { - scope.renderAllPending(); - unsafeUnwrap(this)[name] = v; - }, - configurable: true, - enumerable: true - }); - } - [ "scrollLeft", "scrollTop" ].forEach(getterAndSetterRequiresRendering); - function methodRequiresRendering(name) { - Object.defineProperty(HTMLElement.prototype, name, { - value: function() { - scope.renderAllPending(); - return unsafeUnwrap(this)[name].apply(unsafeUnwrap(this), arguments); - }, - configurable: true, - enumerable: true - }); - } - [ "focus", "getBoundingClientRect", "getClientRects", "scrollIntoView" ].forEach(methodRequiresRendering); - registerWrapper(OriginalHTMLElement, HTMLElement, document.createElement("b")); - scope.wrappers.HTMLElement = HTMLElement; - scope.getInnerHTML = getInnerHTML; - scope.setInnerHTML = setInnerHTML; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrap = scope.wrap; - var OriginalHTMLCanvasElement = window.HTMLCanvasElement; - function HTMLCanvasElement(node) { - HTMLElement.call(this, node); - } - HTMLCanvasElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLCanvasElement.prototype, { - getContext: function() { - var context = unsafeUnwrap(this).getContext.apply(unsafeUnwrap(this), arguments); - return context && wrap(context); - } - }); - registerWrapper(OriginalHTMLCanvasElement, HTMLCanvasElement, document.createElement("canvas")); - scope.wrappers.HTMLCanvasElement = HTMLCanvasElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var OriginalHTMLContentElement = window.HTMLContentElement; - function HTMLContentElement(node) { - HTMLElement.call(this, node); - } - HTMLContentElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLContentElement.prototype, { - constructor: HTMLContentElement, - get select() { - return this.getAttribute("select"); - }, - set select(value) { - this.setAttribute("select", value); - }, - setAttribute: function(n, v) { - HTMLElement.prototype.setAttribute.call(this, n, v); - if (String(n).toLowerCase() === "select") this.invalidateShadowRenderer(true); - } - }); - if (OriginalHTMLContentElement) registerWrapper(OriginalHTMLContentElement, HTMLContentElement); - scope.wrappers.HTMLContentElement = HTMLContentElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var wrapHTMLCollection = scope.wrapHTMLCollection; - var unwrap = scope.unwrap; - var OriginalHTMLFormElement = window.HTMLFormElement; - function HTMLFormElement(node) { - HTMLElement.call(this, node); - } - HTMLFormElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLFormElement.prototype, { - get elements() { - return wrapHTMLCollection(unwrap(this).elements); - } - }); - registerWrapper(OriginalHTMLFormElement, HTMLFormElement, document.createElement("form")); - scope.wrappers.HTMLFormElement = HTMLFormElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var registerWrapper = scope.registerWrapper; - var unwrap = scope.unwrap; - var rewrap = scope.rewrap; - var OriginalHTMLImageElement = window.HTMLImageElement; - function HTMLImageElement(node) { - HTMLElement.call(this, node); - } - HTMLImageElement.prototype = Object.create(HTMLElement.prototype); - registerWrapper(OriginalHTMLImageElement, HTMLImageElement, document.createElement("img")); - function Image(width, height) { - if (!(this instanceof Image)) { - throw new TypeError("DOM object constructor cannot be called as a function."); - } - var node = unwrap(document.createElement("img")); - HTMLElement.call(this, node); - rewrap(node, this); - if (width !== undefined) node.width = width; - if (height !== undefined) node.height = height; - } - Image.prototype = HTMLImageElement.prototype; - scope.wrappers.HTMLImageElement = HTMLImageElement; - scope.wrappers.Image = Image; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var NodeList = scope.wrappers.NodeList; - var registerWrapper = scope.registerWrapper; - var OriginalHTMLShadowElement = window.HTMLShadowElement; - function HTMLShadowElement(node) { - HTMLElement.call(this, node); - } - HTMLShadowElement.prototype = Object.create(HTMLElement.prototype); - HTMLShadowElement.prototype.constructor = HTMLShadowElement; - if (OriginalHTMLShadowElement) registerWrapper(OriginalHTMLShadowElement, HTMLShadowElement); - scope.wrappers.HTMLShadowElement = HTMLShadowElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var contentTable = new WeakMap(); - var templateContentsOwnerTable = new WeakMap(); - function getTemplateContentsOwner(doc) { - if (!doc.defaultView) return doc; - var d = templateContentsOwnerTable.get(doc); - if (!d) { - d = doc.implementation.createHTMLDocument(""); - while (d.lastChild) { - d.removeChild(d.lastChild); - } - templateContentsOwnerTable.set(doc, d); - } - return d; - } - function extractContent(templateElement) { - var doc = getTemplateContentsOwner(templateElement.ownerDocument); - var df = unwrap(doc.createDocumentFragment()); - var child; - while (child = templateElement.firstChild) { - df.appendChild(child); - } - return df; - } - var OriginalHTMLTemplateElement = window.HTMLTemplateElement; - function HTMLTemplateElement(node) { - HTMLElement.call(this, node); - if (!OriginalHTMLTemplateElement) { - var content = extractContent(node); - contentTable.set(this, wrap(content)); - } - } - HTMLTemplateElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLTemplateElement.prototype, { - constructor: HTMLTemplateElement, - get content() { - if (OriginalHTMLTemplateElement) return wrap(unsafeUnwrap(this).content); - return contentTable.get(this); - } - }); - if (OriginalHTMLTemplateElement) registerWrapper(OriginalHTMLTemplateElement, HTMLTemplateElement); - scope.wrappers.HTMLTemplateElement = HTMLTemplateElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var registerWrapper = scope.registerWrapper; - var OriginalHTMLMediaElement = window.HTMLMediaElement; - if (!OriginalHTMLMediaElement) return; - function HTMLMediaElement(node) { - HTMLElement.call(this, node); - } - HTMLMediaElement.prototype = Object.create(HTMLElement.prototype); - registerWrapper(OriginalHTMLMediaElement, HTMLMediaElement, document.createElement("audio")); - scope.wrappers.HTMLMediaElement = HTMLMediaElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLMediaElement = scope.wrappers.HTMLMediaElement; - var registerWrapper = scope.registerWrapper; - var unwrap = scope.unwrap; - var rewrap = scope.rewrap; - var OriginalHTMLAudioElement = window.HTMLAudioElement; - if (!OriginalHTMLAudioElement) return; - function HTMLAudioElement(node) { - HTMLMediaElement.call(this, node); - } - HTMLAudioElement.prototype = Object.create(HTMLMediaElement.prototype); - registerWrapper(OriginalHTMLAudioElement, HTMLAudioElement, document.createElement("audio")); - function Audio(src) { - if (!(this instanceof Audio)) { - throw new TypeError("DOM object constructor cannot be called as a function."); - } - var node = unwrap(document.createElement("audio")); - HTMLMediaElement.call(this, node); - rewrap(node, this); - node.setAttribute("preload", "auto"); - if (src !== undefined) node.setAttribute("src", src); - } - Audio.prototype = HTMLAudioElement.prototype; - scope.wrappers.HTMLAudioElement = HTMLAudioElement; - scope.wrappers.Audio = Audio; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var rewrap = scope.rewrap; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var OriginalHTMLOptionElement = window.HTMLOptionElement; - function trimText(s) { - return s.replace(/\s+/g, " ").trim(); - } - function HTMLOptionElement(node) { - HTMLElement.call(this, node); - } - HTMLOptionElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLOptionElement.prototype, { - get text() { - return trimText(this.textContent); - }, - set text(value) { - this.textContent = trimText(String(value)); - }, - get form() { - return wrap(unwrap(this).form); - } - }); - registerWrapper(OriginalHTMLOptionElement, HTMLOptionElement, document.createElement("option")); - function Option(text, value, defaultSelected, selected) { - if (!(this instanceof Option)) { - throw new TypeError("DOM object constructor cannot be called as a function."); - } - var node = unwrap(document.createElement("option")); - HTMLElement.call(this, node); - rewrap(node, this); - if (text !== undefined) node.text = text; - if (value !== undefined) node.setAttribute("value", value); - if (defaultSelected === true) node.setAttribute("selected", ""); - node.selected = selected === true; - } - Option.prototype = HTMLOptionElement.prototype; - scope.wrappers.HTMLOptionElement = HTMLOptionElement; - scope.wrappers.Option = Option; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var OriginalHTMLSelectElement = window.HTMLSelectElement; - function HTMLSelectElement(node) { - HTMLElement.call(this, node); - } - HTMLSelectElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLSelectElement.prototype, { - add: function(element, before) { - if (typeof before === "object") before = unwrap(before); - unwrap(this).add(unwrap(element), before); - }, - remove: function(indexOrNode) { - if (indexOrNode === undefined) { - HTMLElement.prototype.remove.call(this); - return; - } - if (typeof indexOrNode === "object") indexOrNode = unwrap(indexOrNode); - unwrap(this).remove(indexOrNode); - }, - get form() { - return wrap(unwrap(this).form); - } - }); - registerWrapper(OriginalHTMLSelectElement, HTMLSelectElement, document.createElement("select")); - scope.wrappers.HTMLSelectElement = HTMLSelectElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var wrapHTMLCollection = scope.wrapHTMLCollection; - var OriginalHTMLTableElement = window.HTMLTableElement; - function HTMLTableElement(node) { - HTMLElement.call(this, node); - } - HTMLTableElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLTableElement.prototype, { - get caption() { - return wrap(unwrap(this).caption); - }, - createCaption: function() { - return wrap(unwrap(this).createCaption()); - }, - get tHead() { - return wrap(unwrap(this).tHead); - }, - createTHead: function() { - return wrap(unwrap(this).createTHead()); - }, - createTFoot: function() { - return wrap(unwrap(this).createTFoot()); - }, - get tFoot() { - return wrap(unwrap(this).tFoot); - }, - get tBodies() { - return wrapHTMLCollection(unwrap(this).tBodies); - }, - createTBody: function() { - return wrap(unwrap(this).createTBody()); - }, - get rows() { - return wrapHTMLCollection(unwrap(this).rows); - }, - insertRow: function(index) { - return wrap(unwrap(this).insertRow(index)); - } - }); - registerWrapper(OriginalHTMLTableElement, HTMLTableElement, document.createElement("table")); - scope.wrappers.HTMLTableElement = HTMLTableElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var wrapHTMLCollection = scope.wrapHTMLCollection; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var OriginalHTMLTableSectionElement = window.HTMLTableSectionElement; - function HTMLTableSectionElement(node) { - HTMLElement.call(this, node); - } - HTMLTableSectionElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLTableSectionElement.prototype, { - constructor: HTMLTableSectionElement, - get rows() { - return wrapHTMLCollection(unwrap(this).rows); - }, - insertRow: function(index) { - return wrap(unwrap(this).insertRow(index)); - } - }); - registerWrapper(OriginalHTMLTableSectionElement, HTMLTableSectionElement, document.createElement("thead")); - scope.wrappers.HTMLTableSectionElement = HTMLTableSectionElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var wrapHTMLCollection = scope.wrapHTMLCollection; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var OriginalHTMLTableRowElement = window.HTMLTableRowElement; - function HTMLTableRowElement(node) { - HTMLElement.call(this, node); - } - HTMLTableRowElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLTableRowElement.prototype, { - get cells() { - return wrapHTMLCollection(unwrap(this).cells); - }, - insertCell: function(index) { - return wrap(unwrap(this).insertCell(index)); - } - }); - registerWrapper(OriginalHTMLTableRowElement, HTMLTableRowElement, document.createElement("tr")); - scope.wrappers.HTMLTableRowElement = HTMLTableRowElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLContentElement = scope.wrappers.HTMLContentElement; - var HTMLElement = scope.wrappers.HTMLElement; - var HTMLShadowElement = scope.wrappers.HTMLShadowElement; - var HTMLTemplateElement = scope.wrappers.HTMLTemplateElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var OriginalHTMLUnknownElement = window.HTMLUnknownElement; - function HTMLUnknownElement(node) { - switch (node.localName) { - case "content": - return new HTMLContentElement(node); - - case "shadow": - return new HTMLShadowElement(node); - - case "template": - return new HTMLTemplateElement(node); - } - HTMLElement.call(this, node); - } - HTMLUnknownElement.prototype = Object.create(HTMLElement.prototype); - registerWrapper(OriginalHTMLUnknownElement, HTMLUnknownElement); - scope.wrappers.HTMLUnknownElement = HTMLUnknownElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var Element = scope.wrappers.Element; - var HTMLElement = scope.wrappers.HTMLElement; - var registerWrapper = scope.registerWrapper; - var defineWrapGetter = scope.defineWrapGetter; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrap = scope.wrap; - var mixin = scope.mixin; - var SVG_NS = "http://www.w3.org/2000/svg"; - var OriginalSVGElement = window.SVGElement; - var svgTitleElement = document.createElementNS(SVG_NS, "title"); - if (!("classList" in svgTitleElement)) { - var descr = Object.getOwnPropertyDescriptor(Element.prototype, "classList"); - Object.defineProperty(HTMLElement.prototype, "classList", descr); - delete Element.prototype.classList; - } - function SVGElement(node) { - Element.call(this, node); - } - SVGElement.prototype = Object.create(Element.prototype); - mixin(SVGElement.prototype, { - get ownerSVGElement() { - return wrap(unsafeUnwrap(this).ownerSVGElement); - } - }); - registerWrapper(OriginalSVGElement, SVGElement, document.createElementNS(SVG_NS, "title")); - scope.wrappers.SVGElement = SVGElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var OriginalSVGUseElement = window.SVGUseElement; - var SVG_NS = "http://www.w3.org/2000/svg"; - var gWrapper = wrap(document.createElementNS(SVG_NS, "g")); - var useElement = document.createElementNS(SVG_NS, "use"); - var SVGGElement = gWrapper.constructor; - var parentInterfacePrototype = Object.getPrototypeOf(SVGGElement.prototype); - var parentInterface = parentInterfacePrototype.constructor; - function SVGUseElement(impl) { - parentInterface.call(this, impl); - } - SVGUseElement.prototype = Object.create(parentInterfacePrototype); - if ("instanceRoot" in useElement) { - mixin(SVGUseElement.prototype, { - get instanceRoot() { - return wrap(unwrap(this).instanceRoot); - }, - get animatedInstanceRoot() { - return wrap(unwrap(this).animatedInstanceRoot); - } - }); - } - registerWrapper(OriginalSVGUseElement, SVGUseElement, useElement); - scope.wrappers.SVGUseElement = SVGUseElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var EventTarget = scope.wrappers.EventTarget; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrap = scope.wrap; - var OriginalSVGElementInstance = window.SVGElementInstance; - if (!OriginalSVGElementInstance) return; - function SVGElementInstance(impl) { - EventTarget.call(this, impl); - } - SVGElementInstance.prototype = Object.create(EventTarget.prototype); - mixin(SVGElementInstance.prototype, { - get correspondingElement() { - return wrap(unsafeUnwrap(this).correspondingElement); - }, - get correspondingUseElement() { - return wrap(unsafeUnwrap(this).correspondingUseElement); - }, - get parentNode() { - return wrap(unsafeUnwrap(this).parentNode); - }, - get childNodes() { - throw new Error("Not implemented"); - }, - get firstChild() { - return wrap(unsafeUnwrap(this).firstChild); - }, - get lastChild() { - return wrap(unsafeUnwrap(this).lastChild); - }, - get previousSibling() { - return wrap(unsafeUnwrap(this).previousSibling); - }, - get nextSibling() { - return wrap(unsafeUnwrap(this).nextSibling); - } - }); - registerWrapper(OriginalSVGElementInstance, SVGElementInstance); - scope.wrappers.SVGElementInstance = SVGElementInstance; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var OriginalCanvasRenderingContext2D = window.CanvasRenderingContext2D; - function CanvasRenderingContext2D(impl) { - setWrapper(impl, this); - } - mixin(CanvasRenderingContext2D.prototype, { - get canvas() { - return wrap(unsafeUnwrap(this).canvas); - }, - drawImage: function() { - arguments[0] = unwrapIfNeeded(arguments[0]); - unsafeUnwrap(this).drawImage.apply(unsafeUnwrap(this), arguments); - }, - createPattern: function() { - arguments[0] = unwrap(arguments[0]); - return unsafeUnwrap(this).createPattern.apply(unsafeUnwrap(this), arguments); - } - }); - registerWrapper(OriginalCanvasRenderingContext2D, CanvasRenderingContext2D, document.createElement("canvas").getContext("2d")); - scope.wrappers.CanvasRenderingContext2D = CanvasRenderingContext2D; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var addForwardingProperties = scope.addForwardingProperties; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var OriginalWebGLRenderingContext = window.WebGLRenderingContext; - if (!OriginalWebGLRenderingContext) return; - function WebGLRenderingContext(impl) { - setWrapper(impl, this); - } - mixin(WebGLRenderingContext.prototype, { - get canvas() { - return wrap(unsafeUnwrap(this).canvas); - }, - texImage2D: function() { - arguments[5] = unwrapIfNeeded(arguments[5]); - unsafeUnwrap(this).texImage2D.apply(unsafeUnwrap(this), arguments); - }, - texSubImage2D: function() { - arguments[6] = unwrapIfNeeded(arguments[6]); - unsafeUnwrap(this).texSubImage2D.apply(unsafeUnwrap(this), arguments); - } - }); - var OriginalWebGLRenderingContextBase = Object.getPrototypeOf(OriginalWebGLRenderingContext.prototype); - if (OriginalWebGLRenderingContextBase !== Object.prototype) { - addForwardingProperties(OriginalWebGLRenderingContextBase, WebGLRenderingContext.prototype); - } - var instanceProperties = /WebKit/.test(navigator.userAgent) ? { - drawingBufferHeight: null, - drawingBufferWidth: null - } : {}; - registerWrapper(OriginalWebGLRenderingContext, WebGLRenderingContext, instanceProperties); - scope.wrappers.WebGLRenderingContext = WebGLRenderingContext; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var Node = scope.wrappers.Node; - var GetElementsByInterface = scope.GetElementsByInterface; - var NonElementParentNodeInterface = scope.NonElementParentNodeInterface; - var ParentNodeInterface = scope.ParentNodeInterface; - var SelectorsInterface = scope.SelectorsInterface; - var mixin = scope.mixin; - var registerObject = scope.registerObject; - var registerWrapper = scope.registerWrapper; - var OriginalDocumentFragment = window.DocumentFragment; - function DocumentFragment(node) { - Node.call(this, node); - } - DocumentFragment.prototype = Object.create(Node.prototype); - mixin(DocumentFragment.prototype, ParentNodeInterface); - mixin(DocumentFragment.prototype, SelectorsInterface); - mixin(DocumentFragment.prototype, GetElementsByInterface); - mixin(DocumentFragment.prototype, NonElementParentNodeInterface); - registerWrapper(OriginalDocumentFragment, DocumentFragment, document.createDocumentFragment()); - scope.wrappers.DocumentFragment = DocumentFragment; - var Comment = registerObject(document.createComment("")); - scope.wrappers.Comment = Comment; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var DocumentFragment = scope.wrappers.DocumentFragment; - var TreeScope = scope.TreeScope; - var elementFromPoint = scope.elementFromPoint; - var getInnerHTML = scope.getInnerHTML; - var getTreeScope = scope.getTreeScope; - var mixin = scope.mixin; - var rewrap = scope.rewrap; - var setInnerHTML = scope.setInnerHTML; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var shadowHostTable = new WeakMap(); - var nextOlderShadowTreeTable = new WeakMap(); - function ShadowRoot(hostWrapper) { - var node = unwrap(unsafeUnwrap(hostWrapper).ownerDocument.createDocumentFragment()); - DocumentFragment.call(this, node); - rewrap(node, this); - var oldShadowRoot = hostWrapper.shadowRoot; - nextOlderShadowTreeTable.set(this, oldShadowRoot); - this.treeScope_ = new TreeScope(this, getTreeScope(oldShadowRoot || hostWrapper)); - shadowHostTable.set(this, hostWrapper); - } - ShadowRoot.prototype = Object.create(DocumentFragment.prototype); - mixin(ShadowRoot.prototype, { - constructor: ShadowRoot, - get innerHTML() { - return getInnerHTML(this); - }, - set innerHTML(value) { - setInnerHTML(this, value); - this.invalidateShadowRenderer(); - }, - get olderShadowRoot() { - return nextOlderShadowTreeTable.get(this) || null; - }, - get host() { - return shadowHostTable.get(this) || null; - }, - invalidateShadowRenderer: function() { - return shadowHostTable.get(this).invalidateShadowRenderer(); - }, - elementFromPoint: function(x, y) { - return elementFromPoint(this, this.ownerDocument, x, y); - }, - getSelection: function() { - return document.getSelection(); - }, - get activeElement() { - var unwrappedActiveElement = unwrap(this).ownerDocument.activeElement; - if (!unwrappedActiveElement || !unwrappedActiveElement.nodeType) return null; - var activeElement = wrap(unwrappedActiveElement); - if (activeElement === this.host) { - return null; - } - while (!this.contains(activeElement) && !this.host.contains(activeElement)) { - while (activeElement.parentNode) { - activeElement = activeElement.parentNode; - } - if (activeElement.host) { - activeElement = activeElement.host; - } else { - return null; - } - } - return activeElement; - } - }); - scope.wrappers.ShadowRoot = ShadowRoot; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var getTreeScope = scope.getTreeScope; - var OriginalRange = window.Range; - var ShadowRoot = scope.wrappers.ShadowRoot; - function getHost(node) { - var root = getTreeScope(node).root; - if (root instanceof ShadowRoot) { - return root.host; - } - return null; - } - function hostNodeToShadowNode(refNode, offset) { - if (refNode.shadowRoot) { - offset = Math.min(refNode.childNodes.length - 1, offset); - var child = refNode.childNodes[offset]; - if (child) { - var insertionPoint = scope.getDestinationInsertionPoints(child); - if (insertionPoint.length > 0) { - var parentNode = insertionPoint[0].parentNode; - if (parentNode.nodeType == Node.ELEMENT_NODE) { - refNode = parentNode; - } - } - } - } - return refNode; - } - function shadowNodeToHostNode(node) { - node = wrap(node); - return getHost(node) || node; - } - function Range(impl) { - setWrapper(impl, this); - } - Range.prototype = { - get startContainer() { - return shadowNodeToHostNode(unsafeUnwrap(this).startContainer); - }, - get endContainer() { - return shadowNodeToHostNode(unsafeUnwrap(this).endContainer); - }, - get commonAncestorContainer() { - return shadowNodeToHostNode(unsafeUnwrap(this).commonAncestorContainer); - }, - setStart: function(refNode, offset) { - refNode = hostNodeToShadowNode(refNode, offset); - unsafeUnwrap(this).setStart(unwrapIfNeeded(refNode), offset); - }, - setEnd: function(refNode, offset) { - refNode = hostNodeToShadowNode(refNode, offset); - unsafeUnwrap(this).setEnd(unwrapIfNeeded(refNode), offset); - }, - setStartBefore: function(refNode) { - unsafeUnwrap(this).setStartBefore(unwrapIfNeeded(refNode)); - }, - setStartAfter: function(refNode) { - unsafeUnwrap(this).setStartAfter(unwrapIfNeeded(refNode)); - }, - setEndBefore: function(refNode) { - unsafeUnwrap(this).setEndBefore(unwrapIfNeeded(refNode)); - }, - setEndAfter: function(refNode) { - unsafeUnwrap(this).setEndAfter(unwrapIfNeeded(refNode)); - }, - selectNode: function(refNode) { - unsafeUnwrap(this).selectNode(unwrapIfNeeded(refNode)); - }, - selectNodeContents: function(refNode) { - unsafeUnwrap(this).selectNodeContents(unwrapIfNeeded(refNode)); - }, - compareBoundaryPoints: function(how, sourceRange) { - return unsafeUnwrap(this).compareBoundaryPoints(how, unwrap(sourceRange)); - }, - extractContents: function() { - return wrap(unsafeUnwrap(this).extractContents()); - }, - cloneContents: function() { - return wrap(unsafeUnwrap(this).cloneContents()); - }, - insertNode: function(node) { - unsafeUnwrap(this).insertNode(unwrapIfNeeded(node)); - }, - surroundContents: function(newParent) { - unsafeUnwrap(this).surroundContents(unwrapIfNeeded(newParent)); - }, - cloneRange: function() { - return wrap(unsafeUnwrap(this).cloneRange()); - }, - isPointInRange: function(node, offset) { - return unsafeUnwrap(this).isPointInRange(unwrapIfNeeded(node), offset); - }, - comparePoint: function(node, offset) { - return unsafeUnwrap(this).comparePoint(unwrapIfNeeded(node), offset); - }, - intersectsNode: function(node) { - return unsafeUnwrap(this).intersectsNode(unwrapIfNeeded(node)); - }, - toString: function() { - return unsafeUnwrap(this).toString(); - } - }; - if (OriginalRange.prototype.createContextualFragment) { - Range.prototype.createContextualFragment = function(html) { - return wrap(unsafeUnwrap(this).createContextualFragment(html)); - }; - } - registerWrapper(window.Range, Range, document.createRange()); - scope.wrappers.Range = Range; - })(window.ShadowDOMPolyfill); - (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; - var ArraySplice = scope.ArraySplice; - function updateWrapperUpAndSideways(wrapper) { - wrapper.previousSibling_ = wrapper.previousSibling; - wrapper.nextSibling_ = wrapper.nextSibling; - wrapper.parentNode_ = wrapper.parentNode; - } - 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() { - 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(); - } - 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; - }; - 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; - var newChildren = this.childNodes; - 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); - 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 = { - 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); - } - }, - 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); - }, - distributionResolution: function(node) { - if (isShadowHost(node)) { - var shadowHost = node; - var pool = poolPopulation(shadowHost); - var shadowTrees = getShadowTrees(shadowHost); - for (var i = 0; i < shadowTrees.length; i++) { - this.poolDistribution(shadowTrees[i], pool); - } - for (var i = shadowTrees.length - 1; i >= 0; i--) { - var shadowTree = shadowTrees[i]; - var shadow = getShadowInsertionPoint(shadowTree); - if (shadow) { - var olderShadowRoot = shadowTree.olderShadowRoot; - if (olderShadowRoot) { - pool = poolPopulation(olderShadowRoot); - } - for (var j = 0; j < pool.length; j++) { - destributeNodeInto(pool[j], shadow); - } - } - this.distributionResolution(shadowTree); - } - } - for (var child = node.firstChild; child; child = child.nextSibling) { - this.distributionResolution(child); - } - }, - poolDistribution: function(node, pool) { - if (node instanceof HTMLShadowElement) return; - if (node instanceof HTMLContentElement) { - var content = node; - this.updateDependentAttributes(content.getAttribute("select")); - var anyDistributed = false; - 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; - } - } - 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; - }, - invalidateAttributes: function() { - this.attributes = Object.create(null); - }, - updateDependentAttributes: function(selector) { - if (!selector) return; - var attributes = this.attributes; - if (/\.\w+/.test(selector)) attributes["class"] = true; - if (/#\w+/.test(selector)) attributes["id"] = true; - selector.replace(/\[\s*([^\s=\|~\]]+)/g, function(_, name) { - attributes[name] = true; - }); - }, - dependsOnAttribute: function(name) { - return this.attributes[name]; - }, - associateNode: function(node) { - unsafeUnwrap(node).polymerShadowRenderer_ = this; - } - }; - 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) { - destinationInsertionPointsTable.set(node, undefined); - } - var selectorStartCharRe = /^(:not\()?[*.#[a-zA-Z_|]/; - function matches(node, contentElement) { - var select = contentElement.getAttribute("select"); - if (!select) return true; - 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) { - 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; - } - 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(); - } - 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() { - renderAllPending(); - return getDistributedNodes(this); - }; - Element.prototype.getDestinationInsertionPoints = function() { - renderAllPending(); - return getDestinationInsertionPoints(this) || []; - }; - HTMLContentElement.prototype.nodeIsInserted_ = HTMLShadowElement.prototype.nodeIsInserted_ = function() { - 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; - scope.visual = { - insertBefore: insertBefore, - remove: remove - }; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var assert = scope.assert; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var elementsWithFormProperty = [ "HTMLButtonElement", "HTMLFieldSetElement", "HTMLInputElement", "HTMLKeygenElement", "HTMLLabelElement", "HTMLLegendElement", "HTMLObjectElement", "HTMLOutputElement", "HTMLTextAreaElement" ]; - function createWrapperConstructor(name) { - if (!window[name]) return; - assert(!scope.wrappers[name]); - var GeneratedWrapper = function(node) { - HTMLElement.call(this, node); - }; - GeneratedWrapper.prototype = Object.create(HTMLElement.prototype); - mixin(GeneratedWrapper.prototype, { - get form() { - return wrap(unwrap(this).form); - } - }); - registerWrapper(window[name], GeneratedWrapper, document.createElement(name.slice(4, -7))); - scope.wrappers[name] = GeneratedWrapper; - } - elementsWithFormProperty.forEach(createWrapperConstructor); - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var OriginalSelection = window.Selection; - function Selection(impl) { - setWrapper(impl, this); - } - Selection.prototype = { - get anchorNode() { - return wrap(unsafeUnwrap(this).anchorNode); - }, - get focusNode() { - return wrap(unsafeUnwrap(this).focusNode); - }, - addRange: function(range) { - unsafeUnwrap(this).addRange(unwrapIfNeeded(range)); - }, - collapse: function(node, index) { - unsafeUnwrap(this).collapse(unwrapIfNeeded(node), index); - }, - containsNode: function(node, allowPartial) { - return unsafeUnwrap(this).containsNode(unwrapIfNeeded(node), allowPartial); - }, - getRangeAt: function(index) { - return wrap(unsafeUnwrap(this).getRangeAt(index)); - }, - removeRange: function(range) { - unsafeUnwrap(this).removeRange(unwrap(range)); - }, - selectAllChildren: function(node) { - unsafeUnwrap(this).selectAllChildren(node instanceof ShadowRoot ? unsafeUnwrap(node.host) : unwrapIfNeeded(node)); - }, - toString: function() { - return unsafeUnwrap(this).toString(); - } - }; - if (OriginalSelection.prototype.extend) { - Selection.prototype.extend = function(node, offset) { - unsafeUnwrap(this).extend(unwrapIfNeeded(node), offset); - }; - } - registerWrapper(window.Selection, Selection, window.getSelection()); - scope.wrappers.Selection = Selection; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var OriginalTreeWalker = window.TreeWalker; - function TreeWalker(impl) { - setWrapper(impl, this); - } - TreeWalker.prototype = { - get root() { - return wrap(unsafeUnwrap(this).root); - }, - get currentNode() { - return wrap(unsafeUnwrap(this).currentNode); - }, - set currentNode(node) { - unsafeUnwrap(this).currentNode = unwrapIfNeeded(node); - }, - get filter() { - return unsafeUnwrap(this).filter; - }, - parentNode: function() { - return wrap(unsafeUnwrap(this).parentNode()); - }, - firstChild: function() { - return wrap(unsafeUnwrap(this).firstChild()); - }, - lastChild: function() { - return wrap(unsafeUnwrap(this).lastChild()); - }, - previousSibling: function() { - return wrap(unsafeUnwrap(this).previousSibling()); - }, - previousNode: function() { - return wrap(unsafeUnwrap(this).previousNode()); - }, - nextNode: function() { - return wrap(unsafeUnwrap(this).nextNode()); - } - }; - registerWrapper(OriginalTreeWalker, TreeWalker); - scope.wrappers.TreeWalker = TreeWalker; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var GetElementsByInterface = scope.GetElementsByInterface; - var Node = scope.wrappers.Node; - var ParentNodeInterface = scope.ParentNodeInterface; - var NonElementParentNodeInterface = scope.NonElementParentNodeInterface; - var Selection = scope.wrappers.Selection; - var SelectorsInterface = scope.SelectorsInterface; - var ShadowRoot = scope.wrappers.ShadowRoot; - var TreeScope = scope.TreeScope; - var cloneNode = scope.cloneNode; - var defineGetter = scope.defineGetter; - var defineWrapGetter = scope.defineWrapGetter; - var elementFromPoint = scope.elementFromPoint; - var forwardMethodsToWrapper = scope.forwardMethodsToWrapper; - var matchesNames = scope.matchesNames; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var renderAllPending = scope.renderAllPending; - var rewrap = scope.rewrap; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var wrapEventTargetMethods = scope.wrapEventTargetMethods; - var wrapNodeList = scope.wrapNodeList; - var implementationTable = new WeakMap(); - function Document(node) { - Node.call(this, node); - this.treeScope_ = new TreeScope(this, null); - } - Document.prototype = Object.create(Node.prototype); - defineWrapGetter(Document, "documentElement"); - defineWrapGetter(Document, "body"); - defineWrapGetter(Document, "head"); - defineGetter(Document, "activeElement", function() { - var unwrappedActiveElement = unwrap(this).activeElement; - if (!unwrappedActiveElement || !unwrappedActiveElement.nodeType) return null; - var activeElement = wrap(unwrappedActiveElement); - while (!this.contains(activeElement)) { - while (activeElement.parentNode) { - activeElement = activeElement.parentNode; - } - if (activeElement.host) { - activeElement = activeElement.host; - } else { - return null; - } - } - return activeElement; - }); - function wrapMethod(name) { - var original = document[name]; - Document.prototype[name] = function() { - return wrap(original.apply(unsafeUnwrap(this), arguments)); - }; - } - [ "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode" ].forEach(wrapMethod); - var originalAdoptNode = document.adoptNode; - function adoptNodeNoRemove(node, doc) { - originalAdoptNode.call(unsafeUnwrap(doc), unwrap(node)); - adoptSubtree(node, doc); - } - function adoptSubtree(node, doc) { - if (node.shadowRoot) doc.adoptNode(node.shadowRoot); - if (node instanceof ShadowRoot) adoptOlderShadowRoots(node, doc); - for (var child = node.firstChild; child; child = child.nextSibling) { - adoptSubtree(child, doc); - } - } - function adoptOlderShadowRoots(shadowRoot, doc) { - var oldShadowRoot = shadowRoot.olderShadowRoot; - if (oldShadowRoot) doc.adoptNode(oldShadowRoot); - } - var originalGetSelection = document.getSelection; - mixin(Document.prototype, { - adoptNode: function(node) { - if (node.parentNode) node.parentNode.removeChild(node); - adoptNodeNoRemove(node, this); - return node; - }, - elementFromPoint: function(x, y) { - return elementFromPoint(this, this, x, y); - }, - importNode: function(node, deep) { - return cloneNode(node, deep, unsafeUnwrap(this)); - }, - getSelection: function() { - renderAllPending(); - return new Selection(originalGetSelection.call(unwrap(this))); - }, - getElementsByName: function(name) { - return SelectorsInterface.querySelectorAll.call(this, "[name=" + JSON.stringify(String(name)) + "]"); - } - }); - var originalCreateTreeWalker = document.createTreeWalker; - var TreeWalkerWrapper = scope.wrappers.TreeWalker; - Document.prototype.createTreeWalker = function(root, whatToShow, filter, expandEntityReferences) { - var newFilter = null; - if (filter) { - if (filter.acceptNode && typeof filter.acceptNode === "function") { - newFilter = { - acceptNode: function(node) { - return filter.acceptNode(wrap(node)); - } - }; - } else if (typeof filter === "function") { - newFilter = function(node) { - return filter(wrap(node)); - }; - } - } - return new TreeWalkerWrapper(originalCreateTreeWalker.call(unwrap(this), unwrap(root), whatToShow, newFilter, expandEntityReferences)); - }; - if (document.registerElement) { - var originalRegisterElement = document.registerElement; - Document.prototype.registerElement = function(tagName, object) { - var prototype, extendsOption; - if (object !== undefined) { - prototype = object.prototype; - extendsOption = object.extends; - } - if (!prototype) prototype = Object.create(HTMLElement.prototype); - if (scope.nativePrototypeTable.get(prototype)) { - throw new Error("NotSupportedError"); - } - var proto = Object.getPrototypeOf(prototype); - var nativePrototype; - var prototypes = []; - while (proto) { - nativePrototype = scope.nativePrototypeTable.get(proto); - if (nativePrototype) break; - prototypes.push(proto); - proto = Object.getPrototypeOf(proto); - } - if (!nativePrototype) { - throw new Error("NotSupportedError"); - } - var newPrototype = Object.create(nativePrototype); - for (var i = prototypes.length - 1; i >= 0; i--) { - newPrototype = Object.create(newPrototype); - } - [ "createdCallback", "attachedCallback", "detachedCallback", "attributeChangedCallback" ].forEach(function(name) { - var f = prototype[name]; - if (!f) return; - newPrototype[name] = function() { - if (!(wrap(this) instanceof CustomElementConstructor)) { - rewrap(this); - } - f.apply(wrap(this), arguments); - }; - }); - var p = { - prototype: newPrototype - }; - if (extendsOption) p.extends = extendsOption; - function CustomElementConstructor(node) { - if (!node) { - if (extendsOption) { - return document.createElement(extendsOption, tagName); - } else { - return document.createElement(tagName); - } - } - setWrapper(node, this); - } - CustomElementConstructor.prototype = prototype; - CustomElementConstructor.prototype.constructor = CustomElementConstructor; - scope.constructorTable.set(newPrototype, CustomElementConstructor); - scope.nativePrototypeTable.set(prototype, newPrototype); - var nativeConstructor = originalRegisterElement.call(unwrap(this), tagName, p); - return CustomElementConstructor; - }; - forwardMethodsToWrapper([ window.HTMLDocument || window.Document ], [ "registerElement" ]); - } - forwardMethodsToWrapper([ window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement, window.HTMLHtmlElement ], [ "appendChild", "compareDocumentPosition", "contains", "getElementsByClassName", "getElementsByTagName", "getElementsByTagNameNS", "insertBefore", "querySelector", "querySelectorAll", "removeChild", "replaceChild" ]); - forwardMethodsToWrapper([ window.HTMLBodyElement, window.HTMLHeadElement, window.HTMLHtmlElement ], matchesNames); - forwardMethodsToWrapper([ window.HTMLDocument || window.Document ], [ "adoptNode", "importNode", "contains", "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode", "createTreeWalker", "elementFromPoint", "getElementById", "getElementsByName", "getSelection" ]); - mixin(Document.prototype, GetElementsByInterface); - mixin(Document.prototype, ParentNodeInterface); - mixin(Document.prototype, SelectorsInterface); - mixin(Document.prototype, NonElementParentNodeInterface); - mixin(Document.prototype, { - get implementation() { - var implementation = implementationTable.get(this); - if (implementation) return implementation; - implementation = new DOMImplementation(unwrap(this).implementation); - implementationTable.set(this, implementation); - return implementation; - }, - get defaultView() { - return wrap(unwrap(this).defaultView); - } - }); - registerWrapper(window.Document, Document, document.implementation.createHTMLDocument("")); - if (window.HTMLDocument) registerWrapper(window.HTMLDocument, Document); - wrapEventTargetMethods([ window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement ]); - function DOMImplementation(impl) { - setWrapper(impl, this); - } - var originalCreateDocument = document.implementation.createDocument; - DOMImplementation.prototype.createDocument = function() { - arguments[2] = unwrap(arguments[2]); - return wrap(originalCreateDocument.apply(unsafeUnwrap(this), arguments)); - }; - function wrapImplMethod(constructor, name) { - var original = document.implementation[name]; - constructor.prototype[name] = function() { - return wrap(original.apply(unsafeUnwrap(this), arguments)); - }; - } - function forwardImplMethod(constructor, name) { - var original = document.implementation[name]; - constructor.prototype[name] = function() { - return original.apply(unsafeUnwrap(this), arguments); - }; - } - wrapImplMethod(DOMImplementation, "createDocumentType"); - wrapImplMethod(DOMImplementation, "createHTMLDocument"); - forwardImplMethod(DOMImplementation, "hasFeature"); - registerWrapper(window.DOMImplementation, DOMImplementation); - forwardMethodsToWrapper([ window.DOMImplementation ], [ "createDocument", "createDocumentType", "createHTMLDocument", "hasFeature" ]); - scope.adoptNodeNoRemove = adoptNodeNoRemove; - scope.wrappers.DOMImplementation = DOMImplementation; - scope.wrappers.Document = Document; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var EventTarget = scope.wrappers.EventTarget; - var Selection = scope.wrappers.Selection; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var renderAllPending = scope.renderAllPending; - var unwrap = scope.unwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var OriginalWindow = window.Window; - var originalGetComputedStyle = window.getComputedStyle; - var originalGetDefaultComputedStyle = window.getDefaultComputedStyle; - var originalGetSelection = window.getSelection; - function Window(impl) { - EventTarget.call(this, impl); - } - Window.prototype = Object.create(EventTarget.prototype); - OriginalWindow.prototype.getComputedStyle = function(el, pseudo) { - return wrap(this || window).getComputedStyle(unwrapIfNeeded(el), pseudo); - }; - if (originalGetDefaultComputedStyle) { - OriginalWindow.prototype.getDefaultComputedStyle = function(el, pseudo) { - return wrap(this || window).getDefaultComputedStyle(unwrapIfNeeded(el), pseudo); - }; - } - OriginalWindow.prototype.getSelection = function() { - return wrap(this || window).getSelection(); - }; - delete window.getComputedStyle; - delete window.getDefaultComputedStyle; - delete window.getSelection; - [ "addEventListener", "removeEventListener", "dispatchEvent" ].forEach(function(name) { - OriginalWindow.prototype[name] = function() { - var w = wrap(this || window); - return w[name].apply(w, arguments); - }; - delete window[name]; - }); - mixin(Window.prototype, { - getComputedStyle: function(el, pseudo) { - renderAllPending(); - return originalGetComputedStyle.call(unwrap(this), unwrapIfNeeded(el), pseudo); - }, - getSelection: function() { - renderAllPending(); - return new Selection(originalGetSelection.call(unwrap(this))); - }, - get document() { - return wrap(unwrap(this).document); - } - }); - if (originalGetDefaultComputedStyle) { - Window.prototype.getDefaultComputedStyle = function(el, pseudo) { - renderAllPending(); - return originalGetDefaultComputedStyle.call(unwrap(this), unwrapIfNeeded(el), pseudo); - }; - } - registerWrapper(OriginalWindow, Window, window); - scope.wrappers.Window = Window; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var unwrap = scope.unwrap; - var OriginalDataTransfer = window.DataTransfer || window.Clipboard; - var OriginalDataTransferSetDragImage = OriginalDataTransfer.prototype.setDragImage; - if (OriginalDataTransferSetDragImage) { - OriginalDataTransfer.prototype.setDragImage = function(image, x, y) { - OriginalDataTransferSetDragImage.call(this, unwrap(image), x, y); - }; - } - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unwrap = scope.unwrap; - var OriginalFormData = window.FormData; - if (!OriginalFormData) return; - function FormData(formElement) { - var impl; - if (formElement instanceof OriginalFormData) { - impl = formElement; - } else { - impl = new OriginalFormData(formElement && unwrap(formElement)); - } - setWrapper(impl, this); - } - registerWrapper(OriginalFormData, FormData, new OriginalFormData()); - scope.wrappers.FormData = FormData; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var originalSend = XMLHttpRequest.prototype.send; - XMLHttpRequest.prototype.send = function(obj) { - return originalSend.call(this, unwrapIfNeeded(obj)); - }; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var isWrapperFor = scope.isWrapperFor; - var elements = { - a: "HTMLAnchorElement", - area: "HTMLAreaElement", - audio: "HTMLAudioElement", - base: "HTMLBaseElement", - body: "HTMLBodyElement", - br: "HTMLBRElement", - button: "HTMLButtonElement", - canvas: "HTMLCanvasElement", - caption: "HTMLTableCaptionElement", - col: "HTMLTableColElement", - content: "HTMLContentElement", - data: "HTMLDataElement", - datalist: "HTMLDataListElement", - del: "HTMLModElement", - dir: "HTMLDirectoryElement", - div: "HTMLDivElement", - dl: "HTMLDListElement", - embed: "HTMLEmbedElement", - fieldset: "HTMLFieldSetElement", - font: "HTMLFontElement", - form: "HTMLFormElement", - frame: "HTMLFrameElement", - frameset: "HTMLFrameSetElement", - h1: "HTMLHeadingElement", - head: "HTMLHeadElement", - hr: "HTMLHRElement", - html: "HTMLHtmlElement", - iframe: "HTMLIFrameElement", - img: "HTMLImageElement", - input: "HTMLInputElement", - keygen: "HTMLKeygenElement", - label: "HTMLLabelElement", - legend: "HTMLLegendElement", - li: "HTMLLIElement", - link: "HTMLLinkElement", - map: "HTMLMapElement", - marquee: "HTMLMarqueeElement", - menu: "HTMLMenuElement", - menuitem: "HTMLMenuItemElement", - meta: "HTMLMetaElement", - meter: "HTMLMeterElement", - object: "HTMLObjectElement", - ol: "HTMLOListElement", - optgroup: "HTMLOptGroupElement", - option: "HTMLOptionElement", - output: "HTMLOutputElement", - p: "HTMLParagraphElement", - param: "HTMLParamElement", - pre: "HTMLPreElement", - progress: "HTMLProgressElement", - q: "HTMLQuoteElement", - script: "HTMLScriptElement", - select: "HTMLSelectElement", - shadow: "HTMLShadowElement", - source: "HTMLSourceElement", - span: "HTMLSpanElement", - style: "HTMLStyleElement", - table: "HTMLTableElement", - tbody: "HTMLTableSectionElement", - template: "HTMLTemplateElement", - textarea: "HTMLTextAreaElement", - thead: "HTMLTableSectionElement", - time: "HTMLTimeElement", - title: "HTMLTitleElement", - tr: "HTMLTableRowElement", - track: "HTMLTrackElement", - ul: "HTMLUListElement", - video: "HTMLVideoElement" - }; - function overrideConstructor(tagName) { - var nativeConstructorName = elements[tagName]; - var nativeConstructor = window[nativeConstructorName]; - if (!nativeConstructor) return; - var element = document.createElement(tagName); - var wrapperConstructor = element.constructor; - window[nativeConstructorName] = wrapperConstructor; - } - Object.keys(elements).forEach(overrideConstructor); - Object.getOwnPropertyNames(scope.wrappers).forEach(function(name) { - window[name] = scope.wrappers[name]; - }); - })(window.ShadowDOMPolyfill); - (function(scope) { - var ShadowCSS = { - strictStyling: false, - registry: {}, - shimStyling: function(root, name, extendsName) { - var scopeStyles = this.prepareRoot(root, name, extendsName); - var typeExtension = this.isTypeExtension(extendsName); - var scopeSelector = this.makeScopeSelector(name, typeExtension); - var cssText = stylesToCssText(scopeStyles, true); - cssText = this.scopeCssText(cssText, scopeSelector); - if (root) { - root.shimmedStyle = cssText; - } - this.addCssToDocument(cssText, name); - }, - shimStyle: function(style, selector) { - return this.shimCssText(style.textContent, selector); - }, - shimCssText: function(cssText, selector) { - cssText = this.insertDirectives(cssText); - return this.scopeCssText(cssText, selector); - }, - makeScopeSelector: function(name, typeExtension) { - if (name) { - return typeExtension ? "[is=" + name + "]" : name; - } - return ""; - }, - isTypeExtension: function(extendsName) { - return extendsName && extendsName.indexOf("-") < 0; - }, - prepareRoot: function(root, name, extendsName) { - var def = this.registerRoot(root, name, extendsName); - this.replaceTextInStyles(def.rootStyles, this.insertDirectives); - this.removeStyles(root, def.rootStyles); - if (this.strictStyling) { - this.applyScopeToContent(root, name); - } - return def.scopeStyles; - }, - removeStyles: function(root, styles) { - for (var i = 0, l = styles.length, s; i < l && (s = styles[i]); i++) { - s.parentNode.removeChild(s); - } - }, - registerRoot: function(root, name, extendsName) { - var def = this.registry[name] = { - root: root, - name: name, - extendsName: extendsName - }; - var styles = this.findStyles(root); - def.rootStyles = styles; - def.scopeStyles = def.rootStyles; - var extendee = this.registry[def.extendsName]; - if (extendee) { - def.scopeStyles = extendee.scopeStyles.concat(def.scopeStyles); - } - return def; - }, - findStyles: function(root) { - if (!root) { - return []; - } - var styles = root.querySelectorAll("style"); - return Array.prototype.filter.call(styles, function(s) { - return !s.hasAttribute(NO_SHIM_ATTRIBUTE); - }); - }, - applyScopeToContent: function(root, name) { - if (root) { - Array.prototype.forEach.call(root.querySelectorAll("*"), function(node) { - node.setAttribute(name, ""); - }); - Array.prototype.forEach.call(root.querySelectorAll("template"), function(template) { - this.applyScopeToContent(template.content, name); - }, this); - } - }, - insertDirectives: function(cssText) { - cssText = this.insertPolyfillDirectivesInCssText(cssText); - return this.insertPolyfillRulesInCssText(cssText); - }, - insertPolyfillDirectivesInCssText: function(cssText) { - cssText = cssText.replace(cssCommentNextSelectorRe, function(match, p1) { - return p1.slice(0, -2) + "{"; - }); - return cssText.replace(cssContentNextSelectorRe, function(match, p1) { - return p1 + " {"; - }); - }, - insertPolyfillRulesInCssText: function(cssText) { - cssText = cssText.replace(cssCommentRuleRe, function(match, p1) { - return p1.slice(0, -1); - }); - return cssText.replace(cssContentRuleRe, function(match, p1, p2, p3) { - var rule = match.replace(p1, "").replace(p2, ""); - return p3 + rule; - }); - }, - scopeCssText: function(cssText, scopeSelector) { - var unscoped = this.extractUnscopedRulesFromCssText(cssText); - cssText = this.insertPolyfillHostInCssText(cssText); - cssText = this.convertColonHost(cssText); - cssText = this.convertColonHostContext(cssText); - cssText = this.convertShadowDOMSelectors(cssText); - if (scopeSelector) { - var self = this, cssText; - withCssRules(cssText, function(rules) { - cssText = self.scopeRules(rules, scopeSelector); - }); - } - cssText = cssText + "\n" + unscoped; - return cssText.trim(); - }, - extractUnscopedRulesFromCssText: function(cssText) { - var r = "", m; - while (m = cssCommentUnscopedRuleRe.exec(cssText)) { - r += m[1].slice(0, -1) + "\n\n"; - } - while (m = cssContentUnscopedRuleRe.exec(cssText)) { - r += m[0].replace(m[2], "").replace(m[1], m[3]) + "\n\n"; - } - return r; - }, - convertColonHost: function(cssText) { - return this.convertColonRule(cssText, cssColonHostRe, this.colonHostPartReplacer); - }, - convertColonHostContext: function(cssText) { - return this.convertColonRule(cssText, cssColonHostContextRe, this.colonHostContextPartReplacer); - }, - convertColonRule: function(cssText, regExp, partReplacer) { - return cssText.replace(regExp, function(m, p1, p2, p3) { - p1 = polyfillHostNoCombinator; - if (p2) { - var parts = p2.split(","), r = []; - for (var i = 0, l = parts.length, p; i < l && (p = parts[i]); i++) { - p = p.trim(); - r.push(partReplacer(p1, p, p3)); - } - return r.join(","); - } else { - return p1 + p3; - } - }); - }, - colonHostContextPartReplacer: function(host, part, suffix) { - if (part.match(polyfillHost)) { - return this.colonHostPartReplacer(host, part, suffix); - } else { - return host + part + suffix + ", " + part + " " + host + suffix; - } - }, - colonHostPartReplacer: function(host, part, suffix) { - return host + part.replace(polyfillHost, "") + suffix; - }, - convertShadowDOMSelectors: function(cssText) { - for (var i = 0; i < shadowDOMSelectorsRe.length; i++) { - cssText = cssText.replace(shadowDOMSelectorsRe[i], " "); - } - return cssText; - }, - scopeRules: function(cssRules, scopeSelector) { - var cssText = ""; - if (cssRules) { - Array.prototype.forEach.call(cssRules, function(rule) { - if (rule.selectorText && (rule.style && rule.style.cssText !== undefined)) { - cssText += this.scopeSelector(rule.selectorText, scopeSelector, this.strictStyling) + " {\n "; - cssText += this.propertiesFromRule(rule) + "\n}\n\n"; - } else if (rule.type === CSSRule.MEDIA_RULE) { - cssText += "@media " + rule.media.mediaText + " {\n"; - cssText += this.scopeRules(rule.cssRules, scopeSelector); - cssText += "\n}\n\n"; - } else { - try { - if (rule.cssText) { - cssText += rule.cssText + "\n\n"; - } - } catch (x) { - if (rule.type === CSSRule.KEYFRAMES_RULE && rule.cssRules) { - cssText += this.ieSafeCssTextFromKeyFrameRule(rule); - } - } - } - }, this); - } - return cssText; - }, - ieSafeCssTextFromKeyFrameRule: function(rule) { - var cssText = "@keyframes " + rule.name + " {"; - Array.prototype.forEach.call(rule.cssRules, function(rule) { - cssText += " " + rule.keyText + " {" + rule.style.cssText + "}"; - }); - cssText += " }"; - return cssText; - }, - scopeSelector: function(selector, scopeSelector, strict) { - var r = [], parts = selector.split(","); - parts.forEach(function(p) { - p = p.trim(); - if (this.selectorNeedsScoping(p, scopeSelector)) { - p = strict && !p.match(polyfillHostNoCombinator) ? this.applyStrictSelectorScope(p, scopeSelector) : this.applySelectorScope(p, scopeSelector); - } - r.push(p); - }, this); - return r.join(", "); - }, - selectorNeedsScoping: function(selector, scopeSelector) { - if (Array.isArray(scopeSelector)) { - return true; - } - var re = this.makeScopeMatcher(scopeSelector); - return !selector.match(re); - }, - makeScopeMatcher: function(scopeSelector) { - scopeSelector = scopeSelector.replace(/\[/g, "\\[").replace(/\]/g, "\\]"); - return new RegExp("^(" + scopeSelector + ")" + selectorReSuffix, "m"); - }, - applySelectorScope: function(selector, selectorScope) { - return Array.isArray(selectorScope) ? this.applySelectorScopeList(selector, selectorScope) : this.applySimpleSelectorScope(selector, selectorScope); - }, - applySelectorScopeList: function(selector, scopeSelectorList) { - var r = []; - for (var i = 0, s; s = scopeSelectorList[i]; i++) { - r.push(this.applySimpleSelectorScope(selector, s)); - } - return r.join(", "); - }, - applySimpleSelectorScope: function(selector, scopeSelector) { - if (selector.match(polyfillHostRe)) { - selector = selector.replace(polyfillHostNoCombinator, scopeSelector); - return selector.replace(polyfillHostRe, scopeSelector + " "); - } else { - return scopeSelector + " " + selector; - } - }, - applyStrictSelectorScope: function(selector, scopeSelector) { - scopeSelector = scopeSelector.replace(/\[is=([^\]]*)\]/g, "$1"); - var splits = [ " ", ">", "+", "~" ], scoped = selector, attrName = "[" + scopeSelector + "]"; - splits.forEach(function(sep) { - var parts = scoped.split(sep); - scoped = parts.map(function(p) { - var t = p.trim().replace(polyfillHostRe, ""); - if (t && splits.indexOf(t) < 0 && t.indexOf(attrName) < 0) { - p = t.replace(/([^:]*)(:*)(.*)/, "$1" + attrName + "$2$3"); - } - return p; - }).join(sep); - }); - return scoped; - }, - insertPolyfillHostInCssText: function(selector) { - return selector.replace(colonHostContextRe, polyfillHostContext).replace(colonHostRe, polyfillHost); - }, - propertiesFromRule: function(rule) { - var cssText = rule.style.cssText; - if (rule.style.content && !rule.style.content.match(/['"]+|attr/)) { - cssText = cssText.replace(/content:[^;]*;/g, "content: '" + rule.style.content + "';"); - } - var style = rule.style; - for (var i in style) { - if (style[i] === "initial") { - cssText += i + ": initial; "; - } - } - return cssText; - }, - replaceTextInStyles: function(styles, action) { - if (styles && action) { - if (!(styles instanceof Array)) { - styles = [ styles ]; - } - Array.prototype.forEach.call(styles, function(s) { - s.textContent = action.call(this, s.textContent); - }, this); - } - }, - addCssToDocument: function(cssText, name) { - if (cssText.match("@import")) { - addOwnSheet(cssText, name); - } else { - addCssToDocument(cssText); - } - } - }; - var selectorRe = /([^{]*)({[\s\S]*?})/gim, cssCommentRe = /\/\*[^*]*\*+([^\/*][^*]*\*+)*\//gim, cssCommentNextSelectorRe = /\/\*\s*@polyfill ([^*]*\*+([^\/*][^*]*\*+)*\/)([^{]*?){/gim, cssContentNextSelectorRe = /polyfill-next-selector[^}]*content\:[\s]*?['"](.*?)['"][;\s]*}([^{]*?){/gim, cssCommentRuleRe = /\/\*\s@polyfill-rule([^*]*\*+([^\/*][^*]*\*+)*)\//gim, cssContentRuleRe = /(polyfill-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim, cssCommentUnscopedRuleRe = /\/\*\s@polyfill-unscoped-rule([^*]*\*+([^\/*][^*]*\*+)*)\//gim, cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim, cssPseudoRe = /::(x-[^\s{,(]*)/gim, cssPartRe = /::part\(([^)]*)\)/gim, polyfillHost = "-shadowcsshost", polyfillHostContext = "-shadowcsscontext", parenSuffix = ")(?:\\((" + "(?:\\([^)(]*\\)|[^)(]*)+?" + ")\\))?([^,{]*)"; - var cssColonHostRe = new RegExp("(" + polyfillHost + parenSuffix, "gim"), cssColonHostContextRe = new RegExp("(" + polyfillHostContext + parenSuffix, "gim"), selectorReSuffix = "([>\\s~+[.,{:][\\s\\S]*)?$", colonHostRe = /\:host/gim, colonHostContextRe = /\:host-context/gim, polyfillHostNoCombinator = polyfillHost + "-no-combinator", polyfillHostRe = new RegExp(polyfillHost, "gim"), polyfillHostContextRe = new RegExp(polyfillHostContext, "gim"), shadowDOMSelectorsRe = [ />>>/g, /::shadow/g, /::content/g, /\/deep\//g, /\/shadow\//g, /\/shadow-deep\//g, /\^\^/g, /\^/g ]; - function stylesToCssText(styles, preserveComments) { - var cssText = ""; - Array.prototype.forEach.call(styles, function(s) { - cssText += s.textContent + "\n\n"; - }); - if (!preserveComments) { - cssText = cssText.replace(cssCommentRe, ""); - } - return cssText; - } - function cssTextToStyle(cssText) { - var style = document.createElement("style"); - style.textContent = cssText; - return style; - } - function cssToRules(cssText) { - var style = cssTextToStyle(cssText); - document.head.appendChild(style); - var rules = []; - if (style.sheet) { - try { - rules = style.sheet.cssRules; - } catch (e) {} - } else { - console.warn("sheet not found", style); - } - style.parentNode.removeChild(style); - return rules; - } - var frame = document.createElement("iframe"); - frame.style.display = "none"; - function initFrame() { - frame.initialized = true; - document.body.appendChild(frame); - var doc = frame.contentDocument; - var base = doc.createElement("base"); - base.href = document.baseURI; - doc.head.appendChild(base); - } - function inFrame(fn) { - if (!frame.initialized) { - initFrame(); - } - document.body.appendChild(frame); - fn(frame.contentDocument); - document.body.removeChild(frame); - } - var isChrome = navigator.userAgent.match("Chrome"); - function withCssRules(cssText, callback) { - if (!callback) { - return; - } - var rules; - if (cssText.match("@import") && isChrome) { - var style = cssTextToStyle(cssText); - inFrame(function(doc) { - doc.head.appendChild(style.impl); - rules = Array.prototype.slice.call(style.sheet.cssRules, 0); - callback(rules); - }); - } else { - rules = cssToRules(cssText); - callback(rules); - } - } - function rulesToCss(cssRules) { - for (var i = 0, css = []; i < cssRules.length; i++) { - css.push(cssRules[i].cssText); - } - return css.join("\n\n"); - } - function addCssToDocument(cssText) { - if (cssText) { - getSheet().appendChild(document.createTextNode(cssText)); - } - } - function addOwnSheet(cssText, name) { - var style = cssTextToStyle(cssText); - style.setAttribute(name, ""); - style.setAttribute(SHIMMED_ATTRIBUTE, ""); - document.head.appendChild(style); - } - var SHIM_ATTRIBUTE = "shim-shadowdom"; - var SHIMMED_ATTRIBUTE = "shim-shadowdom-css"; - var NO_SHIM_ATTRIBUTE = "no-shim"; - var sheet; - function getSheet() { - if (!sheet) { - sheet = document.createElement("style"); - sheet.setAttribute(SHIMMED_ATTRIBUTE, ""); - sheet[SHIMMED_ATTRIBUTE] = true; - } - return sheet; - } - if (window.ShadowDOMPolyfill) { - addCssToDocument("style { display: none !important; }\n"); - var doc = ShadowDOMPolyfill.wrap(document); - var head = doc.querySelector("head"); - head.insertBefore(getSheet(), head.childNodes[0]); - document.addEventListener("DOMContentLoaded", function() { - var urlResolver = scope.urlResolver; - if (window.HTMLImports && !HTMLImports.useNative) { - var SHIM_SHEET_SELECTOR = "link[rel=stylesheet]" + "[" + SHIM_ATTRIBUTE + "]"; - var SHIM_STYLE_SELECTOR = "style[" + SHIM_ATTRIBUTE + "]"; - HTMLImports.importer.documentPreloadSelectors += "," + SHIM_SHEET_SELECTOR; - HTMLImports.importer.importsPreloadSelectors += "," + SHIM_SHEET_SELECTOR; - HTMLImports.parser.documentSelectors = [ HTMLImports.parser.documentSelectors, SHIM_SHEET_SELECTOR, SHIM_STYLE_SELECTOR ].join(","); - var originalParseGeneric = HTMLImports.parser.parseGeneric; - HTMLImports.parser.parseGeneric = function(elt) { - if (elt[SHIMMED_ATTRIBUTE]) { - return; - } - var style = elt.__importElement || elt; - if (!style.hasAttribute(SHIM_ATTRIBUTE)) { - originalParseGeneric.call(this, elt); - return; - } - if (elt.__resource) { - style = elt.ownerDocument.createElement("style"); - style.textContent = elt.__resource; - } - HTMLImports.path.resolveUrlsInStyle(style, elt.href); - style.textContent = ShadowCSS.shimStyle(style); - style.removeAttribute(SHIM_ATTRIBUTE, ""); - style.setAttribute(SHIMMED_ATTRIBUTE, ""); - style[SHIMMED_ATTRIBUTE] = true; - if (style.parentNode !== head) { - if (elt.parentNode === head) { - head.replaceChild(style, elt); - } else { - this.addElementToDocument(style); - } - } - style.__importParsed = true; - this.markParsingComplete(elt); - this.parseNext(); - }; - var hasResource = HTMLImports.parser.hasResource; - HTMLImports.parser.hasResource = function(node) { - if (node.localName === "link" && node.rel === "stylesheet" && node.hasAttribute(SHIM_ATTRIBUTE)) { - return node.__resource; - } else { - return hasResource.call(this, node); - } - }; - } - }); - } - scope.ShadowCSS = ShadowCSS; - })(window.WebComponents); -} - -(function(scope) { - if (window.ShadowDOMPolyfill) { - window.wrap = ShadowDOMPolyfill.wrapIfNeeded; - window.unwrap = ShadowDOMPolyfill.unwrapIfNeeded; - } else { - window.wrap = window.unwrap = function(n) { - return n; - }; - } -})(window.WebComponents); - -(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 && " " != 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 (" " == 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 (" " == 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 (" " != 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 (" " == 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 (" " != c && "\n" != c && "\r" != c) { - buffer += percentEscape(c); - } - break; - - case "query": - if (!stateOverride && "#" == c) { - this._fragment = "#"; - state = "fragment"; - } else if (EOF != c && " " != c && "\n" != c && "\r" != c) { - this._query += percentEscapeQuery(c); - } - break; - - case "fragment": - if (EOF != c && " " != 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); - -(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(scope) { - "use strict"; - if (!window.performance) { - 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.HTMLImports.__importsParsingHook) { - window.HTMLImports.__importsParsingHook(elt); - } - if (elt.import) { - elt.import.__importParsed = true; - } - this.markParsingComplete(elt); - if (elt.__resource && !elt.__error) { - elt.dispatchEvent(new CustomEvent("load", { - bubbles: false - })); - } else { - elt.dispatchEvent(new CustomEvent("error", { - bubbles: false - })); - } - if (elt.__pending) { - var fn; - while (elt.__pending.length) { - fn = elt.__pending.shift(); - if (fn) { - fn({ - target: elt - }); - } - } - } - this.parseNext(); - }, - parseLink: function(linkElt) { - if (nodeIsImport(linkElt)) { - this.parseImport(linkElt); - } else { - linkElt.href = linkElt.href; - this.parseGeneric(linkElt); - } - }, - parseStyle: function(elt) { - var src = elt; - elt = cloneStyle(elt); - src.__appliedElement = elt; - elt.__importElement = src; - this.parseGeneric(elt); - }, - parseGeneric: function(elt) { - this.trackElement(elt); - this.addElementToDocument(elt); - }, - rootImportForElement: function(elt) { - var n = elt; - while (n.ownerDocument.__importLink) { - n = n.ownerDocument.__importLink; - } - return n; - }, - addElementToDocument: function(elt) { - var port = this.rootImportForElement(elt.__importElement || elt); - port.parentNode.insertBefore(elt, port); - }, - trackElement: function(elt, callback) { - var self = this; - var done = function(e) { - elt.removeEventListener("load", done); - elt.removeEventListener("error", done); - if (callback) { - callback(e); - } - self.markParsingComplete(elt); - self.parseNext(); - }; - elt.addEventListener("load", done); - elt.addEventListener("error", done); - if (isIE && elt.localName === "style") { - var fakeLoad = false; - if (elt.textContent.indexOf("@import") == -1) { - fakeLoad = true; - } else if (elt.sheet) { - fakeLoad = true; - var csr = elt.sheet.cssRules; - var len = csr ? csr.length : 0; - for (var i = 0, r; i < len && (r = csr[i]); i++) { - if (r.type === CSSRule.IMPORT_RULE) { - fakeLoad = fakeLoad && Boolean(r.styleSheet); - } - } - } - if (fakeLoad) { - setTimeout(function() { - elt.dispatchEvent(new CustomEvent("load", { - bubbles: false - })); - }); - } - } - }, - parseScript: function(scriptElt) { - var script = document.createElement("script"); - script.__importElement = scriptElt; - script.src = scriptElt.src ? scriptElt.src : generateScriptDataUrl(scriptElt); - scope.currentScript = scriptElt; - this.trackElement(script, function(e) { - if (script.parentNode) { - script.parentNode.removeChild(script); - } - scope.currentScript = null; - }); - this.addElementToDocument(script); - }, - nextToParse: function() { - this._mayParse = []; - return !this.parsingElement && (this.nextToParseInDoc(rootDocument) || this.nextToParseDynamic()); - }, - nextToParseInDoc: function(doc, link) { - if (doc && this._mayParse.indexOf(doc) < 0) { - this._mayParse.push(doc); - var nodes = doc.querySelectorAll(this.parseSelectorsForNode(doc)); - for (var i = 0, l = nodes.length, p = 0, n; i < l && (n = nodes[i]); i++) { - if (!this.isParsed(n)) { - if (this.hasResource(n)) { - return nodeIsImport(n) ? this.nextToParseInDoc(n.__doc, n) : n; - } else { - return; - } - } - } - } - return link; - }, - nextToParseDynamic: function() { - return this.dynamicElements[0]; - }, - parseSelectorsForNode: function(node) { - var doc = node.ownerDocument || node; - return doc === rootDocument ? this.documentSelectors : this.importsSelectors; - }, - isParsed: function(node) { - return node.__importParsed; - }, - needsDynamicParsing: function(elt) { - return this.dynamicElements.indexOf(elt) >= 0; - }, - hasResource: function(node) { - if (nodeIsImport(node) && node.__doc === undefined) { - return false; - } - return true; - } - }; - function nodeIsImport(elt) { - return elt.localName === "link" && elt.rel === IMPORT_LINK_TYPE; - } - function generateScriptDataUrl(script) { - var scriptContent = generateScriptContent(script); - return "data:text/javascript;charset=utf-8," + encodeURIComponent(scriptContent); - } - function generateScriptContent(script) { - return script.textContent + generateSourceMapHint(script); - } - function generateSourceMapHint(script) { - var owner = script.ownerDocument; - owner.__importedScripts = owner.__importedScripts || 0; - var moniker = script.ownerDocument.baseURI; - var num = owner.__importedScripts ? "-" + owner.__importedScripts : ""; - owner.__importedScripts++; - return "\n//# sourceURL=" + moniker + num + ".js\n"; - } - function cloneStyle(style) { - var clone = style.ownerDocument.createElement("style"); - clone.textContent = style.textContent; - path.resolveUrlsInStyle(clone); - return clone; - } - scope.parser = importParser; - scope.IMPORT_SELECTOR = IMPORT_SELECTOR; -}); - -window.HTMLImports.addModule(function(scope) { - var flags = scope.flags; - var IMPORT_LINK_TYPE = scope.IMPORT_LINK_TYPE; - var IMPORT_SELECTOR = scope.IMPORT_SELECTOR; - var rootDocument = scope.rootDocument; - var Loader = scope.Loader; - var Observer = scope.Observer; - var parser = scope.parser; - var importer = { - documents: {}, - documentPreloadSelectors: IMPORT_SELECTOR, - importsPreloadSelectors: [ IMPORT_SELECTOR ].join(","), - loadNode: function(node) { - importLoader.addNode(node); - }, - loadSubtree: function(parent) { - var nodes = this.marshalNodes(parent); - importLoader.addNodes(nodes); - }, - marshalNodes: function(parent) { - return parent.querySelectorAll(this.loadSelectorsForNode(parent)); - }, - loadSelectorsForNode: function(node) { - var doc = node.ownerDocument || node; - return doc === rootDocument ? this.documentPreloadSelectors : this.importsPreloadSelectors; - }, - loaded: function(url, elt, resource, err, redirectedUrl) { - flags.load && console.log("loaded", url, elt); - elt.__resource = resource; - elt.__error = err; - if (isImportLink(elt)) { - var doc = this.documents[url]; - if (doc === undefined) { - doc = err ? null : makeDocument(resource, redirectedUrl || url); - if (doc) { - doc.__importLink = elt; - this.bootDocument(doc); - } - this.documents[url] = doc; - } - elt.__doc = doc; - } - parser.parseNext(); - }, - bootDocument: function(doc) { - this.loadSubtree(doc); - this.observer.observe(doc); - parser.parseNext(); - }, - loadedAll: function() { - parser.parseNext(); - } - }; - var importLoader = new Loader(importer.loaded.bind(importer), importer.loadedAll.bind(importer)); - importer.observer = new Observer(); - function isImportLink(elt) { - return isLinkRel(elt, IMPORT_LINK_TYPE); - } - function isLinkRel(elt, rel) { - return elt.localName === "link" && elt.getAttribute("rel") === rel; - } - function hasBaseURIAccessor(doc) { - return !!Object.getOwnPropertyDescriptor(doc, "baseURI"); - } - function makeDocument(resource, url) { - var doc = document.implementation.createHTMLDocument(IMPORT_LINK_TYPE); - doc._URL = url; - var base = doc.createElement("base"); - base.setAttribute("href", url); - if (!doc.baseURI && !hasBaseURIAccessor(doc)) { - Object.defineProperty(doc, "baseURI", { - value: url - }); - } - var meta = doc.createElement("meta"); - meta.setAttribute("charset", "utf-8"); - doc.head.appendChild(meta); - doc.head.appendChild(base); - doc.body.innerHTML = resource; - if (window.HTMLTemplateElement && HTMLTemplateElement.bootstrap) { - HTMLTemplateElement.bootstrap(doc); - } - return doc; - } - if (!document.baseURI) { - var baseURIDescriptor = { - get: function() { - var base = document.querySelector("base"); - return base ? base.href : window.location.href; - }, - configurable: true - }; - Object.defineProperty(document, "baseURI", baseURIDescriptor); - Object.defineProperty(rootDocument, "baseURI", baseURIDescriptor); - } - scope.importer = importer; - scope.importLoader = importLoader; -}); - -window.HTMLImports.addModule(function(scope) { - var parser = scope.parser; - var importer = scope.importer; - var dynamic = { - added: function(nodes) { - var owner, parsed, loading; - for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) { - if (!owner) { - owner = n.ownerDocument; - parsed = parser.isParsed(owner); - } - loading = this.shouldLoadNode(n); - if (loading) { - importer.loadNode(n); - } - if (this.shouldParseNode(n) && parsed) { - parser.parseDynamic(n, loading); - } - } - }, - shouldLoadNode: function(node) { - return node.nodeType === 1 && matches.call(node, importer.loadSelectorsForNode(node)); - }, - shouldParseNode: function(node) { - return node.nodeType === 1 && matches.call(node, parser.parseSelectorsForNode(node)); - } - }; - importer.observer.addCallback = dynamic.added.bind(dynamic); - var matches = HTMLElement.prototype.matches || HTMLElement.prototype.matchesSelector || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector || HTMLElement.prototype.msMatchesSelector; -}); - -(function(scope) { - var initializeModules = scope.initializeModules; - var isIE = scope.isIE; - if (scope.useNative) { - return; - } - initializeModules(); - var rootDocument = scope.rootDocument; - function bootstrap() { - window.HTMLImports.importer.bootDocument(rootDocument); - } - if (document.readyState === "complete" || document.readyState === "interactive" && !window.attachEvent) { - bootstrap(); - } else { - document.addEventListener("DOMContentLoaded", bootstrap); - } -})(window.HTMLImports); - -window.CustomElements = window.CustomElements || { - flags: {} -}; - -(function(scope) { - var flags = scope.flags; - var modules = []; - var addModule = function(module) { - modules.push(module); - }; - var initializeModules = function() { - modules.forEach(function(module) { - module(scope); - }); - }; - scope.addModule = addModule; - scope.initializeModules = initializeModules; - scope.hasNative = Boolean(document.registerElement); - scope.isIE = /Trident/.test(navigator.userAgent); - scope.useNative = !flags.register && scope.hasNative && !window.ShadowDOMPolyfill && (!window.HTMLImports || window.HTMLImports.useNative); -})(window.CustomElements); - -window.CustomElements.addModule(function(scope) { - var IMPORT_LINK_TYPE = window.HTMLImports ? window.HTMLImports.IMPORT_LINK_TYPE : "none"; - function forSubtree(node, cb) { - findAllElements(node, function(e) { - if (cb(e)) { - return true; - } - forRoots(e, cb); - }); - forRoots(node, cb); - } - function findAllElements(node, find, data) { - var e = node.firstElementChild; - if (!e) { - e = node.firstChild; - while (e && e.nodeType !== Node.ELEMENT_NODE) { - e = e.nextSibling; - } - } - while (e) { - if (find(e, data) !== true) { - findAllElements(e, find, data); - } - e = e.nextElementSibling; - } - return null; - } - function forRoots(node, cb) { - var root = node.shadowRoot; - while (root) { - forSubtree(root, cb); - root = root.olderShadowRoot; - } - } - function forDocumentTree(doc, cb) { - _forDocumentTree(doc, cb, []); - } - function _forDocumentTree(doc, cb, processingDocuments) { - doc = window.wrap(doc); - if (processingDocuments.indexOf(doc) >= 0) { - return; - } - processingDocuments.push(doc); - var imports = doc.querySelectorAll("link[rel=" + IMPORT_LINK_TYPE + "]"); - for (var i = 0, l = imports.length, n; i < l && (n = imports[i]); i++) { - if (n.import) { - _forDocumentTree(n.import, cb, processingDocuments); - } - } - cb(doc); - } - scope.forDocumentTree = forDocumentTree; - scope.forSubtree = forSubtree; -}); - -window.CustomElements.addModule(function(scope) { - var flags = scope.flags; - var forSubtree = scope.forSubtree; - var forDocumentTree = scope.forDocumentTree; - function addedNode(node, isAttached) { - return added(node, isAttached) || addedSubtree(node, isAttached); - } - function added(node, isAttached) { - if (scope.upgrade(node, isAttached)) { - return true; - } - if (isAttached) { - attached(node); - } - } - function addedSubtree(node, isAttached) { - forSubtree(node, function(e) { - if (added(e, isAttached)) { - return true; - } - }); - } - var hasThrottledAttached = window.MutationObserver._isPolyfilled && flags["throttle-attached"]; - scope.hasPolyfillMutations = hasThrottledAttached; - scope.hasThrottledAttached = hasThrottledAttached; - var isPendingMutations = false; - var pendingMutations = []; - function deferMutation(fn) { - pendingMutations.push(fn); - if (!isPendingMutations) { - isPendingMutations = true; - setTimeout(takeMutations); - } - } - function takeMutations() { - isPendingMutations = false; - var $p = pendingMutations; - for (var i = 0, l = $p.length, p; i < l && (p = $p[i]); i++) { - p(); - } - pendingMutations = []; - } - function attached(element) { - if (hasThrottledAttached) { - deferMutation(function() { - _attached(element); - }); - } else { - _attached(element); - } - } - function _attached(element) { - if (element.__upgraded__ && !element.__attached) { - element.__attached = true; - if (element.attachedCallback) { - element.attachedCallback(); - } - } - } - function detachedNode(node) { - detached(node); - forSubtree(node, function(e) { - detached(e); - }); - } - function detached(element) { - if (hasThrottledAttached) { - deferMutation(function() { - _detached(element); - }); - } else { - _detached(element); - } - } - function _detached(element) { - if (element.__upgraded__ && element.__attached) { - element.__attached = false; - if (element.detachedCallback) { - element.detachedCallback(); - } - } - } - function inDocument(element) { - var p = element; - var doc = window.wrap(document); - while (p) { - if (p == doc) { - return true; - } - p = p.parentNode || p.nodeType === Node.DOCUMENT_FRAGMENT_NODE && p.host; - } - } - function watchShadow(node) { - if (node.shadowRoot && !node.shadowRoot.__watched) { - flags.dom && console.log("watching shadow-root for: ", node.localName); - var root = node.shadowRoot; - while (root) { - observe(root); - root = root.olderShadowRoot; - } - } - } - function handler(root, mutations) { - if (flags.dom) { - var mx = mutations[0]; - if (mx && mx.type === "childList" && mx.addedNodes) { - if (mx.addedNodes) { - var d = mx.addedNodes[0]; - while (d && d !== document && !d.host) { - d = d.parentNode; - } - var u = d && (d.URL || d._URL || d.host && d.host.localName) || ""; - u = u.split("/?").shift().split("/").pop(); - } - } - console.group("mutations (%d) [%s]", mutations.length, u || ""); - } - var isAttached = inDocument(root); - mutations.forEach(function(mx) { - if (mx.type === "childList") { - forEach(mx.addedNodes, function(n) { - if (!n.localName) { - return; - } - addedNode(n, isAttached); - }); - forEach(mx.removedNodes, function(n) { - if (!n.localName) { - return; - } - detachedNode(n); - }); - } - }); - flags.dom && console.groupEnd(); - } - function takeRecords(node) { - node = window.wrap(node); - if (!node) { - node = window.wrap(document); - } - while (node.parentNode) { - node = node.parentNode; - } - var observer = node.__observer; - if (observer) { - handler(node, observer.takeRecords()); - takeMutations(); - } - } - var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); - function observe(inRoot) { - if (inRoot.__observer) { - return; - } - var observer = new MutationObserver(handler.bind(this, inRoot)); - observer.observe(inRoot, { - childList: true, - subtree: true - }); - inRoot.__observer = observer; - } - function upgradeDocument(doc) { - doc = window.wrap(doc); - flags.dom && console.group("upgradeDocument: ", doc.baseURI.split("/").pop()); - var isMainDocument = doc === window.wrap(document); - addedNode(doc, isMainDocument); - observe(doc); - flags.dom && console.groupEnd(); - } - function upgradeDocumentTree(doc) { - forDocumentTree(doc, upgradeDocument); - } - var originalCreateShadowRoot = Element.prototype.createShadowRoot; - if (originalCreateShadowRoot) { - Element.prototype.createShadowRoot = function() { - var root = originalCreateShadowRoot.call(this); - window.CustomElements.watchShadow(this); - return root; - }; - } - scope.watchShadow = watchShadow; - scope.upgradeDocumentTree = upgradeDocumentTree; - scope.upgradeDocument = upgradeDocument; - scope.upgradeSubtree = addedSubtree; - scope.upgradeAll = addedNode; - scope.attached = attached; - scope.takeRecords = takeRecords; -}); - -window.CustomElements.addModule(function(scope) { - var flags = scope.flags; - function upgrade(node, isAttached) { - if (node.localName === "template") { - if (window.HTMLTemplateElement && HTMLTemplateElement.decorate) { - HTMLTemplateElement.decorate(node); - } - } - if (!node.__upgraded__ && node.nodeType === Node.ELEMENT_NODE) { - var is = node.getAttribute("is"); - var definition = scope.getRegisteredDefinition(node.localName) || scope.getRegisteredDefinition(is); - if (definition) { - if (is && definition.tag == node.localName || !is && !definition.extends) { - return upgradeWithDefinition(node, definition, isAttached); - } - } - } - } - function upgradeWithDefinition(element, definition, isAttached) { - flags.upgrade && console.group("upgrade:", element.localName); - if (definition.is) { - element.setAttribute("is", definition.is); - } - implementPrototype(element, definition); - element.__upgraded__ = true; - created(element); - if (isAttached) { - scope.attached(element); - } - scope.upgradeSubtree(element, isAttached); - flags.upgrade && console.groupEnd(); - return element; - } - function implementPrototype(element, definition) { - if (Object.__proto__) { - element.__proto__ = definition.prototype; - } else { - customMixin(element, definition.prototype, definition.native); - element.__proto__ = definition.prototype; - } - } - function customMixin(inTarget, inSrc, inNative) { - var used = {}; - var p = inSrc; - while (p !== inNative && p !== HTMLElement.prototype) { - var keys = Object.getOwnPropertyNames(p); - for (var i = 0, k; k = keys[i]; i++) { - if (!used[k]) { - Object.defineProperty(inTarget, k, Object.getOwnPropertyDescriptor(p, k)); - used[k] = 1; - } - } - p = Object.getPrototypeOf(p); - } - } - function created(element) { - if (element.createdCallback) { - element.createdCallback(); - } - } - scope.upgrade = upgrade; - scope.upgradeWithDefinition = upgradeWithDefinition; - scope.implementPrototype = implementPrototype; -}); - -window.CustomElements.addModule(function(scope) { - var isIE = scope.isIE; - var upgradeDocumentTree = scope.upgradeDocumentTree; - var upgradeAll = scope.upgradeAll; - var upgradeWithDefinition = scope.upgradeWithDefinition; - var implementPrototype = scope.implementPrototype; - var useNative = scope.useNative; - function register(name, options) { - var definition = options || {}; - if (!name) { - throw new Error("document.registerElement: first argument `name` must not be empty"); - } - if (name.indexOf("-") < 0) { - throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '" + String(name) + "'."); - } - if (isReservedTag(name)) { - throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '" + String(name) + "'. The type name is invalid."); - } - if (getRegisteredDefinition(name)) { - throw new Error("DuplicateDefinitionError: a type with name '" + String(name) + "' is already registered"); - } - if (!definition.prototype) { - definition.prototype = Object.create(HTMLElement.prototype); - } - definition.__name = name.toLowerCase(); - definition.lifecycle = definition.lifecycle || {}; - definition.ancestry = ancestry(definition.extends); - resolveTagName(definition); - resolvePrototypeChain(definition); - overrideAttributeApi(definition.prototype); - registerDefinition(definition.__name, definition); - definition.ctor = generateConstructor(definition); - definition.ctor.prototype = definition.prototype; - definition.prototype.constructor = definition.ctor; - if (scope.ready) { - upgradeDocumentTree(document); - } - return definition.ctor; - } - function overrideAttributeApi(prototype) { - if (prototype.setAttribute._polyfilled) { - return; - } - var setAttribute = prototype.setAttribute; - prototype.setAttribute = function(name, value) { - changeAttribute.call(this, name, value, setAttribute); - }; - var removeAttribute = prototype.removeAttribute; - prototype.removeAttribute = function(name) { - changeAttribute.call(this, name, null, removeAttribute); - }; - prototype.setAttribute._polyfilled = true; - } - function changeAttribute(name, value, operation) { - name = name.toLowerCase(); - var oldValue = this.getAttribute(name); - operation.apply(this, arguments); - var newValue = this.getAttribute(name); - if (this.attributeChangedCallback && newValue !== oldValue) { - this.attributeChangedCallback(name, oldValue, newValue); - } - } - function isReservedTag(name) { - for (var i = 0; i < reservedTagList.length; i++) { - if (name === reservedTagList[i]) { - return true; - } - } - } - var reservedTagList = [ "annotation-xml", "color-profile", "font-face", "font-face-src", "font-face-uri", "font-face-format", "font-face-name", "missing-glyph" ]; - function ancestry(extnds) { - var extendee = getRegisteredDefinition(extnds); - if (extendee) { - return ancestry(extendee.extends).concat([ extendee ]); - } - return []; - } - function resolveTagName(definition) { - var baseTag = definition.extends; - for (var i = 0, a; a = definition.ancestry[i]; i++) { - baseTag = a.is && a.tag; - } - definition.tag = baseTag || definition.__name; - if (baseTag) { - definition.is = definition.__name; - } - } - function resolvePrototypeChain(definition) { - if (!Object.__proto__) { - var nativePrototype = HTMLElement.prototype; - if (definition.is) { - var inst = document.createElement(definition.tag); - nativePrototype = Object.getPrototypeOf(inst); - } - var proto = definition.prototype, ancestor; - var foundPrototype = false; - while (proto) { - if (proto == nativePrototype) { - foundPrototype = true; - } - ancestor = Object.getPrototypeOf(proto); - if (ancestor) { - proto.__proto__ = ancestor; - } - proto = ancestor; - } - if (!foundPrototype) { - console.warn(definition.tag + " prototype not found in prototype chain for " + definition.is); - } - definition.native = nativePrototype; - } - } - function instantiate(definition) { - return upgradeWithDefinition(domCreateElement(definition.tag), definition); - } - var registry = {}; - function getRegisteredDefinition(name) { - if (name) { - return registry[name.toLowerCase()]; - } - } - function registerDefinition(name, definition) { - registry[name] = definition; - } - function generateConstructor(definition) { - return function() { - return instantiate(definition); - }; - } - var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; - function createElementNS(namespace, tag, typeExtension) { - if (namespace === HTML_NAMESPACE) { - return createElement(tag, typeExtension); - } else { - return domCreateElementNS(namespace, tag); - } - } - function createElement(tag, typeExtension) { - if (tag) { - tag = tag.toLowerCase(); - } - if (typeExtension) { - typeExtension = typeExtension.toLowerCase(); - } - var definition = getRegisteredDefinition(typeExtension || tag); - if (definition) { - if (tag == definition.tag && typeExtension == definition.is) { - return new definition.ctor(); - } - if (!typeExtension && !definition.is) { - return new definition.ctor(); - } - } - var element; - if (typeExtension) { - element = createElement(tag); - element.setAttribute("is", typeExtension); - return element; - } - element = domCreateElement(tag); - if (tag.indexOf("-") >= 0) { - implementPrototype(element, HTMLElement); - } - return element; - } - var domCreateElement = document.createElement.bind(document); - var domCreateElementNS = document.createElementNS.bind(document); - var isInstance; - if (!Object.__proto__ && !useNative) { - isInstance = function(obj, ctor) { - if (obj instanceof ctor) { - return true; - } - var p = obj; - while (p) { - if (p === ctor.prototype) { - return true; - } - p = p.__proto__; - } - return false; - }; - } else { - isInstance = function(obj, base) { - return obj instanceof base; - }; - } - function wrapDomMethodToForceUpgrade(obj, methodName) { - var orig = obj[methodName]; - obj[methodName] = function() { - var n = orig.apply(this, arguments); - upgradeAll(n); - return n; - }; - } - wrapDomMethodToForceUpgrade(Node.prototype, "cloneNode"); - wrapDomMethodToForceUpgrade(document, "importNode"); - if (isIE) { - (function() { - var importNode = document.importNode; - document.importNode = function() { - var n = importNode.apply(document, arguments); - if (n.nodeType == n.DOCUMENT_FRAGMENT_NODE) { - var f = document.createDocumentFragment(); - f.appendChild(n); - return f; - } else { - return n; - } - }; - })(); - } - document.registerElement = register; - document.createElement = createElement; - document.createElementNS = createElementNS; - scope.registry = registry; - scope.instanceof = isInstance; - scope.reservedTagList = reservedTagList; - scope.getRegisteredDefinition = getRegisteredDefinition; - document.register = document.registerElement; -}); - -(function(scope) { - var useNative = scope.useNative; - var initializeModules = scope.initializeModules; - var isIE = scope.isIE; - if (useNative) { - var nop = function() {}; - scope.watchShadow = nop; - scope.upgrade = nop; - scope.upgradeAll = nop; - scope.upgradeDocumentTree = nop; - scope.upgradeSubtree = nop; - scope.takeRecords = nop; - scope.instanceof = function(obj, base) { - return obj instanceof base; - }; - } else { - initializeModules(); - } - var upgradeDocumentTree = scope.upgradeDocumentTree; - var upgradeDocument = scope.upgradeDocument; - if (!window.wrap) { - if (window.ShadowDOMPolyfill) { - window.wrap = window.ShadowDOMPolyfill.wrapIfNeeded; - window.unwrap = window.ShadowDOMPolyfill.unwrapIfNeeded; - } else { - window.wrap = window.unwrap = function(node) { - return node; - }; - } - } - if (window.HTMLImports) { - window.HTMLImports.__importsParsingHook = function(elt) { - if (elt.import) { - upgradeDocument(wrap(elt.import)); - } - }; - } - function bootstrap() { - upgradeDocumentTree(window.wrap(document)); - window.CustomElements.ready = true; - var requestAnimationFrame = window.requestAnimationFrame || function(f) { - setTimeout(f, 16); - }; - requestAnimationFrame(function() { - setTimeout(function() { - window.CustomElements.readyTime = Date.now(); - if (window.HTMLImports) { - window.CustomElements.elapsed = window.CustomElements.readyTime - window.HTMLImports.readyTime; - } - document.dispatchEvent(new CustomEvent("WebComponentsReady", { - bubbles: true - })); - }); - }); - } - if (document.readyState === "complete" || scope.flags.eager) { - bootstrap(); - } else if (document.readyState === "interactive" && !window.attachEvent && (!window.HTMLImports || window.HTMLImports.ready)) { - bootstrap(); - } else { - var loadEvent = window.HTMLImports && !window.HTMLImports.ready ? "HTMLImportsLoaded" : "DOMContentLoaded"; - window.addEventListener(loadEvent, bootstrap); - } -})(window.CustomElements); - -(function(scope) { - if (!Function.prototype.bind) { - Function.prototype.bind = function(scope) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - return function() { - var args2 = args.slice(); - args2.push.apply(args2, arguments); - return self.apply(scope, args2); - }; - }; - } -})(window.WebComponents); - -(function(scope) { - var style = document.createElement("style"); - style.textContent = "" + "body {" + "transition: opacity ease-in 0.2s;" + " } \n" + "body[unresolved] {" + "opacity: 0; display: block; overflow: hidden; position: relative;" + " } \n"; - var head = document.querySelector("head"); - head.insertBefore(style, head.firstChild); -})(window.WebComponents); - -(function(scope) { - window.Platform = scope; -})(window.WebComponents); -/*! - * PEP v0.4.1 | https://github.com/jquery/PEP - * Copyright jQuery Foundation and other contributors | http://jquery.org/license - */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - global.PointerEventsPolyfill = factory() -}(this, function () { 'use strict'; - - /** - * This is the constructor for new PointerEvents. - * - * New Pointer Events must be given a type, and an optional dictionary of - * initialization properties. - * - * Due to certain platform requirements, events returned from the constructor - * identify as MouseEvents. - * - * @constructor - * @param {String} inType The type of the event to create. - * @param {Object} [inDict] An optional dictionary of initial event properties. - * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`. - */ - var MOUSE_PROPS = [ - 'bubbles', - 'cancelable', - 'view', - 'detail', - 'screenX', - 'screenY', - 'clientX', - 'clientY', - 'ctrlKey', - 'altKey', - 'shiftKey', - 'metaKey', - 'button', - 'relatedTarget', - 'pageX', - 'pageY' - ]; - - var MOUSE_DEFAULTS = [ - false, - false, - null, - null, - 0, - 0, - 0, - 0, - false, - false, - false, - false, - 0, - null, - 0, - 0 - ]; - - function PointerEvent(inType, inDict) { - inDict = inDict || Object.create(null); - - var e = document.createEvent('Event'); - e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false); - - // define inherited MouseEvent properties - // skip bubbles and cancelable since they're set above in initEvent() - for (var i = 2, p; i < MOUSE_PROPS.length; i++) { - p = MOUSE_PROPS[i]; - e[p] = inDict[p] || MOUSE_DEFAULTS[i]; - } - e.buttons = inDict.buttons || 0; - - // Spec requires that pointers without pressure specified use 0.5 for down - // state and 0 for up state. - var pressure = 0; - if (inDict.pressure) { - pressure = inDict.pressure; - } else { - pressure = e.buttons ? 0.5 : 0; - } - - // add x/y properties aliased to clientX/Y - e.x = e.clientX; - e.y = e.clientY; - - // define the properties of the PointerEvent interface - e.pointerId = inDict.pointerId || 0; - e.width = inDict.width || 0; - e.height = inDict.height || 0; - e.pressure = pressure; - e.tiltX = inDict.tiltX || 0; - e.tiltY = inDict.tiltY || 0; - e.pointerType = inDict.pointerType || ''; - e.hwTimestamp = inDict.hwTimestamp || 0; - e.isPrimary = inDict.isPrimary || false; - return e; - } - - var _PointerEvent = PointerEvent; - - /** - * This module implements a map of pointer states - */ - var USE_MAP = window.Map && window.Map.prototype.forEach; - var PointerMap = USE_MAP ? Map : SparseArrayMap; - - function SparseArrayMap() { - this.array = []; - this.size = 0; - } - - SparseArrayMap.prototype = { - set: function(k, v) { - if (v === undefined) { - return this.delete(k); - } - if (!this.has(k)) { - this.size++; - } - this.array[k] = v; - }, - has: function(k) { - return this.array[k] !== undefined; - }, - delete: function(k) { - if (this.has(k)) { - delete this.array[k]; - this.size--; - } - }, - get: function(k) { - return this.array[k]; - }, - clear: function() { - this.array.length = 0; - this.size = 0; - }, - - // return value, key, map - forEach: function(callback, thisArg) { - return this.array.forEach(function(v, k) { - callback.call(thisArg, v, k, this); - }, this); - } - }; - - var _pointermap = PointerMap; - - var CLONE_PROPS = [ - - // MouseEvent - 'bubbles', - 'cancelable', - 'view', - 'detail', - 'screenX', - 'screenY', - 'clientX', - 'clientY', - 'ctrlKey', - 'altKey', - 'shiftKey', - 'metaKey', - 'button', - 'relatedTarget', - - // DOM Level 3 - 'buttons', - - // PointerEvent - 'pointerId', - 'width', - 'height', - 'pressure', - 'tiltX', - 'tiltY', - 'pointerType', - 'hwTimestamp', - 'isPrimary', - - // event instance - 'type', - 'target', - 'currentTarget', - 'which', - 'pageX', - 'pageY', - 'timeStamp' - ]; - - var CLONE_DEFAULTS = [ - - // MouseEvent - false, - false, - null, - null, - 0, - 0, - 0, - 0, - false, - false, - false, - false, - 0, - null, - - // DOM Level 3 - 0, - - // PointerEvent - 0, - 0, - 0, - 0, - 0, - 0, - '', - 0, - false, - - // event instance - '', - null, - null, - 0, - 0, - 0, - 0 - ]; - - var BOUNDARY_EVENTS = { - 'pointerover': 1, - 'pointerout': 1, - 'pointerenter': 1, - 'pointerleave': 1 - }; - - var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined'); - - /** - * This module is for normalizing events. Mouse and Touch events will be - * collected here, and fire PointerEvents that have the same semantics, no - * matter the source. - * Events fired: - * - pointerdown: a pointing is added - * - pointerup: a pointer is removed - * - pointermove: a pointer is moved - * - pointerover: a pointer crosses into an element - * - pointerout: a pointer leaves an element - * - pointercancel: a pointer will no longer generate events - */ - var dispatcher = { - pointermap: new _pointermap(), - eventMap: Object.create(null), - captureInfo: Object.create(null), - - // Scope objects for native events. - // This exists for ease of testing. - eventSources: Object.create(null), - eventSourceList: [], - /** - * Add a new event source that will generate pointer events. - * - * `inSource` must contain an array of event names named `events`, and - * functions with the names specified in the `events` array. - * @param {string} name A name for the event source - * @param {Object} source A new source of platform events. - */ - registerSource: function(name, source) { - var s = source; - var newEvents = s.events; - if (newEvents) { - newEvents.forEach(function(e) { - if (s[e]) { - this.eventMap[e] = s[e].bind(s); - } - }, this); - this.eventSources[name] = s; - this.eventSourceList.push(s); - } - }, - register: function(element) { - var l = this.eventSourceList.length; - for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) { - - // call eventsource register - es.register.call(es, element); - } - }, - unregister: function(element) { - var l = this.eventSourceList.length; - for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) { - - // call eventsource register - es.unregister.call(es, element); - } - }, - contains: /*scope.external.contains || */function(container, contained) { - try { - return container.contains(contained); - } catch (ex) { - - // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427 - return false; - } - }, - - // EVENTS - down: function(inEvent) { - inEvent.bubbles = true; - this.fireEvent('pointerdown', inEvent); - }, - move: function(inEvent) { - inEvent.bubbles = true; - this.fireEvent('pointermove', inEvent); - }, - up: function(inEvent) { - inEvent.bubbles = true; - this.fireEvent('pointerup', inEvent); - }, - enter: function(inEvent) { - inEvent.bubbles = false; - this.fireEvent('pointerenter', inEvent); - }, - leave: function(inEvent) { - inEvent.bubbles = false; - this.fireEvent('pointerleave', inEvent); - }, - over: function(inEvent) { - inEvent.bubbles = true; - this.fireEvent('pointerover', inEvent); - }, - out: function(inEvent) { - inEvent.bubbles = true; - this.fireEvent('pointerout', inEvent); - }, - cancel: function(inEvent) { - inEvent.bubbles = true; - this.fireEvent('pointercancel', inEvent); - }, - leaveOut: function(event) { - this.out(event); - if (!this.contains(event.target, event.relatedTarget)) { - this.leave(event); - } - }, - enterOver: function(event) { - this.over(event); - if (!this.contains(event.target, event.relatedTarget)) { - this.enter(event); - } - }, - - // LISTENER LOGIC - eventHandler: function(inEvent) { - - // This is used to prevent multiple dispatch of pointerevents from - // platform events. This can happen when two elements in different scopes - // are set up to create pointer events, which is relevant to Shadow DOM. - if (inEvent._handledByPE) { - return; - } - var type = inEvent.type; - var fn = this.eventMap && this.eventMap[type]; - if (fn) { - fn(inEvent); - } - inEvent._handledByPE = true; - }, - - // set up event listeners - listen: function(target, events) { - events.forEach(function(e) { - this.addEvent(target, e); - }, this); - }, - - // remove event listeners - unlisten: function(target, events) { - events.forEach(function(e) { - this.removeEvent(target, e); - }, this); - }, - addEvent: /*scope.external.addEvent || */function(target, eventName) { - target.addEventListener(eventName, this.boundHandler); - }, - removeEvent: /*scope.external.removeEvent || */function(target, eventName) { - target.removeEventListener(eventName, this.boundHandler); - }, - - // EVENT CREATION AND TRACKING - /** - * Creates a new Event of type `inType`, based on the information in - * `inEvent`. - * - * @param {string} inType A string representing the type of event to create - * @param {Event} inEvent A platform event with a target - * @return {Event} A PointerEvent of type `inType` - */ - makeEvent: function(inType, inEvent) { - - // relatedTarget must be null if pointer is captured - if (this.captureInfo[inEvent.pointerId]) { - inEvent.relatedTarget = null; - } - var e = new _PointerEvent(inType, inEvent); - if (inEvent.preventDefault) { - e.preventDefault = inEvent.preventDefault; - } - e._target = e._target || inEvent.target; - return e; - }, - - // make and dispatch an event in one call - fireEvent: function(inType, inEvent) { - var e = this.makeEvent(inType, inEvent); - return this.dispatchEvent(e); - }, - /** - * Returns a snapshot of inEvent, with writable properties. - * - * @param {Event} inEvent An event that contains properties to copy. - * @return {Object} An object containing shallow copies of `inEvent`'s - * properties. - */ - cloneEvent: function(inEvent) { - var eventCopy = Object.create(null); - var p; - for (var i = 0; i < CLONE_PROPS.length; i++) { - p = CLONE_PROPS[i]; - eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i]; - - // Work around SVGInstanceElement shadow tree - // Return the element that is represented by the instance for Safari, Chrome, IE. - // This is the behavior implemented by Firefox. - if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) { - if (eventCopy[p] instanceof SVGElementInstance) { - eventCopy[p] = eventCopy[p].correspondingUseElement; - } - } - } - - // keep the semantics of preventDefault - if (inEvent.preventDefault) { - eventCopy.preventDefault = function() { - inEvent.preventDefault(); - }; - } - return eventCopy; - }, - getTarget: function(inEvent) { - var capture = this.captureInfo[inEvent.pointerId]; - if (!capture) { - return inEvent._target; - } - if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) { - return capture; - } - }, - setCapture: function(inPointerId, inTarget) { - if (this.captureInfo[inPointerId]) { - this.releaseCapture(inPointerId); - } - this.captureInfo[inPointerId] = inTarget; - var e = document.createEvent('Event'); - e.initEvent('gotpointercapture', true, false); - e.pointerId = inPointerId; - this.implicitRelease = this.releaseCapture.bind(this, inPointerId); - document.addEventListener('pointerup', this.implicitRelease); - document.addEventListener('pointercancel', this.implicitRelease); - e._target = inTarget; - this.asyncDispatchEvent(e); - }, - releaseCapture: function(inPointerId) { - var t = this.captureInfo[inPointerId]; - if (t) { - var e = document.createEvent('Event'); - e.initEvent('lostpointercapture', true, false); - e.pointerId = inPointerId; - this.captureInfo[inPointerId] = undefined; - document.removeEventListener('pointerup', this.implicitRelease); - document.removeEventListener('pointercancel', this.implicitRelease); - e._target = t; - this.asyncDispatchEvent(e); - } - }, - /** - * Dispatches the event to its target. - * - * @param {Event} inEvent The event to be dispatched. - * @return {Boolean} True if an event handler returns true, false otherwise. - */ - dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) { - var t = this.getTarget(inEvent); - if (t) { - return t.dispatchEvent(inEvent); - } - }, - asyncDispatchEvent: function(inEvent) { - requestAnimationFrame(this.dispatchEvent.bind(this, inEvent)); - } - }; - dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher); - - var _dispatcher = dispatcher; - - var targeting = { - shadow: function(inEl) { - if (inEl) { - return inEl.shadowRoot || inEl.webkitShadowRoot; - } - }, - canTarget: function(shadow) { - return shadow && Boolean(shadow.elementFromPoint); - }, - targetingShadow: function(inEl) { - var s = this.shadow(inEl); - if (this.canTarget(s)) { - return s; - } - }, - olderShadow: function(shadow) { - var os = shadow.olderShadowRoot; - if (!os) { - var se = shadow.querySelector('shadow'); - if (se) { - os = se.olderShadowRoot; - } - } - return os; - }, - allShadows: function(element) { - var shadows = []; - var s = this.shadow(element); - while (s) { - shadows.push(s); - s = this.olderShadow(s); - } - return shadows; - }, - searchRoot: function(inRoot, x, y) { - if (inRoot) { - var t = inRoot.elementFromPoint(x, y); - var st, sr; - - // is element a shadow host? - sr = this.targetingShadow(t); - while (sr) { - - // find the the element inside the shadow root - st = sr.elementFromPoint(x, y); - if (!st) { - - // check for older shadows - sr = this.olderShadow(sr); - } else { - - // shadowed element may contain a shadow root - var ssr = this.targetingShadow(st); - return this.searchRoot(ssr, x, y) || st; - } - } - - // light dom element is the target - return t; - } - }, - owner: function(element) { - var s = element; - - // walk up until you hit the shadow root or document - while (s.parentNode) { - s = s.parentNode; - } - - // the owner element is expected to be a Document or ShadowRoot - if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) { - s = document; - } - return s; - }, - findTarget: function(inEvent) { - var x = inEvent.clientX; - var y = inEvent.clientY; - - // if the listener is in the shadow root, it is much faster to start there - var s = this.owner(inEvent.target); - - // if x, y is not in this root, fall back to document search - if (!s.elementFromPoint(x, y)) { - s = document; - } - return this.searchRoot(s, x, y); - } - }; - - /** - * This module uses Mutation Observers to dynamically adjust which nodes will - * generate Pointer Events. - * - * All nodes that wish to generate Pointer Events must have the attribute - * `touch-action` set to `none`. - */ - var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); - var map = Array.prototype.map.call.bind(Array.prototype.map); - var toArray = Array.prototype.slice.call.bind(Array.prototype.slice); - var filter = Array.prototype.filter.call.bind(Array.prototype.filter); - var MO = window.MutationObserver || window.WebKitMutationObserver; - var SELECTOR = '[touch-action]'; - var OBSERVER_INIT = { - subtree: true, - childList: true, - attributes: true, - attributeOldValue: true, - attributeFilter: ['touch-action'] - }; - - function Installer(add, remove, changed, binder) { - this.addCallback = add.bind(binder); - this.removeCallback = remove.bind(binder); - this.changedCallback = changed.bind(binder); - if (MO) { - this.observer = new MO(this.mutationWatcher.bind(this)); - } - } - - Installer.prototype = { - watchSubtree: function(target) { - - // Only watch scopes that can target find, as these are top-level. - // Otherwise we can see duplicate additions and removals that add noise. - // - // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see - // a removal without an insertion when a node is redistributed among - // shadows. Since it all ends up correct in the document, watching only - // the document will yield the correct mutations to watch. - if (this.observer && targeting.canTarget(target)) { - this.observer.observe(target, OBSERVER_INIT); - } - }, - enableOnSubtree: function(target) { - this.watchSubtree(target); - if (target === document && document.readyState !== 'complete') { - this.installOnLoad(); - } else { - this.installNewSubtree(target); - } - }, - installNewSubtree: function(target) { - forEach(this.findElements(target), this.addElement, this); - }, - findElements: function(target) { - if (target.querySelectorAll) { - return target.querySelectorAll(SELECTOR); - } - return []; - }, - removeElement: function(el) { - this.removeCallback(el); - }, - addElement: function(el) { - this.addCallback(el); - }, - elementChanged: function(el, oldValue) { - this.changedCallback(el, oldValue); - }, - concatLists: function(accum, list) { - return accum.concat(toArray(list)); - }, - - // register all touch-action = none nodes on document load - installOnLoad: function() { - document.addEventListener('readystatechange', function() { - if (document.readyState === 'complete') { - this.installNewSubtree(document); - } - }.bind(this)); - }, - isElement: function(n) { - return n.nodeType === Node.ELEMENT_NODE; - }, - flattenMutationTree: function(inNodes) { - - // find children with touch-action - var tree = map(inNodes, this.findElements, this); - - // make sure the added nodes are accounted for - tree.push(filter(inNodes, this.isElement)); - - // flatten the list - return tree.reduce(this.concatLists, []); - }, - mutationWatcher: function(mutations) { - mutations.forEach(this.mutationHandler, this); - }, - mutationHandler: function(m) { - if (m.type === 'childList') { - var added = this.flattenMutationTree(m.addedNodes); - added.forEach(this.addElement, this); - var removed = this.flattenMutationTree(m.removedNodes); - removed.forEach(this.removeElement, this); - } else if (m.type === 'attributes') { - this.elementChanged(m.target, m.oldValue); - } - } - }; - - var installer = Installer; - - function shadowSelector(v) { - return 'body /shadow-deep/ ' + selector(v); - } - function selector(v) { - return '[touch-action="' + v + '"]'; - } - function rule(v) { - return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; touch-action-delay: none; }'; - } - var attrib2css = [ - 'none', - 'auto', - 'pan-x', - 'pan-y', - { - rule: 'pan-x pan-y', - selectors: [ - 'pan-x pan-y', - 'pan-y pan-x' - ] - } - ]; - var styles = ''; - - // only install stylesheet if the browser has touch action support - var hasNativePE = window.PointerEvent || window.MSPointerEvent; - - // only add shadow selectors if shadowdom is supported - var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot; - - function applyAttributeStyles() { - if (hasNativePE) { - attrib2css.forEach(function(r) { - if (String(r) === r) { - styles += selector(r) + rule(r) + '\n'; - if (hasShadowRoot) { - styles += shadowSelector(r) + rule(r) + '\n'; - } - } else { - styles += r.selectors.map(selector) + rule(r.rule) + '\n'; - if (hasShadowRoot) { - styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n'; - } - } - }); - - var el = document.createElement('style'); - el.textContent = styles; - document.head.appendChild(el); - } - } - - var mouse__pointermap = _dispatcher.pointermap; - - // radius around touchend that swallows mouse events - var DEDUP_DIST = 25; - - // left, middle, right, back, forward - var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16]; - - var HAS_BUTTONS = false; - try { - HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1; - } catch (e) {} - - // handler block for native mouse events - var mouseEvents = { - POINTER_ID: 1, - POINTER_TYPE: 'mouse', - events: [ - 'mousedown', - 'mousemove', - 'mouseup', - 'mouseover', - 'mouseout' - ], - register: function(target) { - _dispatcher.listen(target, this.events); - }, - unregister: function(target) { - _dispatcher.unlisten(target, this.events); - }, - lastTouches: [], - - // collide with the global mouse listener - isEventSimulatedFromTouch: function(inEvent) { - var lts = this.lastTouches; - var x = inEvent.clientX; - var y = inEvent.clientY; - for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) { - - // simulated mouse events will be swallowed near a primary touchend - var dx = Math.abs(x - t.x); - var dy = Math.abs(y - t.y); - if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) { - return true; - } - } - }, - prepareEvent: function(inEvent) { - var e = _dispatcher.cloneEvent(inEvent); - - // forward mouse preventDefault - var pd = e.preventDefault; - e.preventDefault = function() { - inEvent.preventDefault(); - pd(); - }; - e.pointerId = this.POINTER_ID; - e.isPrimary = true; - e.pointerType = this.POINTER_TYPE; - return e; - }, - prepareButtonsForMove: function(e, inEvent) { - var p = mouse__pointermap.get(this.POINTER_ID); - e.buttons = p ? p.buttons : 0; - inEvent.buttons = e.buttons; - }, - mousedown: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var p = mouse__pointermap.get(this.POINTER_ID); - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { - e.buttons = BUTTON_TO_BUTTONS[e.button]; - if (p) { e.buttons |= p.buttons; } - inEvent.buttons = e.buttons; - } - mouse__pointermap.set(this.POINTER_ID, inEvent); - if (!p) { - _dispatcher.down(e); - } else { - _dispatcher.move(e); - } - } - }, - mousemove: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); } - _dispatcher.move(e); - } - }, - mouseup: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var p = mouse__pointermap.get(this.POINTER_ID); - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { - var up = BUTTON_TO_BUTTONS[e.button]; - - // Produces wrong state of buttons in Browsers without `buttons` support - // when a mouse button that was pressed outside the document is released - // inside and other buttons are still pressed down. - e.buttons = p ? p.buttons & ~up : 0; - inEvent.buttons = e.buttons; - } - mouse__pointermap.set(this.POINTER_ID, inEvent); - - // Support: Firefox <=44 only - // FF Ubuntu includes the lifted button in the `buttons` property on - // mouseup. - // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366 - if (e.buttons === 0 || e.buttons === BUTTON_TO_BUTTONS[e.button]) { - this.cleanupMouse(); - _dispatcher.up(e); - } else { - _dispatcher.move(e); - } - } - }, - mouseover: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); } - _dispatcher.enterOver(e); - } - }, - mouseout: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); } - _dispatcher.leaveOut(e); - } - }, - cancel: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.cancel(e); - this.cleanupMouse(); - }, - cleanupMouse: function() { - mouse__pointermap.delete(this.POINTER_ID); - } - }; - - var mouse = mouseEvents; - - var captureInfo = _dispatcher.captureInfo; - var findTarget = targeting.findTarget.bind(targeting); - var allShadows = targeting.allShadows.bind(targeting); - var touch__pointermap = _dispatcher.pointermap; - - // This should be long enough to ignore compat mouse events made by touch - var DEDUP_TIMEOUT = 2500; - var CLICK_COUNT_TIMEOUT = 200; - var ATTRIB = 'touch-action'; - var INSTALLER; - - // The presence of touch event handlers blocks scrolling, and so we must be careful to - // avoid adding handlers unnecessarily. Chrome plans to add a touch-action-delay property - // (crbug.com/329559) to address this, and once we have that we can opt-in to a simpler - // handler registration mechanism. Rather than try to predict how exactly to opt-in to - // that we'll just leave this disabled until there is a build of Chrome to test. - var HAS_TOUCH_ACTION_DELAY = false; - - // handler block for native touch events - var touchEvents = { - events: [ - 'touchstart', - 'touchmove', - 'touchend', - 'touchcancel' - ], - register: function(target) { - if (HAS_TOUCH_ACTION_DELAY) { - _dispatcher.listen(target, this.events); - } else { - INSTALLER.enableOnSubtree(target); - } - }, - unregister: function(target) { - if (HAS_TOUCH_ACTION_DELAY) { - _dispatcher.unlisten(target, this.events); - } else { - - // TODO(dfreedman): is it worth it to disconnect the MO? - } - }, - elementAdded: function(el) { - var a = el.getAttribute(ATTRIB); - var st = this.touchActionToScrollType(a); - if (st) { - el._scrollType = st; - _dispatcher.listen(el, this.events); - - // set touch-action on shadows as well - allShadows(el).forEach(function(s) { - s._scrollType = st; - _dispatcher.listen(s, this.events); - }, this); - } - }, - elementRemoved: function(el) { - el._scrollType = undefined; - _dispatcher.unlisten(el, this.events); - - // remove touch-action from shadow - allShadows(el).forEach(function(s) { - s._scrollType = undefined; - _dispatcher.unlisten(s, this.events); - }, this); - }, - elementChanged: function(el, oldValue) { - var a = el.getAttribute(ATTRIB); - var st = this.touchActionToScrollType(a); - var oldSt = this.touchActionToScrollType(oldValue); - - // simply update scrollType if listeners are already established - if (st && oldSt) { - el._scrollType = st; - allShadows(el).forEach(function(s) { - s._scrollType = st; - }, this); - } else if (oldSt) { - this.elementRemoved(el); - } else if (st) { - this.elementAdded(el); - } - }, - scrollTypes: { - EMITTER: 'none', - XSCROLLER: 'pan-x', - YSCROLLER: 'pan-y', - SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/ - }, - touchActionToScrollType: function(touchAction) { - var t = touchAction; - var st = this.scrollTypes; - if (t === 'none') { - return 'none'; - } else if (t === st.XSCROLLER) { - return 'X'; - } else if (t === st.YSCROLLER) { - return 'Y'; - } else if (st.SCROLLER.exec(t)) { - return 'XY'; - } - }, - POINTER_TYPE: 'touch', - firstTouch: null, - isPrimaryTouch: function(inTouch) { - return this.firstTouch === inTouch.identifier; - }, - setPrimaryTouch: function(inTouch) { - - // set primary touch if there no pointers, or the only pointer is the mouse - if (touch__pointermap.size === 0 || (touch__pointermap.size === 1 && touch__pointermap.has(1))) { - this.firstTouch = inTouch.identifier; - this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY }; - this.scrolling = false; - this.cancelResetClickCount(); - } - }, - removePrimaryPointer: function(inPointer) { - if (inPointer.isPrimary) { - this.firstTouch = null; - this.firstXY = null; - this.resetClickCount(); - } - }, - clickCount: 0, - resetId: null, - resetClickCount: function() { - var fn = function() { - this.clickCount = 0; - this.resetId = null; - }.bind(this); - this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT); - }, - cancelResetClickCount: function() { - if (this.resetId) { - clearTimeout(this.resetId); - } - }, - typeToButtons: function(type) { - var ret = 0; - if (type === 'touchstart' || type === 'touchmove') { - ret = 1; - } - return ret; - }, - touchToPointer: function(inTouch) { - var cte = this.currentTouchEvent; - var e = _dispatcher.cloneEvent(inTouch); - - // We reserve pointerId 1 for Mouse. - // Touch identifiers can start at 0. - // Add 2 to the touch identifier for compatibility. - var id = e.pointerId = inTouch.identifier + 2; - e.target = captureInfo[id] || findTarget(e); - e.bubbles = true; - e.cancelable = true; - e.detail = this.clickCount; - e.button = 0; - e.buttons = this.typeToButtons(cte.type); - e.width = inTouch.radiusX || inTouch.webkitRadiusX || 0; - e.height = inTouch.radiusY || inTouch.webkitRadiusY || 0; - e.pressure = inTouch.force || inTouch.webkitForce || 0.5; - e.isPrimary = this.isPrimaryTouch(inTouch); - e.pointerType = this.POINTER_TYPE; - - // forward touch preventDefaults - var self = this; - e.preventDefault = function() { - self.scrolling = false; - self.firstXY = null; - cte.preventDefault(); - }; - return e; - }, - processTouches: function(inEvent, inFunction) { - var tl = inEvent.changedTouches; - this.currentTouchEvent = inEvent; - for (var i = 0, t; i < tl.length; i++) { - t = tl[i]; - inFunction.call(this, this.touchToPointer(t)); - } - }, - - // For single axis scrollers, determines whether the element should emit - // pointer events or behave as a scroller - shouldScroll: function(inEvent) { - if (this.firstXY) { - var ret; - var scrollAxis = inEvent.currentTarget._scrollType; - if (scrollAxis === 'none') { - - // this element is a touch-action: none, should never scroll - ret = false; - } else if (scrollAxis === 'XY') { - - // this element should always scroll - ret = true; - } else { - var t = inEvent.changedTouches[0]; - - // check the intended scroll axis, and other axis - var a = scrollAxis; - var oa = scrollAxis === 'Y' ? 'X' : 'Y'; - var da = Math.abs(t['client' + a] - this.firstXY[a]); - var doa = Math.abs(t['client' + oa] - this.firstXY[oa]); - - // if delta in the scroll axis > delta other axis, scroll instead of - // making events - ret = da >= doa; - } - this.firstXY = null; - return ret; - } - }, - findTouch: function(inTL, inId) { - for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) { - if (t.identifier === inId) { - return true; - } - } - }, - - // In some instances, a touchstart can happen without a touchend. This - // leaves the pointermap in a broken state. - // Therefore, on every touchstart, we remove the touches that did not fire a - // touchend event. - // To keep state globally consistent, we fire a - // pointercancel for this "abandoned" touch - vacuumTouches: function(inEvent) { - var tl = inEvent.touches; - - // pointermap.size should be < tl.length here, as the touchstart has not - // been processed yet. - if (touch__pointermap.size >= tl.length) { - var d = []; - touch__pointermap.forEach(function(value, key) { - - // Never remove pointerId == 1, which is mouse. - // Touch identifiers are 2 smaller than their pointerId, which is the - // index in pointermap. - if (key !== 1 && !this.findTouch(tl, key - 2)) { - var p = value.out; - d.push(p); - } - }, this); - d.forEach(this.cancelOut, this); - } - }, - touchstart: function(inEvent) { - this.vacuumTouches(inEvent); - this.setPrimaryTouch(inEvent.changedTouches[0]); - this.dedupSynthMouse(inEvent); - if (!this.scrolling) { - this.clickCount++; - this.processTouches(inEvent, this.overDown); - } - }, - overDown: function(inPointer) { - touch__pointermap.set(inPointer.pointerId, { - target: inPointer.target, - out: inPointer, - outTarget: inPointer.target - }); - _dispatcher.over(inPointer); - _dispatcher.enter(inPointer); - _dispatcher.down(inPointer); - }, - touchmove: function(inEvent) { - if (!this.scrolling) { - if (this.shouldScroll(inEvent)) { - this.scrolling = true; - this.touchcancel(inEvent); - } else { - inEvent.preventDefault(); - this.processTouches(inEvent, this.moveOverOut); - } - } - }, - moveOverOut: function(inPointer) { - var event = inPointer; - var pointer = touch__pointermap.get(event.pointerId); - - // a finger drifted off the screen, ignore it - if (!pointer) { - return; - } - var outEvent = pointer.out; - var outTarget = pointer.outTarget; - _dispatcher.move(event); - if (outEvent && outTarget !== event.target) { - outEvent.relatedTarget = event.target; - event.relatedTarget = outTarget; - - // recover from retargeting by shadow - outEvent.target = outTarget; - if (event.target) { - _dispatcher.leaveOut(outEvent); - _dispatcher.enterOver(event); - } else { - - // clean up case when finger leaves the screen - event.target = outTarget; - event.relatedTarget = null; - this.cancelOut(event); - } - } - pointer.out = event; - pointer.outTarget = event.target; - }, - touchend: function(inEvent) { - this.dedupSynthMouse(inEvent); - this.processTouches(inEvent, this.upOut); - }, - upOut: function(inPointer) { - if (!this.scrolling) { - _dispatcher.up(inPointer); - _dispatcher.out(inPointer); - _dispatcher.leave(inPointer); - } - this.cleanUpPointer(inPointer); - }, - touchcancel: function(inEvent) { - this.processTouches(inEvent, this.cancelOut); - }, - cancelOut: function(inPointer) { - _dispatcher.cancel(inPointer); - _dispatcher.out(inPointer); - _dispatcher.leave(inPointer); - this.cleanUpPointer(inPointer); - }, - cleanUpPointer: function(inPointer) { - touch__pointermap.delete(inPointer.pointerId); - this.removePrimaryPointer(inPointer); - }, - - // prevent synth mouse events from creating pointer events - dedupSynthMouse: function(inEvent) { - var lts = mouse.lastTouches; - var t = inEvent.changedTouches[0]; - - // only the primary finger will synth mouse events - if (this.isPrimaryTouch(t)) { - - // remember x/y of last touch - var lt = { x: t.clientX, y: t.clientY }; - lts.push(lt); - var fn = (function(lts, lt) { - var i = lts.indexOf(lt); - if (i > -1) { - lts.splice(i, 1); - } - }).bind(null, lts, lt); - setTimeout(fn, DEDUP_TIMEOUT); - } - } - }; - - if (!HAS_TOUCH_ACTION_DELAY) { - INSTALLER = new installer(touchEvents.elementAdded, touchEvents.elementRemoved, - touchEvents.elementChanged, touchEvents); - } - - var touch = touchEvents; - - var ms__pointermap = _dispatcher.pointermap; - var HAS_BITMAP_TYPE = window.MSPointerEvent && - typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number'; - var msEvents = { - events: [ - 'MSPointerDown', - 'MSPointerMove', - 'MSPointerUp', - 'MSPointerOut', - 'MSPointerOver', - 'MSPointerCancel', - 'MSGotPointerCapture', - 'MSLostPointerCapture' - ], - register: function(target) { - _dispatcher.listen(target, this.events); - }, - unregister: function(target) { - _dispatcher.unlisten(target, this.events); - }, - POINTER_TYPES: [ - '', - 'unavailable', - 'touch', - 'pen', - 'mouse' - ], - prepareEvent: function(inEvent) { - var e = inEvent; - if (HAS_BITMAP_TYPE) { - e = _dispatcher.cloneEvent(inEvent); - e.pointerType = this.POINTER_TYPES[inEvent.pointerType]; - } - return e; - }, - cleanup: function(id) { - ms__pointermap.delete(id); - }, - MSPointerDown: function(inEvent) { - ms__pointermap.set(inEvent.pointerId, inEvent); - var e = this.prepareEvent(inEvent); - _dispatcher.down(e); - }, - MSPointerMove: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.move(e); - }, - MSPointerUp: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.up(e); - this.cleanup(inEvent.pointerId); - }, - MSPointerOut: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.leaveOut(e); - }, - MSPointerOver: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.enterOver(e); - }, - MSPointerCancel: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.cancel(e); - this.cleanup(inEvent.pointerId); - }, - MSLostPointerCapture: function(inEvent) { - var e = _dispatcher.makeEvent('lostpointercapture', inEvent); - _dispatcher.dispatchEvent(e); - }, - MSGotPointerCapture: function(inEvent) { - var e = _dispatcher.makeEvent('gotpointercapture', inEvent); - _dispatcher.dispatchEvent(e); - } - }; - - var ms = msEvents; - - function platform_events__applyPolyfill() { - - // only activate if this platform does not have pointer events - if (!window.PointerEvent) { - window.PointerEvent = _PointerEvent; - - if (window.navigator.msPointerEnabled) { - var tp = window.navigator.msMaxTouchPoints; - Object.defineProperty(window.navigator, 'maxTouchPoints', { - value: tp, - enumerable: true - }); - _dispatcher.registerSource('ms', ms); - } else { - _dispatcher.registerSource('mouse', mouse); - if (window.ontouchstart !== undefined) { - _dispatcher.registerSource('touch', touch); - } - } - - _dispatcher.register(document); - } - } - - var n = window.navigator; - var s, r; - function assertDown(id) { - if (!_dispatcher.pointermap.has(id)) { - throw new Error('InvalidPointerId'); - } - } - if (n.msPointerEnabled) { - s = function(pointerId) { - assertDown(pointerId); - this.msSetPointerCapture(pointerId); - }; - r = function(pointerId) { - assertDown(pointerId); - this.msReleasePointerCapture(pointerId); - }; - } else { - s = function setPointerCapture(pointerId) { - assertDown(pointerId); - _dispatcher.setCapture(pointerId, this); - }; - r = function releasePointerCapture(pointerId) { - assertDown(pointerId); - _dispatcher.releaseCapture(pointerId, this); - }; - } - - function _capture__applyPolyfill() { - if (window.Element && !Element.prototype.setPointerCapture) { - Object.defineProperties(Element.prototype, { - 'setPointerCapture': { - value: s - }, - 'releasePointerCapture': { - value: r - } - }); - } - } - - applyAttributeStyles(); - platform_events__applyPolyfill(); - _capture__applyPolyfill(); - - var pointerevents = { - dispatcher: _dispatcher, - Installer: installer, - PointerEvent: _PointerEvent, - PointerMap: _pointermap, - targetFinding: targeting - }; - - return pointerevents; - -})); - -(function () { - -/*** Variables ***/ - - var win = window, - doc = document, - attrProto = { - setAttribute: Element.prototype.setAttribute, - removeAttribute: Element.prototype.removeAttribute - }, - hasShadow = Element.prototype.createShadowRoot, - container = doc.createElement('div'), - noop = function(){}, - trueop = function(){ return true; }, - regexReplaceCommas = /,/g, - regexCamelToDash = /([a-z])([A-Z])/g, - regexPseudoParens = /\(|\)/g, - regexPseudoCapture = /:(\w+)\u276A(.+?(?=\u276B))|:(\w+)/g, - regexDigits = /(\d+)/g, - keypseudo = { - action: function (pseudo, event) { - return pseudo.value.match(regexDigits).indexOf(String(event.keyCode)) > -1 == (pseudo.name == 'keypass') || null; - } - }, - /* - - The prefix object generated here is added to the xtag object as xtag.prefix later in the code - - Prefix provides a variety of prefix variations for the browser in which your code is running - - The 4 variations of prefix are as follows: - * prefix.dom: the correct prefix case and form when used on DOM elements/style properties - * prefix.lowercase: a lowercase version of the prefix for use in various user-code situations - * prefix.css: the lowercase, dashed version of the prefix - * prefix.js: addresses prefixed APIs present in global and non-Element contexts - */ - prefix = (function () { - var keys = Object.keys(window).join(); - var pre = ((keys.match(/,(ms)/) || keys.match(/,(moz)/) || keys.match(/,(O)/)) || [null, 'webkit'])[1].toLowerCase(); - return { - dom: pre == 'ms' ? 'MS' : pre, - lowercase: pre, - css: '-' + pre + '-', - js: pre == 'ms' ? pre : pre.charAt(0).toUpperCase() + pre.substring(1) - }; - })(), - matchSelector = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype[prefix.lowercase + 'MatchesSelector']; - -/*** Functions ***/ - -// Utilities - - /* - This is an enhanced typeof check for all types of objects. Where typeof would normaly return - 'object' for many common DOM objects (like NodeLists and HTMLCollections). - - For example: typeOf(document.children) will correctly return 'htmlcollection' - */ - var typeCache = {}, - typeString = typeCache.toString, - typeRegexp = /\s([a-zA-Z]+)/; - function typeOf(obj) { - var type = typeString.call(obj); - return typeCache[type] || (typeCache[type] = type.match(typeRegexp)[1].toLowerCase()); - } - - function clone(item, type){ - var fn = clone[type || typeOf(item)]; - return fn ? fn(item) : item; - } - clone.object = function(src){ - var obj = {}; - for (var key in src) obj[key] = clone(src[key]); - return obj; - }; - clone.array = function(src){ - var i = src.length, array = new Array(i); - while (i--) array[i] = clone(src[i]); - return array; - }; - - /* - The toArray() method allows for conversion of any object to a true array. For types that - cannot be converted to an array, the method returns a 1 item array containing the passed-in object. - */ - var unsliceable = { 'undefined': 1, 'null': 1, 'number': 1, 'boolean': 1, 'string': 1, 'function': 1 }; - function toArray(obj){ - return unsliceable[typeOf(obj)] ? [obj] : Array.prototype.slice.call(obj, 0); - } - -// DOM - - var str = ''; - function query(element, selector){ - return (selector || str).length ? toArray(element.querySelectorAll(selector)) : []; - } - -// Pseudos - - function parsePseudo(fn){fn();} - -// Mixins - - function mergeOne(source, key, current){ - var type = typeOf(current); - if (type == 'object' && typeOf(source[key]) == 'object') xtag.merge(source[key], current); - else source[key] = clone(current, type); - return source; - } - - function mergeMixin(tag, original, mixin, name) { - var key, keys = {}; - for (var z in original) keys[z.split(':')[0]] = z; - for (z in mixin) { - key = keys[z.split(':')[0]]; - if (typeof original[key] == 'function') { - if (!key.match(':mixins')) { - original[key + ':mixins'] = original[key]; - delete original[key]; - key = key + ':mixins'; - } - original[key].__mixin__ = xtag.applyPseudos(z + (z.match(':mixins') ? '' : ':mixins'), mixin[z], tag.pseudos, original[key].__mixin__); - } - else { - original[z] = mixin[z]; - delete original[key]; - } - } - } - - var uniqueMixinCount = 0; - function addMixin(tag, original, mixin){ - for (var z in mixin){ - original[z + ':__mixin__(' + (uniqueMixinCount++) + ')'] = xtag.applyPseudos(z, mixin[z], tag.pseudos); - } - } - - function resolveMixins(mixins, output){ - var index = mixins.length; - while (index--){ - output.unshift(mixins[index]); - if (xtag.mixins[mixins[index]].mixins) resolveMixins(xtag.mixins[mixins[index]].mixins, output); - } - return output; - } - - function applyMixins(tag) { - resolveMixins(tag.mixins, []).forEach(function(name){ - var mixin = xtag.mixins[name]; - for (var type in mixin) { - var item = mixin[type], - original = tag[type]; - if (!original) tag[type] = item; - else { - switch (type){ - case 'mixins': break; - case 'events': addMixin(tag, original, item); break; - case 'accessors': - case 'prototype': - for (var z in item) { - if (!original[z]) original[z] = item[z]; - else mergeMixin(tag, original[z], item[z], name); - } - break; - default: mergeMixin(tag, original, item, name); - } - } - } - }); - return tag; - } - -// Events - - function delegateAction(pseudo, event) { - var match, - target = event.target, - root = event.currentTarget; - while (!match && target && target != root) { - if (target.tagName && matchSelector.call(target, pseudo.value)) match = target; - target = target.parentNode; - } - if (!match && root.tagName && matchSelector.call(root, pseudo.value)) match = root; - return match ? pseudo.listener = pseudo.listener.bind(match) : null; - } - - function touchFilter(event){ - return event.button === 0; - } - - function writeProperty(key, event, base, desc){ - if (desc) event[key] = base[key]; - else Object.defineProperty(event, key, { - writable: true, - enumerable: true, - value: base[key] - }); - } - - var skipProps = {}; - for (var z in doc.createEvent('CustomEvent')) skipProps[z] = 1; - function inheritEvent(event, base){ - var desc = Object.getOwnPropertyDescriptor(event, 'target'); - for (var z in base) { - if (!skipProps[z]) writeProperty(z, event, base, desc); - } - event.baseEvent = base; - } - -// Accessors - - function modAttr(element, attr, name, value, method){ - attrProto[method].call(element, name, attr && attr.boolean ? '' : value); - } - - function syncAttr(element, attr, name, value, method){ - if (attr && (attr.property || attr.selector)) { - var nodes = attr.property ? [element.xtag[attr.property]] : attr.selector ? xtag.query(element, attr.selector) : [], - index = nodes.length; - while (index--) nodes[index][method](name, value); - } - } - - function attachProperties(tag, prop, z, accessor, attr, name){ - var key = z.split(':'), type = key[0]; - if (type == 'get') { - key[0] = prop; - tag.prototype[prop].get = xtag.applyPseudos(key.join(':'), accessor[z], tag.pseudos, accessor[z]); - } - else if (type == 'set') { - key[0] = prop; - var setter = tag.prototype[prop].set = xtag.applyPseudos(key.join(':'), attr ? function(value){ - var old, method = 'setAttribute'; - if (attr.boolean){ - value = !!value; - old = this.hasAttribute(name); - if (!value) method = 'removeAttribute'; - } - else { - value = attr.validate ? attr.validate.call(this, value) : value; - old = this.getAttribute(name); - } - modAttr(this, attr, name, value, method); - accessor[z].call(this, value, old); - syncAttr(this, attr, name, value, method); - } : accessor[z] ? function(value){ - accessor[z].call(this, value); - } : null, tag.pseudos, accessor[z]); - - if (attr) attr.setter = accessor[z]; - } - else tag.prototype[prop][z] = accessor[z]; - } - - function parseAccessor(tag, prop){ - tag.prototype[prop] = {}; - var accessor = tag.accessors[prop], - attr = accessor.attribute, - name; - - if (attr) { - name = attr.name = (attr ? (attr.name || prop.replace(regexCamelToDash, '$1-$2')) : prop).toLowerCase(); - attr.key = prop; - tag.attributes[name] = attr; - } - - for (var z in accessor) attachProperties(tag, prop, z, accessor, attr, name); - - if (attr) { - if (!tag.prototype[prop].get) { - var method = (attr.boolean ? 'has' : 'get') + 'Attribute'; - tag.prototype[prop].get = function(){ - return this[method](name); - }; - } - if (!tag.prototype[prop].set) tag.prototype[prop].set = function(value){ - value = attr.boolean ? !!value : attr.validate ? attr.validate.call(this, value) : value; - var method = attr.boolean ? (value ? 'setAttribute' : 'removeAttribute') : 'setAttribute'; - modAttr(this, attr, name, value, method); - syncAttr(this, attr, name, value, method); - }; - } - } - - var unwrapComment = /\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//; - function parseMultiline(fn){ - return typeof fn == 'function' ? unwrapComment.exec(fn.toString())[1] : fn; - } - -/*** X-Tag Object Definition ***/ - - var xtag = { - tags: {}, - defaultOptions: { - pseudos: [], - mixins: [], - events: {}, - methods: {}, - accessors: {}, - lifecycle: {}, - attributes: {}, - 'prototype': { - xtag: { - get: function(){ - return this.__xtag__ ? this.__xtag__ : (this.__xtag__ = { data: {} }); - } - } - } - }, - register: function (name, options) { - var _name; - if (typeof name == 'string') _name = name.toLowerCase(); - else throw 'First argument must be a Custom Element string name'; - xtag.tags[_name] = options || {}; - - var basePrototype = options.prototype; - delete options.prototype; - var tag = xtag.tags[_name].compiled = applyMixins(xtag.merge({}, xtag.defaultOptions, options)); - var proto = tag.prototype; - var lifecycle = tag.lifecycle; - - for (var z in tag.events) tag.events[z] = xtag.parseEvent(z, tag.events[z]); - for (z in lifecycle) lifecycle[z.split(':')[0]] = xtag.applyPseudos(z, lifecycle[z], tag.pseudos, lifecycle[z]); - for (z in tag.methods) proto[z.split(':')[0]] = { value: xtag.applyPseudos(z, tag.methods[z], tag.pseudos, tag.methods[z]), enumerable: true }; - for (z in tag.accessors) parseAccessor(tag, z); - - if (tag.shadow) tag.shadow = tag.shadow.nodeName ? tag.shadow : xtag.createFragment(tag.shadow); - if (tag.content) tag.content = tag.content.nodeName ? tag.content.innerHTML : parseMultiline(tag.content); - var created = lifecycle.created; - var finalized = lifecycle.finalized; - proto.createdCallback = { - enumerable: true, - value: function(){ - var element = this; - if (tag.shadow && hasShadow) this.createShadowRoot().appendChild(tag.shadow.cloneNode(true)); - if (tag.content) this.appendChild(document.createElement('div')).outerHTML = tag.content; - var output = created ? created.apply(this, arguments) : null; - xtag.addEvents(this, tag.events); - for (var name in tag.attributes) { - var attr = tag.attributes[name], - hasAttr = this.hasAttribute(name), - hasDefault = attr.def !== undefined; - if (hasAttr || attr.boolean || hasDefault) { - this[attr.key] = attr.boolean ? hasAttr : !hasAttr && hasDefault ? attr.def : this.getAttribute(name); - } - } - tag.pseudos.forEach(function(obj){ - obj.onAdd.call(element, obj); - }); - this.xtagComponentReady = true; - if (finalized) finalized.apply(this, arguments); - return output; - } - }; - - var inserted = lifecycle.inserted; - var removed = lifecycle.removed; - if (inserted || removed) { - proto.attachedCallback = { value: function(){ - if (removed) this.xtag.__parentNode__ = this.parentNode; - if (inserted) return inserted.apply(this, arguments); - }, enumerable: true }; - } - if (removed) { - proto.detachedCallback = { value: function(){ - var args = toArray(arguments); - args.unshift(this.xtag.__parentNode__); - var output = removed.apply(this, args); - delete this.xtag.__parentNode__; - return output; - }, enumerable: true }; - } - if (lifecycle.attributeChanged) proto.attributeChangedCallback = { value: lifecycle.attributeChanged, enumerable: true }; - - proto.setAttribute = { - writable: true, - enumerable: true, - value: function (name, value){ - var old; - var _name = name.toLowerCase(); - var attr = tag.attributes[_name]; - if (attr) { - old = this.getAttribute(_name); - value = attr.boolean ? '' : attr.validate ? attr.validate.call(this, value) : value; - } - modAttr(this, attr, _name, value, 'setAttribute'); - if (attr) { - if (attr.setter) attr.setter.call(this, attr.boolean ? true : value, old); - syncAttr(this, attr, _name, value, 'setAttribute'); - } - } - }; - - proto.removeAttribute = { - writable: true, - enumerable: true, - value: function (name){ - var _name = name.toLowerCase(); - var attr = tag.attributes[_name]; - var old = this.hasAttribute(_name); - modAttr(this, attr, _name, '', 'removeAttribute'); - if (attr) { - if (attr.setter) attr.setter.call(this, attr.boolean ? false : undefined, old); - syncAttr(this, attr, _name, '', 'removeAttribute'); - } - } - }; - - var definition = {}; - var instance = basePrototype instanceof win.HTMLElement; - var extended = tag['extends'] && (definition['extends'] = tag['extends']); - - if (basePrototype) Object.getOwnPropertyNames(basePrototype).forEach(function(z){ - var prop = proto[z]; - var desc = instance ? Object.getOwnPropertyDescriptor(basePrototype, z) : basePrototype[z]; - if (prop) { - for (var y in desc) { - if (typeof desc[y] == 'function' && prop[y]) prop[y] = xtag.wrap(desc[y], prop[y]); - else prop[y] = desc[y]; - } - } - proto[z] = prop || desc; - }); - - definition['prototype'] = Object.create( - extended ? Object.create(doc.createElement(extended).constructor).prototype : win.HTMLElement.prototype, - proto - ); - - return doc.registerElement(_name, definition); - }, - - /* Exposed Variables */ - - mixins: {}, - prefix: prefix, - captureEvents: { focus: 1, blur: 1, scroll: 1, DOMMouseScroll: 1 }, - customEvents: { - animationstart: { - attach: [prefix.dom + 'AnimationStart'] - }, - animationend: { - attach: [prefix.dom + 'AnimationEnd'] - }, - transitionend: { - attach: [prefix.dom + 'TransitionEnd'] - }, - move: { - attach: ['pointermove'] - }, - enter: { - attach: ['pointerenter'] - }, - leave: { - attach: ['pointerleave'] - }, - scrollwheel: { - attach: ['DOMMouseScroll', 'mousewheel'], - condition: function(event){ - event.delta = event.wheelDelta ? event.wheelDelta / 40 : Math.round(event.detail / 3.5 * -1); - return true; - } - }, - tap: { - attach: ['pointerdown', 'pointerup'], - condition: function(event, custom){ - if (event.type == 'pointerdown') { - custom.startX = event.clientX; - custom.startY = event.clientY; - } - else if (event.button === 0 && - Math.abs(custom.startX - event.clientX) < 10 && - Math.abs(custom.startY - event.clientY) < 10) return true; - } - }, - tapstart: { - attach: ['pointerdown'], - condition: touchFilter - }, - tapend: { - attach: ['pointerup'], - condition: touchFilter - }, - tapmove: { - attach: ['pointerdown'], - condition: function(event, custom){ - if (event.type == 'pointerdown') { - var listener = custom.listener.bind(this); - if (!custom.tapmoveListeners) custom.tapmoveListeners = xtag.addEvents(document, { - pointermove: listener, - pointerup: listener, - pointercancel: listener - }); - } - else if (event.type == 'pointerup' || event.type == 'pointercancel') { - xtag.removeEvents(document, custom.tapmoveListeners); - custom.tapmoveListeners = null; - } - return true; - } - }, - taphold: { - attach: ['pointerdown', 'pointerup'], - condition: function(event, custom){ - if (event.type == 'pointerdown') { - (custom.pointers = custom.pointers || {})[event.pointerId] = setTimeout( - xtag.fireEvent.bind(null, this, 'taphold'), - custom.duration || 1000 - ); - } - else if (event.type == 'pointerup') { - if (custom.pointers) { - clearTimeout(custom.pointers[event.pointerId]); - delete custom.pointers[event.pointerId]; - } - } - else return true; - } - } - }, - pseudos: { - __mixin__: {}, - mixins: { - onCompiled: function(fn, pseudo){ - var mixin = pseudo.source && pseudo.source.__mixin__ || pseudo.source; - if (mixin) switch (pseudo.value) { - case null: case '': case 'before': return function(){ - mixin.apply(this, arguments); - return fn.apply(this, arguments); - }; - case 'after': return function(){ - var returns = fn.apply(this, arguments); - mixin.apply(this, arguments); - return returns; - }; - case 'none': return fn; - } - else return fn; - } - }, - keypass: keypseudo, - keyfail: keypseudo, - delegate: { - action: delegateAction - }, - preventable: { - action: function (pseudo, event) { - return !event.defaultPrevented; - } - }, - duration: { - onAdd: function(pseudo){ - pseudo.source.duration = Number(pseudo.value); - } - }, - capture: { - onCompiled: function(fn, pseudo){ - if (pseudo.source) pseudo.source.capture = true; - } - } - }, - - /* UTILITIES */ - - clone: clone, - typeOf: typeOf, - toArray: toArray, - - wrap: function (original, fn) { - return function(){ - var output = original.apply(this, arguments); - fn.apply(this, arguments); - return output; - }; - }, - /* - Recursively merges one object with another. The first argument is the destination object, - all other objects passed in as arguments are merged from right to left, conflicts are overwritten - */ - merge: function(source, k, v){ - if (typeOf(k) == 'string') return mergeOne(source, k, v); - for (var i = 1, l = arguments.length; i < l; i++){ - var object = arguments[i]; - for (var key in object) mergeOne(source, key, object[key]); - } - return source; - }, - - /* - ----- This should be simplified! ----- - Generates a random ID string - */ - uid: function(){ - return Math.random().toString(36).substr(2,10); - }, - - /* DOM */ - - query: query, - - skipTransition: function(element, fn, bind){ - var prop = prefix.js + 'TransitionProperty'; - element.style[prop] = element.style.transitionProperty = 'none'; - var callback = fn ? fn.call(bind || element) : null; - return xtag.skipFrame(function(){ - element.style[prop] = element.style.transitionProperty = ''; - if (callback) callback.call(bind || element); - }); - }, - - requestFrame: (function(){ - var raf = win.requestAnimationFrame || - win[prefix.lowercase + 'RequestAnimationFrame'] || - function(fn){ return win.setTimeout(fn, 20); }; - return function(fn){ return raf(fn); }; - })(), - - cancelFrame: (function(){ - var cancel = win.cancelAnimationFrame || - win[prefix.lowercase + 'CancelAnimationFrame'] || - win.clearTimeout; - return function(id){ return cancel(id); }; - })(), - - skipFrame: function(fn){ - var id = xtag.requestFrame(function(){ id = xtag.requestFrame(fn); }); - return id; - }, - - matchSelector: function (element, selector) { - return matchSelector.call(element, selector); - }, - - set: function (element, method, value) { - element[method] = value; - if (window.CustomElements) CustomElements.upgradeAll(element); - }, - - innerHTML: function(el, html){ - xtag.set(el, 'innerHTML', html); - }, - - hasClass: function (element, klass) { - return element.className.split(' ').indexOf(klass.trim())>-1; - }, - - addClass: function (element, klass) { - var list = element.className.trim().split(' '); - klass.trim().split(' ').forEach(function (name) { - if (!~list.indexOf(name)) list.push(name); - }); - element.className = list.join(' ').trim(); - return element; - }, - - removeClass: function (element, klass) { - var classes = klass.trim().split(' '); - element.className = element.className.trim().split(' ').filter(function (name) { - return name && !~classes.indexOf(name); - }).join(' '); - return element; - }, - - toggleClass: function (element, klass) { - return xtag[xtag.hasClass(element, klass) ? 'removeClass' : 'addClass'].call(null, element, klass); - }, - - /* - Runs a query on only the children of an element - */ - queryChildren: function (element, selector) { - var id = element.id, - attr = '#' + (element.id = id || 'x_' + xtag.uid()) + ' > ', - parent = element.parentNode || !container.appendChild(element); - selector = attr + (selector + '').replace(regexReplaceCommas, ',' + attr); - var result = element.parentNode.querySelectorAll(selector); - if (!id) element.removeAttribute('id'); - if (!parent) container.removeChild(element); - return toArray(result); - }, - - /* - Creates a document fragment with the content passed in - content can be - a string of HTML, an element, or an array/collection of elements - */ - createFragment: function(content) { - var template = document.createElement('template'); - if (content) { - if (content.nodeName) toArray(arguments).forEach(function(e){ - template.content.appendChild(e); - }); - else template.innerHTML = parseMultiline(content); - } - return document.importNode(template.content, true); - }, - - /* - Removes an element from the DOM for more performant node manipulation. The element - is placed back into the DOM at the place it was taken from. - */ - manipulate: function(element, fn){ - var next = element.nextSibling, - parent = element.parentNode, - returned = fn.call(element) || element; - if (next) parent.insertBefore(returned, next); - else parent.appendChild(returned); - }, - - /* PSEUDOS */ - - applyPseudos: function(key, fn, target, source) { - var listener = fn, - pseudos = {}; - if (key.match(':')) { - var matches = [], - valueFlag = 0; - key.replace(regexPseudoParens, function(match){ - if (match == '(') return ++valueFlag == 1 ? '\u276A' : '('; - return !--valueFlag ? '\u276B' : ')'; - }).replace(regexPseudoCapture, function(z, name, value, solo){ - matches.push([name || solo, value]); - }); - var i = matches.length; - while (i--) parsePseudo(function(){ - var name = matches[i][0], - value = matches[i][1]; - if (!xtag.pseudos[name]) throw "pseudo not found: " + name + " " + value; - value = (value === '' || typeof value == 'undefined') ? null : value; - var pseudo = pseudos[i] = Object.create(xtag.pseudos[name]); - pseudo.key = key; - pseudo.name = name; - pseudo.value = value; - pseudo['arguments'] = (value || '').split(','); - pseudo.action = pseudo.action || trueop; - pseudo.source = source; - pseudo.onAdd = pseudo.onAdd || noop; - pseudo.onRemove = pseudo.onRemove || noop; - var original = pseudo.listener = listener; - listener = function(){ - var output = pseudo.action.apply(this, [pseudo].concat(toArray(arguments))); - if (output === null || output === false) return output; - output = pseudo.listener.apply(this, arguments); - pseudo.listener = original; - return output; - }; - if (!target) pseudo.onAdd.call(fn, pseudo); - else target.push(pseudo); - }); - } - for (var z in pseudos) { - if (pseudos[z].onCompiled) listener = pseudos[z].onCompiled(listener, pseudos[z]) || listener; - } - return listener; - }, - - removePseudos: function(target, pseudos){ - pseudos.forEach(function(obj){ - obj.onRemove.call(target, obj); - }); - }, - - /*** Events ***/ - - parseEvent: function(type, fn) { - var pseudos = type.split(':'), - key = pseudos.shift(), - custom = xtag.customEvents[key], - event = xtag.merge({ - type: key, - stack: noop, - condition: trueop, - capture: xtag.captureEvents[key], - attach: [], - _attach: [], - pseudos: '', - _pseudos: [], - onAdd: noop, - onRemove: noop - }, custom || {}); - event.attach = toArray(event.base || event.attach); - event.chain = key + (event.pseudos.length ? ':' + event.pseudos : '') + (pseudos.length ? ':' + pseudos.join(':') : ''); - var stack = xtag.applyPseudos(event.chain, fn, event._pseudos, event); - event.stack = function(e){ - e.currentTarget = e.currentTarget || this; - var detail = e.detail || {}; - if (!detail.__stack__) return stack.apply(this, arguments); - else if (detail.__stack__ == stack) { - e.stopPropagation(); - e.cancelBubble = true; - return stack.apply(this, arguments); - } - }; - event.listener = function(e){ - var args = toArray(arguments), - output = event.condition.apply(this, args.concat([event])); - if (!output) return output; - // The second condition in this IF is to address the following Blink regression: https://code.google.com/p/chromium/issues/detail?id=367537 - // Remove this when affected browser builds with this regression fall below 5% marketshare - if (e.type != key && (e.baseEvent && e.type != e.baseEvent.type)) { - xtag.fireEvent(e.target, key, { - baseEvent: e, - detail: output !== true && (output.__stack__ = stack) ? output : { __stack__: stack } - }); - } - else return event.stack.apply(this, args); - }; - event.attach.forEach(function(name) { - event._attach.push(xtag.parseEvent(name, event.listener)); - }); - return event; - }, - - addEvent: function (element, type, fn, capture) { - var event = typeof fn == 'function' ? xtag.parseEvent(type, fn) : fn; - event._pseudos.forEach(function(obj){ - obj.onAdd.call(element, obj); - }); - event._attach.forEach(function(obj) { - xtag.addEvent(element, obj.type, obj); - }); - event.onAdd.call(element, event, event.listener); - element.addEventListener(event.type, event.stack, capture || event.capture); - return event; - }, - - addEvents: function (element, obj) { - var events = {}; - for (var z in obj) { - events[z] = xtag.addEvent(element, z, obj[z]); - } - return events; - }, - - removeEvent: function (element, type, event) { - event = event || type; - event.onRemove.call(element, event, event.listener); - xtag.removePseudos(element, event._pseudos); - event._attach.forEach(function(obj) { - xtag.removeEvent(element, obj); - }); - element.removeEventListener(event.type, event.stack); - }, - - removeEvents: function(element, obj){ - for (var z in obj) xtag.removeEvent(element, obj[z]); - }, - - fireEvent: function(element, type, options){ - var event = doc.createEvent('CustomEvent'); - options = options || {}; - event.initCustomEvent(type, - options.bubbles !== false, - options.cancelable !== false, - options.detail - ); - if (options.baseEvent) inheritEvent(event, options.baseEvent); - element.dispatchEvent(event); - } - - }; - - if (typeof define === 'function' && define.amd) define(xtag); - else if (typeof module !== 'undefined' && module.exports) module.exports = xtag; - else win.xtag = xtag; - - doc.addEventListener('WebComponentsReady', function(){ - xtag.fireEvent(doc.body, 'DOMComponentsLoaded'); - }); - -})(); diff --git a/dist/x-tag-core-with-shadowdom.min.js b/dist/x-tag-core-with-shadowdom.min.js deleted file mode 100644 index 3fa6fda..0000000 --- a/dist/x-tag-core-with-shadowdom.min.js +++ /dev/null @@ -1,5 +0,0 @@ -(function(){function e(e){if(this._element=e,e.className!=this._classCache){if(this._classCache=e.className,!this._classCache)return;var t,n=this._classCache.replace(/^\s+|\s+$/g,"").split(/\s+/);for(t=0;n.length>t;t++)a.call(this,n[t])}}function t(e,t){e.className=t.join(" ")}function n(e,t,n){Object.defineProperty?Object.defineProperty(e,t,{get:n}):e.__defineGetter__(t,n)}if(!(window.Element===void 0||"classList"in document.documentElement)){var r=Array.prototype,o=r.indexOf,i=r.slice,a=r.push,s=r.splice,c=r.join;e.prototype={add:function(e){this.contains(e)||(a.call(this,e),t(this._element,i.call(this,0)))},contains:function(e){return-1!==o.call(this,e)},item:function(e){return this[e]||null},remove:function(e){var n=o.call(this,e);-1!==n&&(s.call(this,n,1),t(this._element,i.call(this,0)))},toString:function(){return c.call(this," ")},toggle:function(e){-1===o.call(this,e)?this.add(e):this.remove(e)}},window.DOMTokenList=e,n(Element.prototype,"classList",function(){return new e(this)})}})(),function(){window.WebComponents=window.WebComponents||{flags:{}};var e="webcomponents.js",t=document.querySelector('script[src*="'+e+'"]'),n={};if(!n.noOpts){if(location.search.slice(1).split("&").forEach(function(e){var t,r=e.split("=");r[0]&&(t=r[0].match(/wc-(.+)/))&&(n[t[1]]=r[1]||!0)}),t)for(var r,o=0;r=t.attributes[o];o++)"src"!==r.name&&(n[r.name]=r.value||!0);if(n.log&&n.log.split){var i=n.log.split(",");n.log={},i.forEach(function(e){n.log[e]=!0})}else n.log={}}n.shadow=n.shadow||n.shadowdom||n.polyfill,n.shadow="native"===n.shadow?!1:n.shadow||!HTMLElement.prototype.createShadowRoot,n.register&&(window.CustomElements=window.CustomElements||{flags:{}},window.CustomElements.flags.register=n.register),WebComponents.flags=n}(),WebComponents.flags.shadow&&("undefined"==typeof WeakMap&&function(){var e=Object.defineProperty,t=Date.now()%1e9,n=function(){this.name="__st"+(1e9*Math.random()>>>0)+(t++ +"__")};n.prototype={set:function(t,n){var r=t[this.name];return r&&r[0]===t?r[1]=n:e(t,this.name,{value:[t,n],writable:!0}),this},get:function(e){var t;return(t=e[this.name])&&t[0]===e?t[1]:void 0},"delete":function(e){var t=e[this.name];return t&&t[0]===e?(t[0]=t[1]=void 0,!0):!1},has:function(e){var t=e[this.name];return t?t[0]===e:!1}},window.WeakMap=n}(),window.ShadowDOMPolyfill={},function(e){"use strict";function t(){if("undefined"!=typeof chrome&&chrome.app&&chrome.app.runtime)return!1;if(navigator.getDeviceStorage)return!1;try{var e=Function("return true;");return e()}catch(t){return!1}}function n(e){if(!e)throw Error("Assertion failed")}function r(e,t){for(var n=F(t),r=0;n.length>r;r++){var o=n[r];j(e,o,q(t,o))}return e}function o(e,t){for(var n=F(t),r=0;n.length>r;r++){var o=n[r];switch(o){case"arguments":case"caller":case"length":case"name":case"prototype":case"toString":continue}j(e,o,q(t,o))}return e}function i(e,t){for(var n=0;t.length>n;n++)if(t[n]in e)return t[n]}function a(e,t,n){W.value=n,j(e,t,W)}function s(e,t){var n=e.__proto__||Object.getPrototypeOf(e);if(U)try{F(n)}catch(r){n=n.__proto__}var o=R.get(n);if(o)return o;var i=s(n),a=E(i);return w(n,a,t),a}function c(e,t){v(e,t,!0)}function u(e,t){v(t,e,!1)}function l(e){return/^on[a-z]+$/.test(e)}function d(e){return/^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(e)}function p(e){return H&&d(e)?Function("return this.__impl4cf1e782hg__."+e):function(){return this.__impl4cf1e782hg__[e]}}function h(e){return H&&d(e)?Function("v","this.__impl4cf1e782hg__."+e+" = v"):function(t){this.__impl4cf1e782hg__[e]=t}}function f(e){return H&&d(e)?Function("return this.__impl4cf1e782hg__."+e+".apply(this.__impl4cf1e782hg__, arguments)"):function(){return this.__impl4cf1e782hg__[e].apply(this.__impl4cf1e782hg__,arguments)}}function m(e,t){try{return Object.getOwnPropertyDescriptor(e,t)}catch(n){return B}}function v(t,n,r){for(var o=F(t),i=0;o.length>i;i++){var a=o[i];if("polymerBlackList_"!==a&&!(a in n||t.polymerBlackList_&&t.polymerBlackList_[a])){U&&t.__lookupGetter__(a);var s,c,u=m(t,a);if("function"!=typeof u.value){var d=l(a);s=d?e.getEventHandlerGetter(a):p(a),(u.writable||u.set||Y)&&(c=d?e.getEventHandlerSetter(a):h(a));var v=Y||u.configurable;j(n,a,{get:s,set:c,configurable:v,enumerable:u.enumerable})}else r&&(n[a]=f(a))}}}function g(e,t,n){if(null!=e){var r=e.prototype;w(r,t,n),o(t,e)}}function w(e,t,r){var o=t.prototype;n(void 0===R.get(e)),R.set(e,t),A.set(o,e),c(e,o),r&&u(o,r),a(o,"constructor",t),t.prototype=o}function y(e,t){return R.get(t.prototype)===e}function b(e){var t=Object.getPrototypeOf(e),n=s(t),r=E(n);return w(t,r,e),r}function E(e){function t(t){e.call(this,t)}var n=Object.create(e.prototype);return n.constructor=t,t.prototype=n,t}function _(e){return e&&e.__impl4cf1e782hg__}function T(e){return!_(e)}function S(e){if(null===e)return null;n(T(e));var t=e.__wrapper8e3dd93a60__;return null!=t?t:e.__wrapper8e3dd93a60__=new(s(e,e))(e)}function M(e){return null===e?null:(n(_(e)),e.__impl4cf1e782hg__)}function C(e){return e.__impl4cf1e782hg__}function L(e,t){t.__impl4cf1e782hg__=e,e.__wrapper8e3dd93a60__=t}function N(e){return e&&_(e)?M(e):e}function O(e){return e&&!_(e)?S(e):e}function P(e,t){null!==t&&(n(T(e)),n(void 0===t||_(t)),e.__wrapper8e3dd93a60__=t)}function D(e,t,n){X.get=n,j(e.prototype,t,X)}function x(e,t){D(e,t,function(){return S(this.__impl4cf1e782hg__[t])})}function I(e,t){e.forEach(function(e){t.forEach(function(t){e.prototype[t]=function(){var e=O(this);return e[t].apply(e,arguments)}})})}var R=new WeakMap,A=new WeakMap,k=Object.create(null),H=t(),j=Object.defineProperty,F=Object.getOwnPropertyNames,q=Object.getOwnPropertyDescriptor,W={value:void 0,configurable:!0,enumerable:!1,writable:!0};F(window);var U=/Firefox/.test(navigator.userAgent),B={get:function(){},set:function(){},configurable:!0,enumerable:!0},Y=function(){var e=Object.getOwnPropertyDescriptor(Node.prototype,"nodeType");return e&&!e.get&&!e.set}(),X={get:void 0,configurable:!0,enumerable:!0};e.addForwardingProperties=c,e.assert=n,e.constructorTable=R,e.defineGetter=D,e.defineWrapGetter=x,e.forwardMethodsToWrapper=I,e.isIdentifierName=d,e.isWrapper=_,e.isWrapperFor=y,e.mixin=r,e.nativePrototypeTable=A,e.oneOf=i,e.registerObject=b,e.registerWrapper=g,e.rewrap=P,e.setWrapper=L,e.unsafeUnwrap=C,e.unwrap=M,e.unwrapIfNeeded=N,e.wrap=S,e.wrapIfNeeded=O,e.wrappers=k}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e,t,n){return{index:e,removed:t,addedCount:n}}function n(){}var r=0,o=1,i=2,a=3;n.prototype={calcEditDistances:function(e,t,n,r,o,i){for(var a=i-o+1,s=n-t+1,c=Array(a),u=0;a>u;u++)c[u]=Array(s),c[u][0]=u;for(var l=0;s>l;l++)c[0][l]=l;for(var u=1;a>u;u++)for(var l=1;s>l;l++)if(this.equals(e[t+l-1],r[o+u-1]))c[u][l]=c[u-1][l-1];else{var d=c[u-1][l]+1,p=c[u][l-1]+1;c[u][l]=p>d?d:p}return c},spliceOperationsFromEditDistances:function(e){for(var t=e.length-1,n=e[0].length-1,s=e[t][n],c=[];t>0||n>0;)if(0!=t)if(0!=n){var u,l=e[t-1][n-1],d=e[t-1][n],p=e[t][n-1];u=p>d?l>d?d:l:l>p?p:l,u==l?(l==s?c.push(r):(c.push(o),s=l),t--,n--):u==d?(c.push(a),t--,s=d):(c.push(i),n--,s=p)}else c.push(a),t--;else c.push(i),n--;return c.reverse(),c},calcSplices:function(e,n,s,c,u,l){var d=0,p=0,h=Math.min(s-n,l-u);if(0==n&&0==u&&(d=this.sharedPrefix(e,c,h)),s==e.length&&l==c.length&&(p=this.sharedSuffix(e,c,h-d)),n+=d,u+=d,s-=p,l-=p,0==s-n&&0==l-u)return[];if(n==s){for(var f=t(n,[],0);l>u;)f.removed.push(c[u++]);return[f]}if(u==l)return[t(n,[],s-n)];for(var m=this.spliceOperationsFromEditDistances(this.calcEditDistances(e,n,s,c,u,l)),f=void 0,v=[],g=n,w=u,y=0;m.length>y;y++)switch(m[y]){case r:f&&(v.push(f),f=void 0),g++,w++;break;case o:f||(f=t(g,[],0)),f.addedCount++,g++,f.removed.push(c[w]),w++;break;case i:f||(f=t(g,[],0)),f.addedCount++,g++;break;case a:f||(f=t(g,[],0)),f.removed.push(c[w]),w++}return f&&v.push(f),v},sharedPrefix:function(e,t,n){for(var r=0;n>r;r++)if(!this.equals(e[r],t[r]))return r;return n},sharedSuffix:function(e,t,n){for(var r=e.length,o=t.length,i=0;n>i&&this.equals(e[--r],t[--o]);)i++;return i},calculateSplices:function(e,t){return this.calcSplices(e,0,e.length,t,0,t.length)},equals:function(e,t){return e===t}},e.ArraySplice=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(){a=!1;var e=i.slice(0);i=[];for(var t=0;e.length>t;t++)e[t]()}function n(e){i.push(e),a||(a=!0,r(t,0))}var r,o=window.MutationObserver,i=[],a=!1;if(o){var s=1,c=new o(t),u=document.createTextNode(s);c.observe(u,{characterData:!0}),r=function(){s=(s+1)%2,u.data=s}}else r=window.setTimeout;e.setEndOfMicrotask=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){e.scheduled_||(e.scheduled_=!0,f.push(e),m||(l(n),m=!0))}function n(){for(m=!1;f.length;){var e=f;f=[],e.sort(function(e,t){return e.uid_-t.uid_});for(var t=0;e.length>t;t++){var n=e[t];n.scheduled_=!1;var r=n.takeRecords();i(n),r.length&&n.callback_(r,n)}}}function r(e,t){this.type=e,this.target=t,this.addedNodes=new p.NodeList,this.removedNodes=new p.NodeList,this.previousSibling=null,this.nextSibling=null,this.attributeName=null,this.attributeNamespace=null,this.oldValue=null}function o(e,t){for(;e;e=e.parentNode){var n=h.get(e);if(n)for(var r=0;n.length>r;r++){var o=n[r];o.options.subtree&&o.addTransientObserver(t)}}}function i(e){for(var t=0;e.nodes_.length>t;t++){var n=e.nodes_[t],r=h.get(n);if(!r)return;for(var o=0;r.length>o;o++){var i=r[o];i.observer===e&&i.removeTransientObservers()}}}function a(e,n,o){for(var i=Object.create(null),a=Object.create(null),s=e;s;s=s.parentNode){var c=h.get(s);if(c)for(var u=0;c.length>u;u++){var l=c[u],d=l.options;if(!(s!==e&&!d.subtree||"attributes"===n&&!d.attributes||"attributes"===n&&d.attributeFilter&&(null!==o.namespace||-1===d.attributeFilter.indexOf(o.name))||"characterData"===n&&!d.characterData||"childList"===n&&!d.childList)){var p=l.observer;i[p.uid_]=p,("attributes"===n&&d.attributeOldValue||"characterData"===n&&d.characterDataOldValue)&&(a[p.uid_]=o.oldValue)}}}for(var f in i){var p=i[f],m=new r(n,e);"name"in o&&"namespace"in o&&(m.attributeName=o.name,m.attributeNamespace=o.namespace),o.addedNodes&&(m.addedNodes=o.addedNodes),o.removedNodes&&(m.removedNodes=o.removedNodes),o.previousSibling&&(m.previousSibling=o.previousSibling),o.nextSibling&&(m.nextSibling=o.nextSibling),void 0!==a[f]&&(m.oldValue=a[f]),t(p),p.records_.push(m)}}function s(e){if(this.childList=!!e.childList,this.subtree=!!e.subtree,this.attributes="attributes"in e||!("attributeOldValue"in e||"attributeFilter"in e)?!!e.attributes:!0,this.characterData="characterDataOldValue"in e&&!("characterData"in e)?!0:!!e.characterData,!this.attributes&&(e.attributeOldValue||"attributeFilter"in e)||!this.characterData&&e.characterDataOldValue)throw new TypeError;if(this.characterData=!!e.characterData,this.attributeOldValue=!!e.attributeOldValue,this.characterDataOldValue=!!e.characterDataOldValue,"attributeFilter"in e){if(null==e.attributeFilter||"object"!=typeof e.attributeFilter)throw new TypeError;this.attributeFilter=v.call(e.attributeFilter)}else this.attributeFilter=null}function c(e){this.callback_=e,this.nodes_=[],this.records_=[],this.uid_=++g,this.scheduled_=!1}function u(e,t,n){this.observer=e,this.target=t,this.options=n,this.transientObservedNodes=[]}var l=e.setEndOfMicrotask,d=e.wrapIfNeeded,p=e.wrappers,h=new WeakMap,f=[],m=!1,v=Array.prototype.slice,g=0;c.prototype={constructor:c,observe:function(e,t){e=d(e);var n,r=new s(t),o=h.get(e);o||h.set(e,o=[]);for(var i=0;o.length>i;i++)o[i].observer===this&&(n=o[i],n.removeTransientObservers(),n.options=r);n||(n=new u(this,e,r),o.push(n),this.nodes_.push(e))},disconnect:function(){this.nodes_.forEach(function(e){for(var t=h.get(e),n=0;t.length>n;n++){var r=t[n];if(r.observer===this){t.splice(n,1);break}}},this),this.records_=[]},takeRecords:function(){var e=this.records_;return this.records_=[],e}},u.prototype={addTransientObserver:function(e){if(e!==this.target){t(this.observer),this.transientObservedNodes.push(e);var n=h.get(e);n||h.set(e,n=[]),n.push(this)}},removeTransientObservers:function(){var e=this.transientObservedNodes;this.transientObservedNodes=[];for(var t=0;e.length>t;t++)for(var n=e[t],r=h.get(n),o=0;r.length>o;o++)if(r[o]===this){r.splice(o,1);break}}},e.enqueueMutation=a,e.registerTransientObservers=o,e.wrappers.MutationObserver=c,e.wrappers.MutationRecord=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e,t){this.root=e,this.parent=t}function n(e,t){if(e.treeScope_!==t){e.treeScope_=t;for(var r=e.shadowRoot;r;r=r.olderShadowRoot)r.treeScope_.parent=t;for(var o=e.firstChild;o;o=o.nextSibling)n(o,t)}}function r(n){if(n instanceof e.wrappers.Window,n.treeScope_)return n.treeScope_;var o,i=n.parentNode;return o=i?r(i):new t(n,null),n.treeScope_=o}t.prototype={get renderer(){return this.root instanceof e.wrappers.ShadowRoot?e.getRendererForHost(this.root.host):null},contains:function(e){for(;e;e=e.parent)if(e===this)return!0;return!1}},e.TreeScope=t,e.getTreeScope=r,e.setTreeScope=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return e instanceof Y.ShadowRoot}function n(e){return H(e).root}function r(e,r){var s=[],c=e;for(s.push(c);c;){var u=a(c);if(u&&u.length>0){for(var l=0;u.length>l;l++){var p=u[l];if(i(p)){var h=n(p),f=h.olderShadowRoot;f&&s.push(f)}s.push(p)}c=u[u.length-1]}else if(t(c)){if(d(e,c)&&o(r))break;c=c.host,s.push(c)}else c=c.parentNode,c&&s.push(c)}return s}function o(e){if(!e)return!1;switch(e.type){case"abort":case"error":case"select":case"change":case"load":case"reset":case"resize":case"scroll":case"selectstart":return!0}return!1}function i(e){return e instanceof HTMLShadowElement}function a(t){return e.getDestinationInsertionPoints(t)}function s(e,t){if(0===e.length)return t;t instanceof Y.Window&&(t=t.document);for(var n=H(t),r=e[0],o=H(r),i=u(n,o),a=0;e.length>a;a++){var s=e[a];if(H(s)===i)return s}return e[e.length-1]}function c(e){for(var t=[];e;e=e.parent)t.push(e);return t}function u(e,t){for(var n=c(e),r=c(t),o=null;n.length>0&&r.length>0;){var i=n.pop(),a=r.pop();if(i!==a)break;o=i}return o}function l(e,t,n){t instanceof Y.Window&&(t=t.document);var o,i=H(t),a=H(n),s=r(n,e),o=u(i,a);o||(o=a.root);for(var c=o;c;c=c.parent)for(var l=0;s.length>l;l++){var d=s[l];if(H(d)===c)return d}return null}function d(e,t){return H(e)===H(t)}function p(e){if(!z.get(e)&&(z.set(e,!0),f(B(e),B(e.target)),X)){var t=X;throw X=null,t}}function h(e){switch(e.type){case"load":case"beforeunload":case"unload":return!0}return!1}function f(t,n){if(G.get(t))throw Error("InvalidStateError");G.set(t,!0),e.renderAllPending();var o,i,a;if(h(t)&&!t.bubbles){var s=n;s instanceof Y.Document&&(a=s.defaultView)&&(i=s,o=[])}if(!o)if(n instanceof Y.Window)a=n,o=[];else if(o=r(n,t),!h(t)){var s=o[o.length-1];s instanceof Y.Document&&(a=s.defaultView)}return nt.set(t,o),m(t,o,a,i)&&v(t,o,a,i)&&g(t,o,a,i),J.set(t,rt),$.delete(t,null),G.delete(t),t.defaultPrevented}function m(e,t,n,r){var o=ot;if(n&&!w(n,e,o,t,r))return!1;for(var i=t.length-1;i>0;i--)if(!w(t[i],e,o,t,r))return!1;return!0}function v(e,t,n,r){var o=it,i=t[0]||n;return w(i,e,o,t,r)}function g(e,t,n,r){for(var o=at,i=1;t.length>i;i++)if(!w(t[i],e,o,t,r))return;n&&t.length>0&&w(n,e,o,t,r)}function w(e,t,n,r,o){var i=V.get(e);if(!i)return!0;var a=o||s(r,e);if(a===e){if(n===ot)return!0;n===at&&(n=it)}else if(n===at&&!t.bubbles)return!0;if("relatedTarget"in t){var c=U(t),u=c.relatedTarget;if(u){if(u instanceof Object&&u.addEventListener){var d=B(u),p=l(t,e,d);if(p===a)return!0}else p=null;Z.set(t,p)}}J.set(t,n);var h=t.type,f=!1;K.set(t,a),$.set(t,e),i.depth++;for(var m=0,v=i.length;v>m;m++){var g=i[m];if(g.removed)f=!0;else if(!(g.type!==h||!g.capture&&n===ot||g.capture&&n===at))try{if("function"==typeof g.handler?g.handler.call(e,t):g.handler.handleEvent(t),et.get(t))return!1}catch(w){X||(X=w)}}if(i.depth--,f&&0===i.depth){var y=i.slice();i.length=0;for(var m=0;y.length>m;m++)y[m].removed||i.push(y[m])}return!Q.get(t)}function y(e,t,n){this.type=e,this.handler=t,this.capture=Boolean(n)}function b(e,t){if(!(e instanceof st))return B(S(st,"Event",e,t));var n=e;return yt||"beforeunload"!==n.type||this instanceof M?(q(n,this),void 0):new M(n)}function E(e){return e&&e.relatedTarget?Object.create(e,{relatedTarget:{value:U(e.relatedTarget)}}):e}function _(e,t,n){var r=window[e],o=function(t,n){return t instanceof r?(q(t,this),void 0):B(S(r,e,t,n))};if(o.prototype=Object.create(t.prototype),n&&j(o.prototype,n),r)try{F(r,o,new r("temp"))}catch(i){F(r,o,document.createEvent(e))}return o}function T(e,t){return function(){arguments[t]=U(arguments[t]);var n=U(this);n[e].apply(n,arguments)}}function S(e,t,n,r){if(gt)return new e(n,E(r));var o=U(document.createEvent(t)),i=vt[t],a=[n];return Object.keys(i).forEach(function(e){var t=null!=r&&e in r?r[e]:i[e];"relatedTarget"===e&&(t=U(t)),a.push(t)}),o["init"+t].apply(o,a),o}function M(e){b.call(this,e)}function C(e){return"function"==typeof e?!0:e&&e.handleEvent}function L(e){switch(e){case"DOMAttrModified":case"DOMAttributeNameChanged":case"DOMCharacterDataModified":case"DOMElementNameChanged":case"DOMNodeInserted":case"DOMNodeInsertedIntoDocument":case"DOMNodeRemoved":case"DOMNodeRemovedFromDocument":case"DOMSubtreeModified":return!0}return!1}function N(e){q(e,this)}function O(e){return e instanceof Y.ShadowRoot&&(e=e.host),U(e)}function P(e,t){var n=V.get(e);if(n)for(var r=0;n.length>r;r++)if(!n[r].removed&&n[r].type===t)return!0;return!1}function D(e,t){for(var n=U(e);n;n=n.parentNode)if(P(B(n),t))return!0;return!1}function x(e){k(e,Et)}function I(t,n,o,i){e.renderAllPending();var a=B(_t.call(W(n),o,i));if(!a)return null;var c=r(a,null),u=c.lastIndexOf(t);return-1==u?null:(c=c.slice(0,u),s(c,t))}function R(e){return function(){var t=tt.get(this);return t&&t[e]&&t[e].value||null}}function A(e){var t=e.slice(2);return function(n){var r=tt.get(this);r||(r=Object.create(null),tt.set(this,r));var o=r[e];if(o&&this.removeEventListener(t,o.wrapped,!1),"function"==typeof n){var i=function(t){var r=n.call(this,t);r===!1?t.preventDefault():"onbeforeunload"===e&&"string"==typeof r&&(t.returnValue=r)};this.addEventListener(t,i,!1),r[e]={value:n,wrapped:i}}}}var k=e.forwardMethodsToWrapper,H=e.getTreeScope,j=e.mixin,F=e.registerWrapper,q=e.setWrapper,W=e.unsafeUnwrap,U=e.unwrap,B=e.wrap,Y=e.wrappers;new WeakMap;var X,V=new WeakMap,z=new WeakMap,G=new WeakMap,K=new WeakMap,$=new WeakMap,Z=new WeakMap,J=new WeakMap,Q=new WeakMap,et=new WeakMap,tt=new WeakMap,nt=new WeakMap,rt=0,ot=1,it=2,at=3;y.prototype={equals:function(e){return this.handler===e.handler&&this.type===e.type&&this.capture===e.capture},get removed(){return null===this.handler},remove:function(){this.handler=null}};var st=window.Event;st.prototype.polymerBlackList_={returnValue:!0,keyLocation:!0},b.prototype={get target(){return K.get(this)},get currentTarget(){return $.get(this)},get eventPhase(){return J.get(this)},get path(){var e=nt.get(this);return e?e.slice():[]},stopPropagation:function(){Q.set(this,!0)},stopImmediatePropagation:function(){Q.set(this,!0),et.set(this,!0)}};var ct=function(){var e=document.createEvent("Event");return e.initEvent("test",!0,!0),e.preventDefault(),e.defaultPrevented}();ct||(b.prototype.preventDefault=function(){this.cancelable&&(W(this).preventDefault(),Object.defineProperty(this,"defaultPrevented",{get:function(){return!0},configurable:!0}))}),F(st,b,document.createEvent("Event"));var ut=_("UIEvent",b),lt=_("CustomEvent",b),dt={get relatedTarget(){var e=Z.get(this);return void 0!==e?e:B(U(this).relatedTarget)}},pt=j({initMouseEvent:T("initMouseEvent",14)},dt),ht=j({initFocusEvent:T("initFocusEvent",5)},dt),ft=_("MouseEvent",ut,pt),mt=_("FocusEvent",ut,ht),vt=Object.create(null),gt=function(){try{new window.FocusEvent("focus")}catch(e){return!1}return!0}();if(!gt){var wt=function(e,t,n){if(n){var r=vt[n];t=j(j({},r),t)}vt[e]=t};wt("Event",{bubbles:!1,cancelable:!1}),wt("CustomEvent",{detail:null},"Event"),wt("UIEvent",{view:null,detail:0},"Event"),wt("MouseEvent",{screenX:0,screenY:0,clientX:0,clientY:0,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,button:0,relatedTarget:null},"UIEvent"),wt("FocusEvent",{relatedTarget:null},"UIEvent")}var yt=window.BeforeUnloadEvent;M.prototype=Object.create(b.prototype),j(M.prototype,{get returnValue(){return W(this).returnValue},set returnValue(e){W(this).returnValue=e}}),yt&&F(yt,M);var bt=window.EventTarget,Et=["addEventListener","removeEventListener","dispatchEvent"];[Node,Window].forEach(function(e){var t=e.prototype;Et.forEach(function(e){Object.defineProperty(t,e+"_",{value:t[e]})})}),N.prototype={addEventListener:function(e,t,n){if(C(t)&&!L(e)){var r=new y(e,t,n),o=V.get(this);if(o){for(var i=0;o.length>i;i++)if(r.equals(o[i]))return}else o=[],o.depth=0,V.set(this,o);o.push(r);var a=O(this);a.addEventListener_(e,p,!0)}},removeEventListener:function(e,t,n){n=Boolean(n);var r=V.get(this);if(r){for(var o=0,i=!1,a=0;r.length>a;a++)r[a].type===e&&r[a].capture===n&&(o++,r[a].handler===t&&(i=!0,r[a].remove()));if(i&&1===o){var s=O(this);s.removeEventListener_(e,p,!0)}}},dispatchEvent:function(t){var n=U(t),r=n.type;z.set(n,!1),e.renderAllPending();var o;D(this,r)||(o=function(){},this.addEventListener(r,o,!0));try{return U(this).dispatchEvent_(n)}finally{o&&this.removeEventListener(r,o,!0)}}},bt&&F(bt,N);var _t=document.elementFromPoint;e.elementFromPoint=I,e.getEventHandlerGetter=R,e.getEventHandlerSetter=A,e.wrapEventTargetMethods=x,e.wrappers.BeforeUnloadEvent=M,e.wrappers.CustomEvent=lt,e.wrappers.Event=b,e.wrappers.EventTarget=N,e.wrappers.FocusEvent=mt,e.wrappers.MouseEvent=ft,e.wrappers.UIEvent=ut}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e,t){Object.defineProperty(e,t,m)}function n(e){u(e,this)}function r(){this.length=0,t(this,"length")}function o(e){for(var t=new r,o=0;e.length>o;o++)t[o]=new n(e[o]);return t.length=o,t}function i(e){a.call(this,e)}var a=e.wrappers.UIEvent,s=e.mixin,c=e.registerWrapper,u=e.setWrapper,l=e.unsafeUnwrap,d=e.wrap,p=window.TouchEvent;if(p){var h;try{h=document.createEvent("TouchEvent")}catch(f){return}var m={enumerable:!1};n.prototype={get target(){return d(l(this).target)}};var v={configurable:!0,enumerable:!0,get:null};["clientX","clientY","screenX","screenY","pageX","pageY","identifier","webkitRadiusX","webkitRadiusY","webkitRotationAngle","webkitForce"].forEach(function(e){v.get=function(){return l(this)[e]},Object.defineProperty(n.prototype,e,v)}),r.prototype={item:function(e){return this[e]}},i.prototype=Object.create(a.prototype),s(i.prototype,{get touches(){return o(l(this).touches)},get targetTouches(){return o(l(this).targetTouches)},get changedTouches(){return o(l(this).changedTouches)},initTouchEvent:function(){throw Error("Not implemented")}}),c(p,i,h),e.wrappers.Touch=n,e.wrappers.TouchEvent=i,e.wrappers.TouchList=r}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e,t){Object.defineProperty(e,t,s)}function n(){this.length=0,t(this,"length")}function r(e){if(null==e)return e;for(var t=new n,r=0,o=e.length;o>r;r++)t[r]=a(e[r]);return t.length=o,t}function o(e,t){e.prototype[t]=function(){return r(i(this)[t].apply(i(this),arguments))}}var i=e.unsafeUnwrap,a=e.wrap,s={enumerable:!1};n.prototype={item:function(e){return this[e]}},t(n.prototype,"item"),e.wrappers.NodeList=n,e.addWrapNodeListMethod=o,e.wrapNodeList=r}(window.ShadowDOMPolyfill),function(e){"use strict";e.wrapHTMLCollection=e.wrapNodeList,e.wrappers.HTMLCollection=e.wrappers.NodeList}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){C(e instanceof _)}function n(e){var t=new S;return t[0]=e,t.length=1,t}function r(e,t,n){N(t,"childList",{removedNodes:n,previousSibling:e.previousSibling,nextSibling:e.nextSibling})}function o(e,t){N(e,"childList",{removedNodes:t})}function i(e,t,r,o){if(e instanceof DocumentFragment){var i=s(e);W=!0;for(var a=i.length-1;a>=0;a--)e.removeChild(i[a]),i[a].parentNode_=t;W=!1;for(var a=0;i.length>a;a++)i[a].previousSibling_=i[a-1]||r,i[a].nextSibling_=i[a+1]||o;return r&&(r.nextSibling_=i[0]),o&&(o.previousSibling_=i[i.length-1]),i}var i=n(e),c=e.parentNode;return c&&c.removeChild(e),e.parentNode_=t,e.previousSibling_=r,e.nextSibling_=o,r&&(r.nextSibling_=e),o&&(o.previousSibling_=e),i}function a(e){if(e instanceof DocumentFragment)return s(e);var t=n(e),o=e.parentNode;return o&&r(e,o,t),t}function s(e){for(var t=new S,n=0,r=e.firstChild;r;r=r.nextSibling)t[n++]=r;return t.length=n,o(e,t),t}function c(e){return e}function u(e,t){R(e,t),e.nodeIsInserted_()}function l(e,t){for(var n=O(t),r=0;e.length>r;r++)u(e[r],n)}function d(e){R(e,new M(e,null))}function p(e){for(var t=0;e.length>t;t++)d(e[t])}function h(e,t){var n=e.nodeType===_.DOCUMENT_NODE?e:e.ownerDocument;n!==t.ownerDocument&&n.adoptNode(t)}function f(t,n){if(n.length){var r=t.ownerDocument;if(r!==n[0].ownerDocument)for(var o=0;n.length>o;o++)e.adoptNodeNoRemove(n[o],r)}}function m(e,t){f(e,t);var n=t.length;if(1===n)return k(t[0]);for(var r=k(e.ownerDocument.createDocumentFragment()),o=0;n>o;o++)r.appendChild(k(t[o]));return r}function v(e){if(void 0!==e.firstChild_)for(var t=e.firstChild_;t;){var n=t;t=t.nextSibling_,n.parentNode_=n.previousSibling_=n.nextSibling_=void 0}e.firstChild_=e.lastChild_=void 0}function g(e){if(e.invalidateShadowRenderer()){for(var t=e.firstChild;t;){C(t.parentNode===e);var n=t.nextSibling,r=k(t),o=r.parentNode;o&&K.call(o,r),t.previousSibling_=t.nextSibling_=t.parentNode_=null,t=n}e.firstChild_=e.lastChild_=null}else for(var n,i=k(e),a=i.firstChild;a;)n=a.nextSibling,K.call(i,a),a=n}function w(e){var t=e.parentNode;return t&&t.invalidateShadowRenderer()}function y(e){for(var t,n=0;e.length>n;n++)t=e[n],t.parentNode.removeChild(t)}function b(e,t,n){var r;if(r=n?j(U.call(n,A(e),!1)):j(B.call(A(e),!1)),t){for(var o=e.firstChild;o;o=o.nextSibling)r.appendChild(b(o,!0,n));if(e instanceof q.HTMLTemplateElement)for(var i=r.content,o=e.content.firstChild;o;o=o.nextSibling)i.appendChild(b(o,!0,n))}return r}function E(e,t){if(!t||O(e)!==O(t))return!1;for(var n=t;n;n=n.parentNode)if(n===e)return!0;return!1}function _(e){C(e instanceof Y),T.call(this,e),this.parentNode_=void 0,this.firstChild_=void 0,this.lastChild_=void 0,this.nextSibling_=void 0,this.previousSibling_=void 0,this.treeScope_=void 0}var T=e.wrappers.EventTarget,S=e.wrappers.NodeList,M=e.TreeScope,C=e.assert,L=e.defineWrapGetter,N=e.enqueueMutation,O=e.getTreeScope,P=e.isWrapper,D=e.mixin,x=e.registerTransientObservers,I=e.registerWrapper,R=e.setTreeScope,A=e.unsafeUnwrap,k=e.unwrap,H=e.unwrapIfNeeded,j=e.wrap,F=e.wrapIfNeeded,q=e.wrappers,W=!1,U=document.importNode,B=window.Node.prototype.cloneNode,Y=window.Node,X=window.DocumentFragment;Y.prototype.appendChild;var V=Y.prototype.compareDocumentPosition,z=Y.prototype.isEqualNode,G=Y.prototype.insertBefore,K=Y.prototype.removeChild,$=Y.prototype.replaceChild,Z=/Trident|Edge/.test(navigator.userAgent),J=Z?function(e,t){try{K.call(e,t)}catch(n){if(!(e instanceof X))throw n}}:function(e,t){K.call(e,t)};_.prototype=Object.create(T.prototype),D(_.prototype,{appendChild:function(e){return this.insertBefore(e,null)},insertBefore:function(e,n){t(e);var r;n?P(n)?r=k(n):(r=n,n=j(r)):(n=null,r=null),n&&C(n.parentNode===this);var o,s=n?n.previousSibling:this.lastChild,c=!this.invalidateShadowRenderer()&&!w(e);if(o=c?a(e):i(e,this,s,n),c)h(this,e),v(this),G.call(A(this),k(e),r);else{s||(this.firstChild_=o[0]),n||(this.lastChild_=o[o.length-1],void 0===this.firstChild_&&(this.firstChild_=this.firstChild));var u=r?r.parentNode:A(this);u?G.call(u,m(this,o),r):f(this,o)}return N(this,"childList",{addedNodes:o,nextSibling:n,previousSibling:s}),l(o,this),e},removeChild:function(e){if(t(e),e.parentNode!==this){var r=!1;this.childNodes;for(var o=this.firstChild;o;o=o.nextSibling)if(o===e){r=!0;break}if(!r)throw Error("NotFoundError")}var i=k(e),a=e.nextSibling,s=e.previousSibling;if(this.invalidateShadowRenderer()){var c=this.firstChild,u=this.lastChild,l=i.parentNode;l&&J(l,i),c===e&&(this.firstChild_=a),u===e&&(this.lastChild_=s),s&&(s.nextSibling_=a),a&&(a.previousSibling_=s),e.previousSibling_=e.nextSibling_=e.parentNode_=void 0}else v(this),J(A(this),i);return W||N(this,"childList",{removedNodes:n(e),nextSibling:a,previousSibling:s}),x(this,e),e},replaceChild:function(e,r){t(e);var o;if(P(r)?o=k(r):(o=r,r=j(o)),r.parentNode!==this)throw Error("NotFoundError");var s,c=r.nextSibling,u=r.previousSibling,p=!this.invalidateShadowRenderer()&&!w(e);return p?s=a(e):(c===e&&(c=e.nextSibling),s=i(e,this,u,c)),p?(h(this,e),v(this),$.call(A(this),k(e),o)):(this.firstChild===r&&(this.firstChild_=s[0]),this.lastChild===r&&(this.lastChild_=s[s.length-1]),r.previousSibling_=r.nextSibling_=r.parentNode_=void 0,o.parentNode&&$.call(o.parentNode,m(this,s),o)),N(this,"childList",{addedNodes:s,removedNodes:n(r),nextSibling:c,previousSibling:u}),d(r),l(s,this),r},nodeIsInserted_:function(){for(var e=this.firstChild;e;e=e.nextSibling)e.nodeIsInserted_()},hasChildNodes:function(){return null!==this.firstChild},get parentNode(){return void 0!==this.parentNode_?this.parentNode_:j(A(this).parentNode)},get firstChild(){return void 0!==this.firstChild_?this.firstChild_:j(A(this).firstChild)},get lastChild(){return void 0!==this.lastChild_?this.lastChild_:j(A(this).lastChild)},get nextSibling(){return void 0!==this.nextSibling_?this.nextSibling_:j(A(this).nextSibling)},get previousSibling(){return void 0!==this.previousSibling_?this.previousSibling_:j(A(this).previousSibling)},get parentElement(){for(var e=this.parentNode;e&&e.nodeType!==_.ELEMENT_NODE;)e=e.parentNode;return e},get textContent(){for(var e="",t=this.firstChild;t;t=t.nextSibling)t.nodeType!=_.COMMENT_NODE&&(e+=t.textContent);return e},set textContent(e){null==e&&(e="");var t=c(this.childNodes);if(this.invalidateShadowRenderer()){if(g(this),""!==e){var n=A(this).ownerDocument.createTextNode(e);this.appendChild(n)}}else v(this),A(this).textContent=e;var r=c(this.childNodes);N(this,"childList",{addedNodes:r,removedNodes:t}),p(t),l(r,this)},get childNodes(){for(var e=new S,t=0,n=this.firstChild;n;n=n.nextSibling)e[t++]=n;return e.length=t,e},cloneNode:function(e){return b(this,e)},contains:function(e){return E(this,F(e))},compareDocumentPosition:function(e){return V.call(A(this),H(e))},isEqualNode:function(e){return z.call(A(this),H(e))},normalize:function(){for(var e,t,n=c(this.childNodes),r=[],o="",i=0;n.length>i;i++)t=n[i],t.nodeType===_.TEXT_NODE?e||t.data.length?e?(o+=t.data,r.push(t)):e=t:this.removeChild(t):(e&&r.length&&(e.data+=o,y(r)),r=[],o="",e=null,t.childNodes.length&&t.normalize());e&&r.length&&(e.data+=o,y(r))}}),L(_,"ownerDocument"),I(Y,_,document.createDocumentFragment()),delete _.prototype.querySelector,delete _.prototype.querySelectorAll,_.prototype=D(Object.create(T.prototype),_.prototype),e.cloneNode=b,e.nodeWasAdded=u,e.nodeWasRemoved=d,e.nodesWereAdded=l,e.nodesWereRemoved=p,e.originalInsertBefore=G,e.originalRemoveChild=K,e.snapshotNodeList=c,e.wrappers.Node=_}(window.ShadowDOMPolyfill),function(e){"use strict";function t(t,n,r,o){for(var i=null,a=null,s=0,c=t.length;c>s;s++)i=y(t[s]),!o&&(a=g(i).root)&&a instanceof e.wrappers.ShadowRoot||(r[n++]=i);return n}function n(e){return(e+"").replace(/\/deep\/|::shadow|>>>/g," ")}function r(e){return(e+"").replace(/:host\(([^\s]+)\)/g,"$1").replace(/([^\s]):host/g,"$1").replace(":host","*").replace(/\^|\/shadow\/|\/shadow-deep\/|::shadow|\/deep\/|::content|>>>/g," ")}function o(e,t){for(var n,r=e.firstElementChild;r;){if(r.matches(t))return r;if(n=o(r,t))return n;r=r.nextElementSibling}return null}function i(e,t){return e.matches(t)}function a(e,t,n){var r=e.localName;return r===t||r===n&&e.namespaceURI===P}function s(){return!0}function c(e,t,n){return e.localName===n}function u(e,t){return e.namespaceURI===t}function l(e,t,n){return e.namespaceURI===t&&e.localName===n}function d(e,t,n,r,o,i){for(var a=e.firstElementChild;a;)r(a,o,i)&&(n[t++]=a),t=d(a,t,n,r,o,i),a=a.nextElementSibling;return t}function p(n,r,o,i,a){var s,c=w(this),u=g(this).root;if(u instanceof e.wrappers.ShadowRoot)return d(this,r,o,n,i,null); -if(c instanceof N)s=T.call(c,i);else{if(!(c instanceof O))return d(this,r,o,n,i,null);s=_.call(c,i)}return t(s,r,o,a)}function h(n,r,o,i,a){var s,c=w(this),u=g(this).root;if(u instanceof e.wrappers.ShadowRoot)return d(this,r,o,n,i,a);if(c instanceof N)s=M.call(c,i,a);else{if(!(c instanceof O))return d(this,r,o,n,i,a);s=S.call(c,i,a)}return t(s,r,o,!1)}function f(n,r,o,i,a){var s,c=w(this),u=g(this).root;if(u instanceof e.wrappers.ShadowRoot)return d(this,r,o,n,i,a);if(c instanceof N)s=L.call(c,i,a);else{if(!(c instanceof O))return d(this,r,o,n,i,a);s=C.call(c,i,a)}return t(s,r,o,!1)}var m=e.wrappers.HTMLCollection,v=e.wrappers.NodeList,g=e.getTreeScope,w=e.unsafeUnwrap,y=e.wrap,b=document.querySelector,E=document.documentElement.querySelector,_=document.querySelectorAll,T=document.documentElement.querySelectorAll,S=document.getElementsByTagName,M=document.documentElement.getElementsByTagName,C=document.getElementsByTagNameNS,L=document.documentElement.getElementsByTagNameNS,N=window.Element,O=window.HTMLDocument||window.Document,P="http://www.w3.org/1999/xhtml",D={querySelector:function(t){var r=n(t),i=r!==t;t=r;var a,s=w(this),c=g(this).root;if(c instanceof e.wrappers.ShadowRoot)return o(this,t);if(s instanceof N)a=y(E.call(s,t));else{if(!(s instanceof O))return o(this,t);a=y(b.call(s,t))}return a?!i&&(c=g(a).root)&&c instanceof e.wrappers.ShadowRoot?o(this,t):a:a},querySelectorAll:function(e){var t=n(e),r=t!==e;e=t;var o=new v;return o.length=p.call(this,i,0,o,e,r),o}},x={matches:function(t){return t=r(t),e.originalMatches.call(w(this),t)}},I={getElementsByTagName:function(e){var t=new m,n="*"===e?s:a;return t.length=h.call(this,n,0,t,e,e.toLowerCase()),t},getElementsByClassName:function(e){return this.querySelectorAll("."+e)},getElementsByTagNameNS:function(e,t){var n=new m,r=null;return r="*"===e?"*"===t?s:c:"*"===t?u:l,n.length=f.call(this,r,0,n,e||null,t),n}};e.GetElementsByInterface=I,e.SelectorsInterface=D,e.MatchesInterface=x}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){for(;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.nextSibling;return e}function n(e){for(;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.previousSibling;return e}var r=e.wrappers.NodeList,o={get firstElementChild(){return t(this.firstChild)},get lastElementChild(){return n(this.lastChild)},get childElementCount(){for(var e=0,t=this.firstElementChild;t;t=t.nextElementSibling)e++;return e},get children(){for(var e=new r,t=0,n=this.firstElementChild;n;n=n.nextElementSibling)e[t++]=n;return e.length=t,e},remove:function(){var e=this.parentNode;e&&e.removeChild(this)}},i={get nextElementSibling(){return t(this.nextSibling)},get previousElementSibling(){return n(this.previousSibling)}},a={getElementById:function(e){return/[ \t\n\r\f]/.test(e)?null:this.querySelector('[id="'+e+'"]')}};e.ChildNodeInterface=i,e.NonElementParentNodeInterface=a,e.ParentNodeInterface=o}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r.call(this,e)}var n=e.ChildNodeInterface,r=e.wrappers.Node,o=e.enqueueMutation,i=e.mixin,a=e.registerWrapper,s=e.unsafeUnwrap,c=window.CharacterData;t.prototype=Object.create(r.prototype),i(t.prototype,{get nodeValue(){return this.data},set nodeValue(e){this.data=e},get textContent(){return this.data},set textContent(e){this.data=e},get data(){return s(this).data},set data(e){var t=s(this).data;o(this,"characterData",{oldValue:t}),s(this).data=e}}),i(t.prototype,n),a(c,t,document.createTextNode("")),e.wrappers.CharacterData=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return e>>>0}function n(e){r.call(this,e)}var r=e.wrappers.CharacterData;e.enqueueMutation;var o=e.mixin,i=e.registerWrapper,a=window.Text;n.prototype=Object.create(r.prototype),o(n.prototype,{splitText:function(e){e=t(e);var n=this.data;if(e>n.length)throw Error("IndexSizeError");var r=n.slice(0,e),o=n.slice(e);this.data=r;var i=this.ownerDocument.createTextNode(o);return this.parentNode&&this.parentNode.insertBefore(i,this.nextSibling),i}}),i(a,n,document.createTextNode("")),e.wrappers.Text=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return i(e).getAttribute("class")}function n(e,t){a(e,"attributes",{name:"class",namespace:null,oldValue:t})}function r(t){e.invalidateRendererBasedOnAttribute(t,"class")}function o(e,o,i){var a=e.ownerElement_;if(null==a)return o.apply(e,i);var s=t(a),c=o.apply(e,i);return t(a)!==s&&(n(a,s),r(a)),c}if(!window.DOMTokenList)return console.warn("Missing DOMTokenList prototype, please include a compatible classList polyfill such as http://goo.gl/uTcepH."),void 0;var i=e.unsafeUnwrap,a=e.enqueueMutation,s=DOMTokenList.prototype.add;DOMTokenList.prototype.add=function(){o(this,s,arguments)};var c=DOMTokenList.prototype.remove;DOMTokenList.prototype.remove=function(){o(this,c,arguments)};var u=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(){return o(this,u,arguments)}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(t,n){var r=t.parentNode;if(r&&r.shadowRoot){var o=e.getRendererForHost(r);o.dependsOnAttribute(n)&&o.invalidate()}}function n(e,t,n){l(e,"attributes",{name:t,namespace:null,oldValue:n})}function r(e){a.call(this,e)}var o=e.ChildNodeInterface,i=e.GetElementsByInterface,a=e.wrappers.Node,s=e.ParentNodeInterface,c=e.SelectorsInterface,u=e.MatchesInterface;e.addWrapNodeListMethod;var l=e.enqueueMutation,d=e.mixin;e.oneOf;var p=e.registerWrapper,h=e.unsafeUnwrap,f=e.wrappers,m=window.Element,v=["matches","mozMatchesSelector","msMatchesSelector","webkitMatchesSelector"].filter(function(e){return m.prototype[e]}),g=v[0],w=m.prototype[g],y=new WeakMap;r.prototype=Object.create(a.prototype),d(r.prototype,{createShadowRoot:function(){var t=new f.ShadowRoot(this);h(this).polymerShadowRoot_=t;var n=e.getRendererForHost(this);return n.invalidate(),t},get shadowRoot(){return h(this).polymerShadowRoot_||null},setAttribute:function(e,r){var o=h(this).getAttribute(e);h(this).setAttribute(e,r),n(this,e,o),t(this,e)},removeAttribute:function(e){var r=h(this).getAttribute(e);h(this).removeAttribute(e),n(this,e,r),t(this,e)},get classList(){var e=y.get(this);if(!e){if(e=h(this).classList,!e)return;e.ownerElement_=this,y.set(this,e)}return e},get className(){return h(this).className},set className(e){this.setAttribute("class",e)},get id(){return h(this).id},set id(e){this.setAttribute("id",e)}}),v.forEach(function(e){"matches"!==e&&(r.prototype[e]=function(e){return this.matches(e)})}),m.prototype.webkitCreateShadowRoot&&(r.prototype.webkitCreateShadowRoot=r.prototype.createShadowRoot),d(r.prototype,o),d(r.prototype,i),d(r.prototype,s),d(r.prototype,c),d(r.prototype,u),p(m,r,document.createElementNS(null,"x")),e.invalidateRendererBasedOnAttribute=t,e.matchesNames=v,e.originalMatches=w,e.wrappers.Element=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){switch(e){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";case" ":return" "}}function n(e){return e.replace(L,t)}function r(e){return e.replace(N,t)}function o(e){for(var t={},n=0;e.length>n;n++)t[e[n]]=!0;return t}function i(e){if(e.namespaceURI!==D)return!0;var t=e.ownerDocument.doctype;return t&&t.publicId&&t.systemId}function a(e,t){switch(e.nodeType){case Node.ELEMENT_NODE:for(var o,a=e.tagName.toLowerCase(),c="<"+a,u=e.attributes,l=0;o=u[l];l++)c+=" "+o.name+'="'+n(o.value)+'"';return O[a]?(i(e)&&(c+="/"),c+">"):c+">"+s(e)+"";case Node.TEXT_NODE:var d=e.data;return t&&P[t.localName]?d:r(d);case Node.COMMENT_NODE:return"";default:throw console.error(e),Error("not implemented")}}function s(e){e instanceof C.HTMLTemplateElement&&(e=e.content);for(var t="",n=e.firstChild;n;n=n.nextSibling)t+=a(n,e);return t}function c(e,t,n){var r=n||"div";e.textContent="";var o=S(e.ownerDocument.createElement(r));o.innerHTML=t;for(var i;i=o.firstChild;)e.appendChild(M(i))}function u(e){m.call(this,e)}function l(e,t){var n=S(e.cloneNode(!1));n.innerHTML=t;for(var r,o=S(document.createDocumentFragment());r=n.firstChild;)o.appendChild(r);return M(o)}function d(t){return function(){return e.renderAllPending(),T(this)[t]}}function p(e){v(u,e,d(e))}function h(t){Object.defineProperty(u.prototype,t,{get:d(t),set:function(n){e.renderAllPending(),T(this)[t]=n},configurable:!0,enumerable:!0})}function f(t){Object.defineProperty(u.prototype,t,{value:function(){return e.renderAllPending(),T(this)[t].apply(T(this),arguments)},configurable:!0,enumerable:!0})}var m=e.wrappers.Element,v=e.defineGetter,g=e.enqueueMutation,w=e.mixin,y=e.nodesWereAdded,b=e.nodesWereRemoved,E=e.registerWrapper,_=e.snapshotNodeList,T=e.unsafeUnwrap,S=e.unwrap,M=e.wrap,C=e.wrappers,L=/[&\u00A0"]/g,N=/[&\u00A0<>]/g,O=o(["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"]),P=o(["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"]),D="http://www.w3.org/1999/xhtml",x=/MSIE/.test(navigator.userAgent),I=window.HTMLElement,R=window.HTMLTemplateElement;u.prototype=Object.create(m.prototype),w(u.prototype,{get innerHTML(){return s(this)},set innerHTML(e){if(x&&P[this.localName])return this.textContent=e,void 0;var t=_(this.childNodes);this.invalidateShadowRenderer()?this instanceof C.HTMLTemplateElement?c(this.content,e):c(this,e,this.tagName):!R&&this instanceof C.HTMLTemplateElement?c(this.content,e):T(this).innerHTML=e;var n=_(this.childNodes);g(this,"childList",{addedNodes:n,removedNodes:t}),b(t),y(n,this)},get outerHTML(){return a(this,this.parentNode)},set outerHTML(e){var t=this.parentNode;if(t){t.invalidateShadowRenderer();var n=l(t,e);t.replaceChild(n,this)}},insertAdjacentHTML:function(e,t){var n,r;switch((e+"").toLowerCase()){case"beforebegin":n=this.parentNode,r=this;break;case"afterend":n=this.parentNode,r=this.nextSibling;break;case"afterbegin":n=this,r=this.firstChild;break;case"beforeend":n=this,r=null;break;default:return}var o=l(n,t);n.insertBefore(o,r)},get hidden(){return this.hasAttribute("hidden")},set hidden(e){e?this.setAttribute("hidden",""):this.removeAttribute("hidden")}}),["clientHeight","clientLeft","clientTop","clientWidth","offsetHeight","offsetLeft","offsetTop","offsetWidth","scrollHeight","scrollWidth"].forEach(p),["scrollLeft","scrollTop"].forEach(h),["focus","getBoundingClientRect","getClientRects","scrollIntoView"].forEach(f),E(I,u,document.createElement("b")),e.wrappers.HTMLElement=u,e.getInnerHTML=s,e.setInnerHTML=c}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.unsafeUnwrap,a=e.wrap,s=window.HTMLCanvasElement;t.prototype=Object.create(n.prototype),r(t.prototype,{getContext:function(){var e=i(this).getContext.apply(i(this),arguments);return e&&a(e)}}),o(s,t,document.createElement("canvas")),e.wrappers.HTMLCanvasElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=window.HTMLContentElement;t.prototype=Object.create(n.prototype),r(t.prototype,{constructor:t,get select(){return this.getAttribute("select")},set select(e){this.setAttribute("select",e)},setAttribute:function(e,t){n.prototype.setAttribute.call(this,e,t),"select"===(e+"").toLowerCase()&&this.invalidateShadowRenderer(!0)}}),i&&o(i,t),e.wrappers.HTMLContentElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.wrapHTMLCollection,a=e.unwrap,s=window.HTMLFormElement;t.prototype=Object.create(n.prototype),r(t.prototype,{get elements(){return i(a(this).elements)}}),o(s,t,document.createElement("form")),e.wrappers.HTMLFormElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r.call(this,e)}function n(e,t){if(!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function.");var o=i(document.createElement("img"));r.call(this,o),a(o,this),void 0!==e&&(o.width=e),void 0!==t&&(o.height=t)}var r=e.wrappers.HTMLElement,o=e.registerWrapper,i=e.unwrap,a=e.rewrap,s=window.HTMLImageElement;t.prototype=Object.create(r.prototype),o(s,t,document.createElement("img")),n.prototype=t.prototype,e.wrappers.HTMLImageElement=t,e.wrappers.Image=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement;e.mixin,e.wrappers.NodeList;var r=e.registerWrapper,o=window.HTMLShadowElement;t.prototype=Object.create(n.prototype),t.prototype.constructor=t,o&&r(o,t),e.wrappers.HTMLShadowElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){if(!e.defaultView)return e;var t=d.get(e);if(!t){for(t=e.implementation.createHTMLDocument("");t.lastChild;)t.removeChild(t.lastChild);d.set(e,t)}return t}function n(e){for(var n,r=t(e.ownerDocument),o=c(r.createDocumentFragment());n=e.firstChild;)o.appendChild(n);return o}function r(e){if(o.call(this,e),!p){var t=n(e);l.set(this,u(t))}}var o=e.wrappers.HTMLElement,i=e.mixin,a=e.registerWrapper,s=e.unsafeUnwrap,c=e.unwrap,u=e.wrap,l=new WeakMap,d=new WeakMap,p=window.HTMLTemplateElement;r.prototype=Object.create(o.prototype),i(r.prototype,{constructor:r,get content(){return p?u(s(this).content):l.get(this)}}),p&&a(p,r),e.wrappers.HTMLTemplateElement=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.registerWrapper,o=window.HTMLMediaElement;o&&(t.prototype=Object.create(n.prototype),r(o,t,document.createElement("audio")),e.wrappers.HTMLMediaElement=t)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r.call(this,e)}function n(e){if(!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function.");var t=i(document.createElement("audio"));r.call(this,t),a(t,this),t.setAttribute("preload","auto"),void 0!==e&&t.setAttribute("src",e)}var r=e.wrappers.HTMLMediaElement,o=e.registerWrapper,i=e.unwrap,a=e.rewrap,s=window.HTMLAudioElement;s&&(t.prototype=Object.create(r.prototype),o(s,t,document.createElement("audio")),n.prototype=t.prototype,e.wrappers.HTMLAudioElement=t,e.wrappers.Audio=n)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return e.replace(/\s+/g," ").trim()}function n(e){o.call(this,e)}function r(e,t,n,i){if(!(this instanceof r))throw new TypeError("DOM object constructor cannot be called as a function.");var a=c(document.createElement("option"));o.call(this,a),s(a,this),void 0!==e&&(a.text=e),void 0!==t&&a.setAttribute("value",t),n===!0&&a.setAttribute("selected",""),a.selected=i===!0}var o=e.wrappers.HTMLElement,i=e.mixin,a=e.registerWrapper,s=e.rewrap,c=e.unwrap,u=e.wrap,l=window.HTMLOptionElement;n.prototype=Object.create(o.prototype),i(n.prototype,{get text(){return t(this.textContent)},set text(e){this.textContent=t(e+"")},get form(){return u(c(this).form)}}),a(l,n,document.createElement("option")),r.prototype=n.prototype,e.wrappers.HTMLOptionElement=n,e.wrappers.Option=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.unwrap,a=e.wrap,s=window.HTMLSelectElement;t.prototype=Object.create(n.prototype),r(t.prototype,{add:function(e,t){"object"==typeof t&&(t=i(t)),i(this).add(i(e),t)},remove:function(e){return void 0===e?(n.prototype.remove.call(this),void 0):("object"==typeof e&&(e=i(e)),i(this).remove(e),void 0)},get form(){return a(i(this).form)}}),o(s,t,document.createElement("select")),e.wrappers.HTMLSelectElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.unwrap,a=e.wrap,s=e.wrapHTMLCollection,c=window.HTMLTableElement;t.prototype=Object.create(n.prototype),r(t.prototype,{get caption(){return a(i(this).caption)},createCaption:function(){return a(i(this).createCaption())},get tHead(){return a(i(this).tHead)},createTHead:function(){return a(i(this).createTHead())},createTFoot:function(){return a(i(this).createTFoot())},get tFoot(){return a(i(this).tFoot)},get tBodies(){return s(i(this).tBodies)},createTBody:function(){return a(i(this).createTBody())},get rows(){return s(i(this).rows)},insertRow:function(e){return a(i(this).insertRow(e))}}),o(c,t,document.createElement("table")),e.wrappers.HTMLTableElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.wrapHTMLCollection,a=e.unwrap,s=e.wrap,c=window.HTMLTableSectionElement;t.prototype=Object.create(n.prototype),r(t.prototype,{constructor:t,get rows(){return i(a(this).rows)},insertRow:function(e){return s(a(this).insertRow(e))}}),o(c,t,document.createElement("thead")),e.wrappers.HTMLTableSectionElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.wrapHTMLCollection,a=e.unwrap,s=e.wrap,c=window.HTMLTableRowElement;t.prototype=Object.create(n.prototype),r(t.prototype,{get cells(){return i(a(this).cells)},insertCell:function(e){return s(a(this).insertCell(e))}}),o(c,t,document.createElement("tr")),e.wrappers.HTMLTableRowElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){switch(e.localName){case"content":return new n(e);case"shadow":return new o(e);case"template":return new i(e)}r.call(this,e)}var n=e.wrappers.HTMLContentElement,r=e.wrappers.HTMLElement,o=e.wrappers.HTMLShadowElement,i=e.wrappers.HTMLTemplateElement;e.mixin;var a=e.registerWrapper,s=window.HTMLUnknownElement;t.prototype=Object.create(r.prototype),a(s,t),e.wrappers.HTMLUnknownElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.Element,r=e.wrappers.HTMLElement,o=e.registerWrapper;e.defineWrapGetter;var i=e.unsafeUnwrap,a=e.wrap,s=e.mixin,c="http://www.w3.org/2000/svg",u=window.SVGElement,l=document.createElementNS(c,"title");if(!("classList"in l)){var d=Object.getOwnPropertyDescriptor(n.prototype,"classList");Object.defineProperty(r.prototype,"classList",d),delete n.prototype.classList}t.prototype=Object.create(n.prototype),s(t.prototype,{get ownerSVGElement(){return a(i(this).ownerSVGElement)}}),o(u,t,document.createElementNS(c,"title")),e.wrappers.SVGElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){p.call(this,e)}var n=e.mixin,r=e.registerWrapper,o=e.unwrap,i=e.wrap,a=window.SVGUseElement,s="http://www.w3.org/2000/svg",c=i(document.createElementNS(s,"g")),u=document.createElementNS(s,"use"),l=c.constructor,d=Object.getPrototypeOf(l.prototype),p=d.constructor;t.prototype=Object.create(d),"instanceRoot"in u&&n(t.prototype,{get instanceRoot(){return i(o(this).instanceRoot)},get animatedInstanceRoot(){return i(o(this).animatedInstanceRoot)}}),r(a,t,u),e.wrappers.SVGUseElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.EventTarget,r=e.mixin,o=e.registerWrapper,i=e.unsafeUnwrap,a=e.wrap,s=window.SVGElementInstance;s&&(t.prototype=Object.create(n.prototype),r(t.prototype,{get correspondingElement(){return a(i(this).correspondingElement)},get correspondingUseElement(){return a(i(this).correspondingUseElement)},get parentNode(){return a(i(this).parentNode)},get childNodes(){throw Error("Not implemented")},get firstChild(){return a(i(this).firstChild)},get lastChild(){return a(i(this).lastChild)},get previousSibling(){return a(i(this).previousSibling)},get nextSibling(){return a(i(this).nextSibling)}}),o(s,t),e.wrappers.SVGElementInstance=t)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){o(e,this)}var n=e.mixin,r=e.registerWrapper,o=e.setWrapper,i=e.unsafeUnwrap,a=e.unwrap,s=e.unwrapIfNeeded,c=e.wrap,u=window.CanvasRenderingContext2D;n(t.prototype,{get canvas(){return c(i(this).canvas)},drawImage:function(){arguments[0]=s(arguments[0]),i(this).drawImage.apply(i(this),arguments)},createPattern:function(){return arguments[0]=a(arguments[0]),i(this).createPattern.apply(i(this),arguments)}}),r(u,t,document.createElement("canvas").getContext("2d")),e.wrappers.CanvasRenderingContext2D=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){i(e,this)}var n=e.addForwardingProperties,r=e.mixin,o=e.registerWrapper,i=e.setWrapper,a=e.unsafeUnwrap,s=e.unwrapIfNeeded,c=e.wrap,u=window.WebGLRenderingContext;if(u){r(t.prototype,{get canvas(){return c(a(this).canvas)},texImage2D:function(){arguments[5]=s(arguments[5]),a(this).texImage2D.apply(a(this),arguments)},texSubImage2D:function(){arguments[6]=s(arguments[6]),a(this).texSubImage2D.apply(a(this),arguments)}});var l=Object.getPrototypeOf(u.prototype);l!==Object.prototype&&n(l,t.prototype);var d=/WebKit/.test(navigator.userAgent)?{drawingBufferHeight:null,drawingBufferWidth:null}:{};o(u,t,d),e.wrappers.WebGLRenderingContext=t}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.Node,r=e.GetElementsByInterface,o=e.NonElementParentNodeInterface,i=e.ParentNodeInterface,a=e.SelectorsInterface,s=e.mixin,c=e.registerObject,u=e.registerWrapper,l=window.DocumentFragment;t.prototype=Object.create(n.prototype),s(t.prototype,i),s(t.prototype,a),s(t.prototype,r),s(t.prototype,o),u(l,t,document.createDocumentFragment()),e.wrappers.DocumentFragment=t;var d=c(document.createComment(""));e.wrappers.Comment=d}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t=d(l(e).ownerDocument.createDocumentFragment());n.call(this,t),c(t,this);var o=e.shadowRoot;f.set(this,o),this.treeScope_=new r(this,a(o||e)),h.set(this,e)}var n=e.wrappers.DocumentFragment,r=e.TreeScope,o=e.elementFromPoint,i=e.getInnerHTML,a=e.getTreeScope,s=e.mixin,c=e.rewrap,u=e.setInnerHTML,l=e.unsafeUnwrap,d=e.unwrap,p=e.wrap,h=new WeakMap,f=new WeakMap;t.prototype=Object.create(n.prototype),s(t.prototype,{constructor:t,get innerHTML(){return i(this)},set innerHTML(e){u(this,e),this.invalidateShadowRenderer()},get olderShadowRoot(){return f.get(this)||null},get host(){return h.get(this)||null},invalidateShadowRenderer:function(){return h.get(this).invalidateShadowRenderer()},elementFromPoint:function(e,t){return o(this,this.ownerDocument,e,t)},getSelection:function(){return document.getSelection()},get activeElement(){var e=d(this).ownerDocument.activeElement;if(!e||!e.nodeType)return null;var t=p(e);if(t===this.host)return null;for(;!this.contains(t)&&!this.host.contains(t);){for(;t.parentNode;)t=t.parentNode;if(!t.host)return null;t=t.host}return t}}),e.wrappers.ShadowRoot=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t=d(e).root;return t instanceof h?t.host:null}function n(t,n){if(t.shadowRoot){n=Math.min(t.childNodes.length-1,n);var r=t.childNodes[n];if(r){var o=e.getDestinationInsertionPoints(r);if(o.length>0){var i=o[0].parentNode;i.nodeType==Node.ELEMENT_NODE&&(t=i)}}}return t}function r(e){return e=l(e),t(e)||e}function o(e){a(e,this)}var i=e.registerWrapper,a=e.setWrapper,s=e.unsafeUnwrap,c=e.unwrap,u=e.unwrapIfNeeded,l=e.wrap,d=e.getTreeScope,p=window.Range,h=e.wrappers.ShadowRoot;o.prototype={get startContainer(){return r(s(this).startContainer)},get endContainer(){return r(s(this).endContainer)},get commonAncestorContainer(){return r(s(this).commonAncestorContainer)},setStart:function(e,t){e=n(e,t),s(this).setStart(u(e),t)},setEnd:function(e,t){e=n(e,t),s(this).setEnd(u(e),t)},setStartBefore:function(e){s(this).setStartBefore(u(e))},setStartAfter:function(e){s(this).setStartAfter(u(e))},setEndBefore:function(e){s(this).setEndBefore(u(e))},setEndAfter:function(e){s(this).setEndAfter(u(e))},selectNode:function(e){s(this).selectNode(u(e))},selectNodeContents:function(e){s(this).selectNodeContents(u(e))},compareBoundaryPoints:function(e,t){return s(this).compareBoundaryPoints(e,c(t))},extractContents:function(){return l(s(this).extractContents())},cloneContents:function(){return l(s(this).cloneContents())},insertNode:function(e){s(this).insertNode(u(e))},surroundContents:function(e){s(this).surroundContents(u(e))},cloneRange:function(){return l(s(this).cloneRange())},isPointInRange:function(e,t){return s(this).isPointInRange(u(e),t)},comparePoint:function(e,t){return s(this).comparePoint(u(e),t)},intersectsNode:function(e){return s(this).intersectsNode(u(e))},toString:function(){return""+s(this)}},p.prototype.createContextualFragment&&(o.prototype.createContextualFragment=function(e){return l(s(this).createContextualFragment(e))}),i(window.Range,o,document.createRange()),e.wrappers.Range=o}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){e.previousSibling_=e.previousSibling,e.nextSibling_=e.nextSibling,e.parentNode_=e.parentNode}function n(n,o,i){var a=I(n),s=I(o),c=i?I(i):null;if(r(o),t(o),i)n.firstChild===i&&(n.firstChild_=i),i.previousSibling_=i.previousSibling;else{n.lastChild_=n.lastChild,n.lastChild===n.firstChild&&(n.firstChild_=n.firstChild);var u=R(a.lastChild);u&&(u.nextSibling_=u.nextSibling)}e.originalInsertBefore.call(a,s,c)}function r(n){var r=I(n),o=r.parentNode;if(o){var i=R(o);t(n),n.previousSibling&&(n.previousSibling.nextSibling_=n),n.nextSibling&&(n.nextSibling.previousSibling_=n),i.lastChild===n&&(i.lastChild_=n),i.firstChild===n&&(i.firstChild_=n),e.originalRemoveChild.call(o,r)}}function o(e){k.set(e,[])}function i(e){var t=k.get(e);return t||k.set(e,t=[]),t}function a(e){for(var t=[],n=0,r=e.firstChild;r;r=r.nextSibling)t[n++]=r;return t}function s(){for(var e=0;q.length>e;e++){var t=q[e],n=t.parentRenderer;n&&n.dirty||t.render()}q=[]}function c(){P=null,s()}function u(e){var t=j.get(e);return t||(t=new h(e),j.set(e,t)),t}function l(e){var t=O(e).root;return t instanceof N?t:null}function d(e){return u(e.host)}function p(e){this.skip=!1,this.node=e,this.childNodes=[]}function h(e){this.host=e,this.dirty=!1,this.invalidateAttributes(),this.associateNode(e)}function f(e){for(var t=[],n=e.firstChild;n;n=n.nextSibling)E(n)?t.push.apply(t,i(n)):t.push(n);return t}function m(e){if(e instanceof C)return e;if(e instanceof M)return null;for(var t=e.firstChild;t;t=t.nextSibling){var n=m(t);if(n)return n}return null}function v(e,t){i(t).push(e);var n=H.get(e);n?n.push(t):H.set(e,[t])}function g(e){return H.get(e)}function w(e){H.set(e,void 0)}function y(e,t){var n=t.getAttribute("select");if(!n)return!0;if(n=n.trim(),!n)return!0;if(!(e instanceof S))return!1;if(!U.test(n))return!1;try{return e.matches(n)}catch(r){return!1}}function b(e,t){var n=g(t);return n&&n[n.length-1]===e}function E(e){return e instanceof M||e instanceof C}function _(e){return e.shadowRoot}function T(e){for(var t=[],n=e.shadowRoot;n;n=n.olderShadowRoot)t.push(n);return t}var S=e.wrappers.Element,M=e.wrappers.HTMLContentElement,C=e.wrappers.HTMLShadowElement,L=e.wrappers.Node,N=e.wrappers.ShadowRoot;e.assert;var O=e.getTreeScope;e.mixin;var P,D=e.oneOf,x=e.unsafeUnwrap,I=e.unwrap,R=e.wrap,A=e.ArraySplice,k=new WeakMap,H=new WeakMap,j=new WeakMap,F=D(window,["requestAnimationFrame","mozRequestAnimationFrame","webkitRequestAnimationFrame","setTimeout"]),q=[],W=new A;W.equals=function(e,t){return I(e.node)===t},p.prototype={append:function(e){var t=new p(e);return this.childNodes.push(t),t},sync:function(e){if(!this.skip){for(var t=this.node,o=this.childNodes,i=a(I(t)),s=e||new WeakMap,c=W.calculateSplices(o,i),u=0,l=0,d=0,p=0;c.length>p;p++){for(var h=c[p];h.index>d;d++)l++,o[u++].sync(s);for(var f=h.removed.length,m=0;f>m;m++){var v=R(i[l++]);s.get(v)||r(v)}for(var g=h.addedCount,w=i[l]&&R(i[l]),m=0;g>m;m++){var y=o[u++],b=y.node;n(t,b,w),s.set(b,!0),y.sync(s)}d+=g}for(var p=d;o.length>p;p++)o[p].sync(s)}}},h.prototype={render:function(e){if(this.dirty){this.invalidateAttributes();var t=this.host;this.distribution(t);var n=e||new p(t);this.buildRenderTree(n,t);var r=!e;r&&n.sync(),this.dirty=!1}},get parentRenderer(){return O(this.host).renderer},invalidate:function(){if(!this.dirty){this.dirty=!0;var e=this.parentRenderer;if(e&&e.invalidate(),q.push(this),P)return;P=window[F](c,0)}},distribution:function(e){this.resetAllSubtrees(e),this.distributionResolution(e)},resetAll:function(e){E(e)?o(e):w(e),this.resetAllSubtrees(e)},resetAllSubtrees:function(e){for(var t=e.firstChild;t;t=t.nextSibling)this.resetAll(t);e.shadowRoot&&this.resetAll(e.shadowRoot),e.olderShadowRoot&&this.resetAll(e.olderShadowRoot)},distributionResolution:function(e){if(_(e)){for(var t=e,n=f(t),r=T(t),o=0;r.length>o;o++)this.poolDistribution(r[o],n);for(var o=r.length-1;o>=0;o--){var i=r[o],a=m(i);if(a){var s=i.olderShadowRoot;s&&(n=f(s));for(var c=0;n.length>c;c++)v(n[c],a)}this.distributionResolution(i)}}for(var u=e.firstChild;u;u=u.nextSibling)this.distributionResolution(u)},poolDistribution:function(e,t){if(!(e instanceof C))if(e instanceof M){var n=e;this.updateDependentAttributes(n.getAttribute("select"));for(var r=!1,o=0;t.length>o;o++){var e=t[o];e&&y(e,n)&&(v(e,n),t[o]=void 0,r=!0)}if(!r)for(var i=n.firstChild;i;i=i.nextSibling)v(i,n)}else for(var i=e.firstChild;i;i=i.nextSibling)this.poolDistribution(i,t)},buildRenderTree:function(e,t){for(var n=this.compose(t),r=0;n.length>r;r++){var o=n[r],i=e.append(o);this.buildRenderTree(i,o)}if(_(t)){var a=u(t);a.dirty=!1}},compose:function(e){for(var t=[],n=e.shadowRoot||e,r=n.firstChild;r;r=r.nextSibling)if(E(r)){this.associateNode(n);for(var o=i(r),a=0;o.length>a;a++){var s=o[a];b(r,s)&&t.push(s)}}else t.push(r);return t},invalidateAttributes:function(){this.attributes=Object.create(null)},updateDependentAttributes:function(e){if(e){var t=this.attributes;/\.\w+/.test(e)&&(t["class"]=!0),/#\w+/.test(e)&&(t.id=!0),e.replace(/\[\s*([^\s=\|~\]]+)/g,function(e,n){t[n]=!0})}},dependsOnAttribute:function(e){return this.attributes[e]},associateNode:function(e){x(e).polymerShadowRenderer_=this}};var U=/^(:not\()?[*.#[a-zA-Z_|]/;L.prototype.invalidateShadowRenderer=function(){var e=x(this).polymerShadowRenderer_;return e?(e.invalidate(),!0):!1},M.prototype.getDistributedNodes=C.prototype.getDistributedNodes=function(){return s(),i(this)},S.prototype.getDestinationInsertionPoints=function(){return s(),g(this)||[]},M.prototype.nodeIsInserted_=C.prototype.nodeIsInserted_=function(){this.invalidateShadowRenderer();var e,t=l(this);t&&(e=d(t)),x(this).polymerShadowRenderer_=e,e&&e.invalidate()},e.getRendererForHost=u,e.getShadowTrees=T,e.renderAllPending=s,e.getDestinationInsertionPoints=g,e.visual={insertBefore:n,remove:r}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(t){if(window[t]){r(!e.wrappers[t]);var c=function(e){n.call(this,e)};c.prototype=Object.create(n.prototype),o(c.prototype,{get form(){return s(a(this).form)}}),i(window[t],c,document.createElement(t.slice(4,-7))),e.wrappers[t]=c}}var n=e.wrappers.HTMLElement,r=e.assert,o=e.mixin,i=e.registerWrapper,a=e.unwrap,s=e.wrap,c=["HTMLButtonElement","HTMLFieldSetElement","HTMLInputElement","HTMLKeygenElement","HTMLLabelElement","HTMLLegendElement","HTMLObjectElement","HTMLOutputElement","HTMLTextAreaElement"];c.forEach(t)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r(e,this)}var n=e.registerWrapper,r=e.setWrapper,o=e.unsafeUnwrap,i=e.unwrap,a=e.unwrapIfNeeded,s=e.wrap,c=window.Selection;t.prototype={get anchorNode(){return s(o(this).anchorNode)},get focusNode(){return s(o(this).focusNode)},addRange:function(e){o(this).addRange(a(e))},collapse:function(e,t){o(this).collapse(a(e),t)},containsNode:function(e,t){return o(this).containsNode(a(e),t)},getRangeAt:function(e){return s(o(this).getRangeAt(e))},removeRange:function(e){o(this).removeRange(i(e))},selectAllChildren:function(e){o(this).selectAllChildren(e instanceof ShadowRoot?o(e.host):a(e))},toString:function(){return""+o(this)}},c.prototype.extend&&(t.prototype.extend=function(e,t){o(this).extend(a(e),t)}),n(window.Selection,t,window.getSelection()),e.wrappers.Selection=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r(e,this)}var n=e.registerWrapper,r=e.setWrapper,o=e.unsafeUnwrap,i=e.unwrapIfNeeded,a=e.wrap,s=window.TreeWalker; -t.prototype={get root(){return a(o(this).root)},get currentNode(){return a(o(this).currentNode)},set currentNode(e){o(this).currentNode=i(e)},get filter(){return o(this).filter},parentNode:function(){return a(o(this).parentNode())},firstChild:function(){return a(o(this).firstChild())},lastChild:function(){return a(o(this).lastChild())},previousSibling:function(){return a(o(this).previousSibling())},previousNode:function(){return a(o(this).previousNode())},nextNode:function(){return a(o(this).nextNode())}},n(s,t),e.wrappers.TreeWalker=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){l.call(this,e),this.treeScope_=new v(this,null)}function n(e){var n=document[e];t.prototype[e]=function(){return P(n.apply(N(this),arguments))}}function r(e,t){I.call(N(t),O(e)),o(e,t)}function o(e,t){e.shadowRoot&&t.adoptNode(e.shadowRoot),e instanceof m&&i(e,t);for(var n=e.firstChild;n;n=n.nextSibling)o(n,t)}function i(e,t){var n=e.olderShadowRoot;n&&t.adoptNode(n)}function a(e){L(e,this)}function s(e,t){var n=document.implementation[t];e.prototype[t]=function(){return P(n.apply(N(this),arguments))}}function c(e,t){var n=document.implementation[t];e.prototype[t]=function(){return n.apply(N(this),arguments)}}var u=e.GetElementsByInterface,l=e.wrappers.Node,d=e.ParentNodeInterface,p=e.NonElementParentNodeInterface,h=e.wrappers.Selection,f=e.SelectorsInterface,m=e.wrappers.ShadowRoot,v=e.TreeScope,g=e.cloneNode,w=e.defineGetter,y=e.defineWrapGetter,b=e.elementFromPoint,E=e.forwardMethodsToWrapper,_=e.matchesNames,T=e.mixin,S=e.registerWrapper,M=e.renderAllPending,C=e.rewrap,L=e.setWrapper,N=e.unsafeUnwrap,O=e.unwrap,P=e.wrap,D=e.wrapEventTargetMethods;e.wrapNodeList;var x=new WeakMap;t.prototype=Object.create(l.prototype),y(t,"documentElement"),y(t,"body"),y(t,"head"),w(t,"activeElement",function(){var e=O(this).activeElement;if(!e||!e.nodeType)return null;for(var t=P(e);!this.contains(t);){for(;t.parentNode;)t=t.parentNode;if(!t.host)return null;t=t.host}return t}),["createComment","createDocumentFragment","createElement","createElementNS","createEvent","createEventNS","createRange","createTextNode"].forEach(n);var I=document.adoptNode,R=document.getSelection;T(t.prototype,{adoptNode:function(e){return e.parentNode&&e.parentNode.removeChild(e),r(e,this),e},elementFromPoint:function(e,t){return b(this,this,e,t)},importNode:function(e,t){return g(e,t,N(this))},getSelection:function(){return M(),new h(R.call(O(this)))},getElementsByName:function(e){return f.querySelectorAll.call(this,"[name="+JSON.stringify(e+"")+"]")}});var A=document.createTreeWalker,k=e.wrappers.TreeWalker;if(t.prototype.createTreeWalker=function(e,t,n,r){var o=null;return n&&(n.acceptNode&&"function"==typeof n.acceptNode?o={acceptNode:function(e){return n.acceptNode(P(e))}}:"function"==typeof n&&(o=function(e){return n(P(e))})),new k(A.call(O(this),O(e),t,o,r))},document.registerElement){var H=document.registerElement;t.prototype.registerElement=function(t,n){function r(e){return e?(L(e,this),void 0):i?document.createElement(i,t):document.createElement(t)}var o,i;if(void 0!==n&&(o=n.prototype,i=n.extends),o||(o=Object.create(HTMLElement.prototype)),e.nativePrototypeTable.get(o))throw Error("NotSupportedError");for(var a,s=Object.getPrototypeOf(o),c=[];s&&!(a=e.nativePrototypeTable.get(s));)c.push(s),s=Object.getPrototypeOf(s);if(!a)throw Error("NotSupportedError");for(var u=Object.create(a),l=c.length-1;l>=0;l--)u=Object.create(u);["createdCallback","attachedCallback","detachedCallback","attributeChangedCallback"].forEach(function(e){var t=o[e];t&&(u[e]=function(){P(this)instanceof r||C(this),t.apply(P(this),arguments)})});var d={prototype:u};return i&&(d.extends=i),r.prototype=o,r.prototype.constructor=r,e.constructorTable.set(u,r),e.nativePrototypeTable.set(o,u),H.call(O(this),t,d),r},E([window.HTMLDocument||window.Document],["registerElement"])}E([window.HTMLBodyElement,window.HTMLDocument||window.Document,window.HTMLHeadElement,window.HTMLHtmlElement],["appendChild","compareDocumentPosition","contains","getElementsByClassName","getElementsByTagName","getElementsByTagNameNS","insertBefore","querySelector","querySelectorAll","removeChild","replaceChild"]),E([window.HTMLBodyElement,window.HTMLHeadElement,window.HTMLHtmlElement],_),E([window.HTMLDocument||window.Document],["adoptNode","importNode","contains","createComment","createDocumentFragment","createElement","createElementNS","createEvent","createEventNS","createRange","createTextNode","createTreeWalker","elementFromPoint","getElementById","getElementsByName","getSelection"]),T(t.prototype,u),T(t.prototype,d),T(t.prototype,f),T(t.prototype,p),T(t.prototype,{get implementation(){var e=x.get(this);return e?e:(e=new a(O(this).implementation),x.set(this,e),e)},get defaultView(){return P(O(this).defaultView)}}),S(window.Document,t,document.implementation.createHTMLDocument("")),window.HTMLDocument&&S(window.HTMLDocument,t),D([window.HTMLBodyElement,window.HTMLDocument||window.Document,window.HTMLHeadElement]);var j=document.implementation.createDocument;a.prototype.createDocument=function(){return arguments[2]=O(arguments[2]),P(j.apply(N(this),arguments))},s(a,"createDocumentType"),s(a,"createHTMLDocument"),c(a,"hasFeature"),S(window.DOMImplementation,a),E([window.DOMImplementation],["createDocument","createDocumentType","createHTMLDocument","hasFeature"]),e.adoptNodeNoRemove=r,e.wrappers.DOMImplementation=a,e.wrappers.Document=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.EventTarget,r=e.wrappers.Selection,o=e.mixin,i=e.registerWrapper,a=e.renderAllPending,s=e.unwrap,c=e.unwrapIfNeeded,u=e.wrap,l=window.Window,d=window.getComputedStyle,p=window.getDefaultComputedStyle,h=window.getSelection;t.prototype=Object.create(n.prototype),l.prototype.getComputedStyle=function(e,t){return u(this||window).getComputedStyle(c(e),t)},p&&(l.prototype.getDefaultComputedStyle=function(e,t){return u(this||window).getDefaultComputedStyle(c(e),t)}),l.prototype.getSelection=function(){return u(this||window).getSelection()},delete window.getComputedStyle,delete window.getDefaultComputedStyle,delete window.getSelection,["addEventListener","removeEventListener","dispatchEvent"].forEach(function(e){l.prototype[e]=function(){var t=u(this||window);return t[e].apply(t,arguments)},delete window[e]}),o(t.prototype,{getComputedStyle:function(e,t){return a(),d.call(s(this),c(e),t)},getSelection:function(){return a(),new r(h.call(s(this)))},get document(){return u(s(this).document)}}),p&&(t.prototype.getDefaultComputedStyle=function(e,t){return a(),p.call(s(this),c(e),t)}),i(l,t,window),e.wrappers.Window=t}(window.ShadowDOMPolyfill),function(e){"use strict";var t=e.unwrap,n=window.DataTransfer||window.Clipboard,r=n.prototype.setDragImage;r&&(n.prototype.setDragImage=function(e,n,o){r.call(this,t(e),n,o)})}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t;t=e instanceof i?e:new i(e&&o(e)),r(t,this)}var n=e.registerWrapper,r=e.setWrapper,o=e.unwrap,i=window.FormData;i&&(n(i,t,new i),e.wrappers.FormData=t)}(window.ShadowDOMPolyfill),function(e){"use strict";var t=e.unwrapIfNeeded,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.send=function(e){return n.call(this,t(e))}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t=n[e],r=window[t];if(r){var o=document.createElement(e),i=o.constructor;window[t]=i}}e.isWrapperFor;var n={a:"HTMLAnchorElement",area:"HTMLAreaElement",audio:"HTMLAudioElement",base:"HTMLBaseElement",body:"HTMLBodyElement",br:"HTMLBRElement",button:"HTMLButtonElement",canvas:"HTMLCanvasElement",caption:"HTMLTableCaptionElement",col:"HTMLTableColElement",content:"HTMLContentElement",data:"HTMLDataElement",datalist:"HTMLDataListElement",del:"HTMLModElement",dir:"HTMLDirectoryElement",div:"HTMLDivElement",dl:"HTMLDListElement",embed:"HTMLEmbedElement",fieldset:"HTMLFieldSetElement",font:"HTMLFontElement",form:"HTMLFormElement",frame:"HTMLFrameElement",frameset:"HTMLFrameSetElement",h1:"HTMLHeadingElement",head:"HTMLHeadElement",hr:"HTMLHRElement",html:"HTMLHtmlElement",iframe:"HTMLIFrameElement",img:"HTMLImageElement",input:"HTMLInputElement",keygen:"HTMLKeygenElement",label:"HTMLLabelElement",legend:"HTMLLegendElement",li:"HTMLLIElement",link:"HTMLLinkElement",map:"HTMLMapElement",marquee:"HTMLMarqueeElement",menu:"HTMLMenuElement",menuitem:"HTMLMenuItemElement",meta:"HTMLMetaElement",meter:"HTMLMeterElement",object:"HTMLObjectElement",ol:"HTMLOListElement",optgroup:"HTMLOptGroupElement",option:"HTMLOptionElement",output:"HTMLOutputElement",p:"HTMLParagraphElement",param:"HTMLParamElement",pre:"HTMLPreElement",progress:"HTMLProgressElement",q:"HTMLQuoteElement",script:"HTMLScriptElement",select:"HTMLSelectElement",shadow:"HTMLShadowElement",source:"HTMLSourceElement",span:"HTMLSpanElement",style:"HTMLStyleElement",table:"HTMLTableElement",tbody:"HTMLTableSectionElement",template:"HTMLTemplateElement",textarea:"HTMLTextAreaElement",thead:"HTMLTableSectionElement",time:"HTMLTimeElement",title:"HTMLTitleElement",tr:"HTMLTableRowElement",track:"HTMLTrackElement",ul:"HTMLUListElement",video:"HTMLVideoElement"};Object.keys(n).forEach(t),Object.getOwnPropertyNames(e.wrappers).forEach(function(t){window[t]=e.wrappers[t]})}(window.ShadowDOMPolyfill),function(e){function t(e,t){var n="";return Array.prototype.forEach.call(e,function(e){n+=e.textContent+"\n\n"}),t||(n=n.replace(d,"")),n}function n(e){var t=document.createElement("style");return t.textContent=e,t}function r(e){var t=n(e);document.head.appendChild(t);var r=[];if(t.sheet)try{r=t.sheet.cssRules}catch(o){}else console.warn("sheet not found",t);return t.parentNode.removeChild(t),r}function o(){O.initialized=!0,document.body.appendChild(O);var e=O.contentDocument,t=e.createElement("base");t.href=document.baseURI,e.head.appendChild(t)}function i(e){O.initialized||o(),document.body.appendChild(O),e(O.contentDocument),document.body.removeChild(O)}function a(e,t){if(t){var o;if(e.match("@import")&&D){var a=n(e);i(function(e){e.head.appendChild(a.impl),o=Array.prototype.slice.call(a.sheet.cssRules,0),t(o)})}else o=r(e),t(o)}}function s(e){e&&u().appendChild(document.createTextNode(e))}function c(e,t){var r=n(e);r.setAttribute(t,""),r.setAttribute(I,""),document.head.appendChild(r)}function u(){return P||(P=document.createElement("style"),P.setAttribute(I,""),P[I]=!0),P}var l={strictStyling:!1,registry:{},shimStyling:function(e,n,r){var o=this.prepareRoot(e,n,r),i=this.isTypeExtension(r),a=this.makeScopeSelector(n,i),s=t(o,!0);s=this.scopeCssText(s,a),e&&(e.shimmedStyle=s),this.addCssToDocument(s,n)},shimStyle:function(e,t){return this.shimCssText(e.textContent,t)},shimCssText:function(e,t){return e=this.insertDirectives(e),this.scopeCssText(e,t)},makeScopeSelector:function(e,t){return e?t?"[is="+e+"]":e:""},isTypeExtension:function(e){return e&&0>e.indexOf("-")},prepareRoot:function(e,t,n){var r=this.registerRoot(e,t,n);return this.replaceTextInStyles(r.rootStyles,this.insertDirectives),this.removeStyles(e,r.rootStyles),this.strictStyling&&this.applyScopeToContent(e,t),r.scopeStyles},removeStyles:function(e,t){for(var n,r=0,o=t.length;o>r&&(n=t[r]);r++)n.parentNode.removeChild(n)},registerRoot:function(e,t,n){var r=this.registry[t]={root:e,name:t,extendsName:n},o=this.findStyles(e);r.rootStyles=o,r.scopeStyles=r.rootStyles;var i=this.registry[r.extendsName];return i&&(r.scopeStyles=i.scopeStyles.concat(r.scopeStyles)),r},findStyles:function(e){if(!e)return[];var t=e.querySelectorAll("style");return Array.prototype.filter.call(t,function(e){return!e.hasAttribute(R)})},applyScopeToContent:function(e,t){e&&(Array.prototype.forEach.call(e.querySelectorAll("*"),function(e){e.setAttribute(t,"")}),Array.prototype.forEach.call(e.querySelectorAll("template"),function(e){this.applyScopeToContent(e.content,t)},this))},insertDirectives:function(e){return e=this.insertPolyfillDirectivesInCssText(e),this.insertPolyfillRulesInCssText(e)},insertPolyfillDirectivesInCssText:function(e){return e=e.replace(p,function(e,t){return t.slice(0,-2)+"{"}),e.replace(h,function(e,t){return t+" {"})},insertPolyfillRulesInCssText:function(e){return e=e.replace(f,function(e,t){return t.slice(0,-1)}),e.replace(m,function(e,t,n,r){var o=e.replace(t,"").replace(n,"");return r+o})},scopeCssText:function(e,t){var n=this.extractUnscopedRulesFromCssText(e);if(e=this.insertPolyfillHostInCssText(e),e=this.convertColonHost(e),e=this.convertColonHostContext(e),e=this.convertShadowDOMSelectors(e),t){var e,r=this;a(e,function(n){e=r.scopeRules(n,t)})}return e=e+"\n"+n,e.trim()},extractUnscopedRulesFromCssText:function(e){for(var t,n="";t=v.exec(e);)n+=t[1].slice(0,-1)+"\n\n";for(;t=g.exec(e);)n+=t[0].replace(t[2],"").replace(t[1],t[3])+"\n\n";return n},convertColonHost:function(e){return this.convertColonRule(e,E,this.colonHostPartReplacer)},convertColonHostContext:function(e){return this.convertColonRule(e,_,this.colonHostContextPartReplacer)},convertColonRule:function(e,t,n){return e.replace(t,function(e,t,r,o){if(t=C,r){for(var i,a=r.split(","),s=[],c=0,u=a.length;u>c&&(i=a[c]);c++)i=i.trim(),s.push(n(t,i,o));return s.join(",")}return t+o})},colonHostContextPartReplacer:function(e,t,n){return t.match(w)?this.colonHostPartReplacer(e,t,n):e+t+n+", "+t+" "+e+n},colonHostPartReplacer:function(e,t,n){return e+t.replace(w,"")+n},convertShadowDOMSelectors:function(e){for(var t=0;N.length>t;t++)e=e.replace(N[t]," ");return e},scopeRules:function(e,t){var n="";return e&&Array.prototype.forEach.call(e,function(e){if(e.selectorText&&e.style&&void 0!==e.style.cssText)n+=this.scopeSelector(e.selectorText,t,this.strictStyling)+" {\n ",n+=this.propertiesFromRule(e)+"\n}\n\n";else if(e.type===CSSRule.MEDIA_RULE)n+="@media "+e.media.mediaText+" {\n",n+=this.scopeRules(e.cssRules,t),n+="\n}\n\n";else try{e.cssText&&(n+=e.cssText+"\n\n")}catch(r){e.type===CSSRule.KEYFRAMES_RULE&&e.cssRules&&(n+=this.ieSafeCssTextFromKeyFrameRule(e))}},this),n},ieSafeCssTextFromKeyFrameRule:function(e){var t="@keyframes "+e.name+" {";return Array.prototype.forEach.call(e.cssRules,function(e){t+=" "+e.keyText+" {"+e.style.cssText+"}"}),t+=" }"},scopeSelector:function(e,t,n){var r=[],o=e.split(",");return o.forEach(function(e){e=e.trim(),this.selectorNeedsScoping(e,t)&&(e=n&&!e.match(C)?this.applyStrictSelectorScope(e,t):this.applySelectorScope(e,t)),r.push(e)},this),r.join(", ")},selectorNeedsScoping:function(e,t){if(Array.isArray(t))return!0;var n=this.makeScopeMatcher(t);return!e.match(n)},makeScopeMatcher:function(e){return e=e.replace(/\[/g,"\\[").replace(/\]/g,"\\]"),RegExp("^("+e+")"+T,"m")},applySelectorScope:function(e,t){return Array.isArray(t)?this.applySelectorScopeList(e,t):this.applySimpleSelectorScope(e,t)},applySelectorScopeList:function(e,t){for(var n,r=[],o=0;n=t[o];o++)r.push(this.applySimpleSelectorScope(e,n));return r.join(", ")},applySimpleSelectorScope:function(e,t){return e.match(L)?(e=e.replace(C,t),e.replace(L,t+" ")):t+" "+e},applyStrictSelectorScope:function(e,t){t=t.replace(/\[is=([^\]]*)\]/g,"$1");var n=[" ",">","+","~"],r=e,o="["+t+"]";return n.forEach(function(e){var t=r.split(e);r=t.map(function(e){var t=e.trim().replace(L,"");return t&&0>n.indexOf(t)&&0>t.indexOf(o)&&(e=t.replace(/([^:]*)(:*)(.*)/,"$1"+o+"$2$3")),e}).join(e)}),r},insertPolyfillHostInCssText:function(e){return e.replace(M,y).replace(S,w)},propertiesFromRule:function(e){var t=e.style.cssText;e.style.content&&!e.style.content.match(/['"]+|attr/)&&(t=t.replace(/content:[^;]*;/g,"content: '"+e.style.content+"';"));var n=e.style;for(var r in n)"initial"===n[r]&&(t+=r+": initial; ");return t},replaceTextInStyles:function(e,t){e&&t&&(e instanceof Array||(e=[e]),Array.prototype.forEach.call(e,function(e){e.textContent=t.call(this,e.textContent)},this))},addCssToDocument:function(e,t){e.match("@import")?c(e,t):s(e)}},d=/\/\*[^*]*\*+([^\/*][^*]*\*+)*\//gim,p=/\/\*\s*@polyfill ([^*]*\*+([^\/*][^*]*\*+)*\/)([^{]*?){/gim,h=/polyfill-next-selector[^}]*content\:[\s]*?['"](.*?)['"][;\s]*}([^{]*?){/gim,f=/\/\*\s@polyfill-rule([^*]*\*+([^\/*][^*]*\*+)*)\//gim,m=/(polyfill-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim,v=/\/\*\s@polyfill-unscoped-rule([^*]*\*+([^\/*][^*]*\*+)*)\//gim,g=/(polyfill-unscoped-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim,w="-shadowcsshost",y="-shadowcsscontext",b=")(?:\\(((?:\\([^)(]*\\)|[^)(]*)+?)\\))?([^,{]*)",E=RegExp("("+w+b,"gim"),_=RegExp("("+y+b,"gim"),T="([>\\s~+[.,{:][\\s\\S]*)?$",S=/\:host/gim,M=/\:host-context/gim,C=w+"-no-combinator",L=RegExp(w,"gim"),N=(RegExp(y,"gim"),[/>>>/g,/::shadow/g,/::content/g,/\/deep\//g,/\/shadow\//g,/\/shadow-deep\//g,/\^\^/g,/\^/g]),O=document.createElement("iframe");O.style.display="none";var P,D=navigator.userAgent.match("Chrome"),x="shim-shadowdom",I="shim-shadowdom-css",R="no-shim";if(window.ShadowDOMPolyfill){s("style { display: none !important; }\n");var A=ShadowDOMPolyfill.wrap(document),k=A.querySelector("head");k.insertBefore(u(),k.childNodes[0]),document.addEventListener("DOMContentLoaded",function(){if(e.urlResolver,window.HTMLImports&&!HTMLImports.useNative){var t="link[rel=stylesheet]["+x+"]",n="style["+x+"]";HTMLImports.importer.documentPreloadSelectors+=","+t,HTMLImports.importer.importsPreloadSelectors+=","+t,HTMLImports.parser.documentSelectors=[HTMLImports.parser.documentSelectors,t,n].join(",");var r=HTMLImports.parser.parseGeneric;HTMLImports.parser.parseGeneric=function(e){if(!e[I]){var t=e.__importElement||e;if(!t.hasAttribute(x))return r.call(this,e),void 0;e.__resource&&(t=e.ownerDocument.createElement("style"),t.textContent=e.__resource),HTMLImports.path.resolveUrlsInStyle(t,e.href),t.textContent=l.shimStyle(t),t.removeAttribute(x,""),t.setAttribute(I,""),t[I]=!0,t.parentNode!==k&&(e.parentNode===k?k.replaceChild(t,e):this.addElementToDocument(t)),t.__importParsed=!0,this.markParsingComplete(e),this.parseNext()}};var o=HTMLImports.parser.hasResource;HTMLImports.parser.hasResource=function(e){return"link"===e.localName&&"stylesheet"===e.rel&&e.hasAttribute(x)?e.__resource:o.call(this,e)}}})}e.ShadowCSS=l}(window.WebComponents)),function(){window.ShadowDOMPolyfill?(window.wrap=ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(e){return e}}(window.WebComponents),function(e){"use strict";function t(e){return void 0!==p[e]}function n(){s.call(this),this._isInvalid=!0}function r(e){return""==e&&n.call(this),e.toLowerCase()}function o(e){var t=e.charCodeAt(0);return t>32&&127>t&&-1==[34,35,60,62,63,96].indexOf(t)?e:encodeURIComponent(e)}function i(e){var t=e.charCodeAt(0);return t>32&&127>t&&-1==[34,35,60,62,96].indexOf(t)?e:encodeURIComponent(e)}function a(e,a,s){function c(e){y.push(e)}var u=a||"scheme start",l=0,d="",g=!1,w=!1,y=[];e:for(;(e[l-1]!=f||0==l)&&!this._isInvalid;){var b=e[l];switch(u){case"scheme start":if(!b||!m.test(b)){if(a){c("Invalid scheme.");break e}d="",u="no scheme";continue}d+=b.toLowerCase(),u="scheme";break;case"scheme":if(b&&v.test(b))d+=b.toLowerCase();else{if(":"!=b){if(a){if(f==b)break e;c("Code point not allowed in scheme: "+b);break e}d="",l=0,u="no scheme";continue}if(this._scheme=d,d="",a)break e;t(this._scheme)&&(this._isRelative=!0),u="file"==this._scheme?"relative":this._isRelative&&s&&s._scheme==this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"==b?(this._query="?",u="query"):"#"==b?(this._fragment="#",u="fragment"):f!=b&&" "!=b&&"\n"!=b&&"\r"!=b&&(this._schemeData+=o(b));break;case"no scheme":if(s&&t(s._scheme)){u="relative";continue}c("Missing scheme."),n.call(this);break;case"relative or authority":if("/"!=b||"/"!=e[l+1]){c("Expected /, got: "+b),u="relative";continue}u="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!=this._scheme&&(this._scheme=s._scheme),f==b){this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query=s._query,this._username=s._username,this._password=s._password;break e}if("/"==b||"\\"==b)"\\"==b&&c("\\ is an invalid code point."),u="relative slash";else if("?"==b)this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query="?",this._username=s._username,this._password=s._password,u="query";else{if("#"!=b){var E=e[l+1],_=e[l+2];("file"!=this._scheme||!m.test(b)||":"!=E&&"|"!=E||f!=_&&"/"!=_&&"\\"!=_&&"?"!=_&&"#"!=_)&&(this._host=s._host,this._port=s._port,this._username=s._username,this._password=s._password,this._path=s._path.slice(),this._path.pop()),u="relative path";continue}this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query=s._query,this._fragment="#",this._username=s._username,this._password=s._password,u="fragment"}break;case"relative slash":if("/"!=b&&"\\"!=b){"file"!=this._scheme&&(this._host=s._host,this._port=s._port,this._username=s._username,this._password=s._password),u="relative path";continue}"\\"==b&&c("\\ is an invalid code point."),u="file"==this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!=b){c("Expected '/', got: "+b),u="authority ignore slashes";continue}u="authority second slash";break;case"authority second slash":if(u="authority ignore slashes","/"!=b){c("Expected '/', got: "+b);continue}break;case"authority ignore slashes":if("/"!=b&&"\\"!=b){u="authority";continue}c("Expected authority, got: "+b);break;case"authority":if("@"==b){g&&(c("@ already seen."),d+="%40"),g=!0;for(var T=0;d.length>T;T++){var S=d[T];if(" "!=S&&"\n"!=S&&"\r"!=S)if(":"!=S||null!==this._password){var M=o(S);null!==this._password?this._password+=M:this._username+=M}else this._password="";else c("Invalid whitespace in authority.")}d=""}else{if(f==b||"/"==b||"\\"==b||"?"==b||"#"==b){l-=d.length,d="",u="host";continue}d+=b}break;case"file host":if(f==b||"/"==b||"\\"==b||"?"==b||"#"==b){2!=d.length||!m.test(d[0])||":"!=d[1]&&"|"!=d[1]?0==d.length?u="relative path start":(this._host=r.call(this,d),d="",u="relative path start"):u="relative path";continue}" "==b||"\n"==b||"\r"==b?c("Invalid whitespace in file host."):d+=b;break;case"host":case"hostname":if(":"!=b||w){if(f==b||"/"==b||"\\"==b||"?"==b||"#"==b){if(this._host=r.call(this,d),d="",u="relative path start",a)break e;continue}" "!=b&&"\n"!=b&&"\r"!=b?("["==b?w=!0:"]"==b&&(w=!1),d+=b):c("Invalid code point in host/hostname: "+b)}else if(this._host=r.call(this,d),d="",u="port","hostname"==a)break e;break;case"port":if(/[0-9]/.test(b))d+=b;else{if(f==b||"/"==b||"\\"==b||"?"==b||"#"==b||a){if(""!=d){var C=parseInt(d,10);C!=p[this._scheme]&&(this._port=C+""),d=""}if(a)break e;u="relative path start";continue}" "==b||"\n"==b||"\r"==b?c("Invalid code point in port: "+b):n.call(this)}break;case"relative path start":if("\\"==b&&c("'\\' not allowed in path."),u="relative path","/"!=b&&"\\"!=b)continue;break;case"relative path":if(f!=b&&"/"!=b&&"\\"!=b&&(a||"?"!=b&&"#"!=b))" "!=b&&"\n"!=b&&"\r"!=b&&(d+=o(b));else{"\\"==b&&c("\\ not allowed in relative path.");var L;(L=h[d.toLowerCase()])&&(d=L),".."==d?(this._path.pop(),"/"!=b&&"\\"!=b&&this._path.push("")):"."==d&&"/"!=b&&"\\"!=b?this._path.push(""):"."!=d&&("file"==this._scheme&&0==this._path.length&&2==d.length&&m.test(d[0])&&"|"==d[1]&&(d=d[0]+":"),this._path.push(d)),d="","?"==b?(this._query="?",u="query"):"#"==b&&(this._fragment="#",u="fragment")}break;case"query":a||"#"!=b?f!=b&&" "!=b&&"\n"!=b&&"\r"!=b&&(this._query+=i(b)):(this._fragment="#",u="fragment");break;case"fragment":f!=b&&" "!=b&&"\n"!=b&&"\r"!=b&&(this._fragment+=b)}l++}}function s(){this._scheme="",this._schemeData="",this._username="",this._password=null,this._host="",this._port="",this._path=[],this._query="",this._fragment="",this._isInvalid=!1,this._isRelative=!1}function c(e,t){void 0===t||t instanceof c||(t=new c(t+"")),this._url=e,s.call(this);var n=e.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");a.call(this,n,null,t)}var u=!1;if(!e.forceJURL)try{var l=new URL("b","http://a");l.pathname="c%20d",u="http://a/c%20d"===l.href}catch(d){}if(!u){var p=Object.create(null);p.ftp=21,p.file=0,p.gopher=70,p.http=80,p.https=443,p.ws=80,p.wss=443;var h=Object.create(null);h["%2e"]=".",h[".%2e"]="..",h["%2e."]="..",h["%2e%2e"]="..";var f=void 0,m=/[a-zA-Z]/,v=/[a-zA-Z0-9\+\-\.]/;c.prototype={toString:function(){return this.href},get href(){if(this._isInvalid)return this._url;var e="";return(""!=this._username||null!=this._password)&&(e=this._username+(null!=this._password?":"+this._password:"")+"@"),this.protocol+(this._isRelative?"//"+e+this.host:"")+this.pathname+this._query+this._fragment},set href(e){s.call(this),a.call(this,e)},get protocol(){return this._scheme+":"},set protocol(e){this._isInvalid||a.call(this,e+":","scheme start")},get host(){return this._isInvalid?"":this._port?this._host+":"+this._port:this._host},set host(e){!this._isInvalid&&this._isRelative&&a.call(this,e,"host")},get hostname(){return this._host},set hostname(e){!this._isInvalid&&this._isRelative&&a.call(this,e,"hostname")},get port(){return this._port},set port(e){!this._isInvalid&&this._isRelative&&a.call(this,e,"port")},get pathname(){return this._isInvalid?"":this._isRelative?"/"+this._path.join("/"):this._schemeData},set pathname(e){!this._isInvalid&&this._isRelative&&(this._path=[],a.call(this,e,"relative path start"))},get search(){return this._isInvalid||!this._query||"?"==this._query?"":this._query},set search(e){!this._isInvalid&&this._isRelative&&(this._query="?","?"==e[0]&&(e=e.slice(1)),a.call(this,e,"query"))},get hash(){return this._isInvalid||!this._fragment||"#"==this._fragment?"":this._fragment},set hash(e){this._isInvalid||(this._fragment="#","#"==e[0]&&(e=e.slice(1)),a.call(this,e,"fragment"))},get origin(){var e;if(this._isInvalid||!this._scheme)return"";switch(this._scheme){case"data":case"file":case"javascript":case"mailto":return"null"}return e=this.host,e?this._scheme+"://"+e:""}};var g=e.URL;g&&(c.createObjectURL=function(){return g.createObjectURL.apply(g,arguments)},c.revokeObjectURL=function(e){g.revokeObjectURL(e)}),e.URL=c}}(self),function(e){function t(e){b.push(e),y||(y=!0,m(r))}function n(e){return window.ShadowDOMPolyfill&&window.ShadowDOMPolyfill.wrapIfNeeded(e)||e}function r(){y=!1;var e=b;b=[],e.sort(function(e,t){return e.uid_-t.uid_});var t=!1;e.forEach(function(e){var n=e.takeRecords();o(e),n.length&&(e.callback_(n,e),t=!0)}),t&&r()}function o(e){e.nodes_.forEach(function(t){var n=v.get(t);n&&n.forEach(function(t){t.observer===e&&t.removeTransientObservers()})})}function i(e,t){for(var n=e;n;n=n.parentNode){var r=v.get(n);if(r)for(var o=0;r.length>o;o++){var i=r[o],a=i.options;if(n===e||a.subtree){var s=t(a);s&&i.enqueue(s)}}}}function a(e){this.callback_=e,this.nodes_=[],this.records_=[],this.uid_=++E}function s(e,t){this.type=e,this.target=t,this.addedNodes=[],this.removedNodes=[],this.previousSibling=null,this.nextSibling=null,this.attributeName=null,this.attributeNamespace=null,this.oldValue=null}function c(e){var t=new s(e.type,e.target);return t.addedNodes=e.addedNodes.slice(),t.removedNodes=e.removedNodes.slice(),t.previousSibling=e.previousSibling,t.nextSibling=e.nextSibling,t.attributeName=e.attributeName,t.attributeNamespace=e.attributeNamespace,t.oldValue=e.oldValue,t}function u(e,t){return _=new s(e,t)}function l(e){return T?T:(T=c(_),T.oldValue=e,T)}function d(){_=T=void 0}function p(e){return e===T||e===_}function h(e,t){return e===t?e:T&&p(e)?T:null}function f(e,t,n){this.observer=e,this.target=t,this.options=n,this.transientObservedNodes=[]}if(!e.JsMutationObserver){var m,v=new WeakMap;if(/Trident|Edge/.test(navigator.userAgent))m=setTimeout;else if(window.setImmediate)m=window.setImmediate;else{var g=[],w=Math.random()+"";window.addEventListener("message",function(e){if(e.data===w){var t=g;g=[],t.forEach(function(e){e()})}}),m=function(e){g.push(e),window.postMessage(w,"*")}}var y=!1,b=[],E=0;a.prototype={observe:function(e,t){if(e=n(e),!t.childList&&!t.attributes&&!t.characterData||t.attributeOldValue&&!t.attributes||t.attributeFilter&&t.attributeFilter.length&&!t.attributes||t.characterDataOldValue&&!t.characterData)throw new SyntaxError;var r=v.get(e);r||v.set(e,r=[]);for(var o,i=0;r.length>i;i++)if(r[i].observer===this){o=r[i],o.removeListeners(),o.options=t;break}o||(o=new f(this,e,t),r.push(o),this.nodes_.push(e)),o.addListeners()},disconnect:function(){this.nodes_.forEach(function(e){for(var t=v.get(e),n=0;t.length>n;n++){var r=t[n];if(r.observer===this){r.removeListeners(),t.splice(n,1);break}}},this),this.records_=[]},takeRecords:function(){var e=this.records_;return this.records_=[],e}};var _,T;f.prototype={enqueue:function(e){var n=this.observer.records_,r=n.length;if(n.length>0){var o=n[r-1],i=h(o,e);if(i)return n[r-1]=i,void 0}else t(this.observer);n[r]=e},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(e){var t=this.options;t.attributes&&e.addEventListener("DOMAttrModified",this,!0),t.characterData&&e.addEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.addEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(e){var t=this.options;t.attributes&&e.removeEventListener("DOMAttrModified",this,!0),t.characterData&&e.removeEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.removeEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(e){if(e!==this.target){this.addListeners_(e),this.transientObservedNodes.push(e);var t=v.get(e);t||v.set(e,t=[]),t.push(this)}},removeTransientObservers:function(){var e=this.transientObservedNodes;this.transientObservedNodes=[],e.forEach(function(e){this.removeListeners_(e);for(var t=v.get(e),n=0;t.length>n;n++)if(t[n]===this){t.splice(n,1);break}},this)},handleEvent:function(e){switch(e.stopImmediatePropagation(),e.type){case"DOMAttrModified":var t=e.attrName,n=e.relatedNode.namespaceURI,r=e.target,o=new u("attributes",r);o.attributeName=t,o.attributeNamespace=n;var a=e.attrChange===MutationEvent.ADDITION?null:e.prevValue;i(r,function(e){return!e.attributes||e.attributeFilter&&e.attributeFilter.length&&-1===e.attributeFilter.indexOf(t)&&-1===e.attributeFilter.indexOf(n)?void 0:e.attributeOldValue?l(a):o});break;case"DOMCharacterDataModified":var r=e.target,o=u("characterData",r),a=e.prevValue;i(r,function(e){return e.characterData?e.characterDataOldValue?l(a):o:void 0});break;case"DOMNodeRemoved":this.addTransientObserver(e.target);case"DOMNodeInserted":var s,c,p=e.target;"DOMNodeInserted"===e.type?(s=[p],c=[]):(s=[],c=[p]);var h=p.previousSibling,f=p.nextSibling,o=u("childList",e.target.parentNode);o.addedNodes=s,o.removedNodes=c,o.previousSibling=h,o.nextSibling=f,i(e.relatedNode,function(e){return e.childList?o:void 0})}d()}},e.JsMutationObserver=a,e.MutationObserver||(e.MutationObserver=a,a._isPolyfilled=!0)}}(self),function(){"use strict";if(!window.performance){var e=Date.now();window.performance={now:function(){return Date.now()-e}}}window.requestAnimationFrame||(window.requestAnimationFrame=function(){var e=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame;return e?function(t){return e(function(){t(performance.now())})}:function(e){return window.setTimeout(e,1e3/60)}}()),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(){return window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(e){clearTimeout(e)}}());var t=function(){var e=document.createEvent("Event");return e.initEvent("foo",!0,!0),e.preventDefault(),e.defaultPrevented}();if(!t){var n=Event.prototype.preventDefault;Event.prototype.preventDefault=function(){this.cancelable&&(n.call(this),Object.defineProperty(this,"defaultPrevented",{get:function(){return!0},configurable:!0}))}}var r=/Trident/.test(navigator.userAgent);if((!window.CustomEvent||r&&"function"!=typeof window.CustomEvent)&&(window.CustomEvent=function(e,t){t=t||{}; -var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,Boolean(t.bubbles),Boolean(t.cancelable),t.detail),n},window.CustomEvent.prototype=window.Event.prototype),!window.Event||r&&"function"!=typeof window.Event){var o=window.Event;window.Event=function(e,t){t=t||{};var n=document.createEvent("Event");return n.initEvent(e,Boolean(t.bubbles),Boolean(t.cancelable)),n},window.Event.prototype=o.prototype}}(window.WebComponents),window.HTMLImports=window.HTMLImports||{flags:{}},function(e){function t(e,t){t=t||f,r(function(){i(e,t)},t)}function n(e){return"complete"===e.readyState||e.readyState===g}function r(e,t){if(n(t))e&&e();else{var o=function(){("complete"===t.readyState||t.readyState===g)&&(t.removeEventListener(w,o),r(e,t))};t.addEventListener(w,o)}}function o(e){e.target.__loaded=!0}function i(e,t){function n(){c==u&&e&&e({allImports:s,loadedImports:l,errorImports:d})}function r(e){o(e),l.push(this),c++,n()}function i(){d.push(this),c++,n()}var s=t.querySelectorAll("link[rel=import]"),c=0,u=s.length,l=[],d=[];if(u)for(var p,h=0;u>h&&(p=s[h]);h++)a(p)?(l.push(this),c++,n()):(p.addEventListener("load",r),p.addEventListener("error",i));else n()}function a(e){return d?e.__loaded||e.import&&"loading"!==e.import.readyState:e.__importParsed}function s(e){for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)c(t)&&u(t)}function c(e){return"link"===e.localName&&"import"===e.rel}function u(e){var t=e.import;t?o({target:e}):(e.addEventListener("load",o),e.addEventListener("error",o))}var l="import",d=Boolean(l in document.createElement("link")),p=Boolean(window.ShadowDOMPolyfill),h=function(e){return p?window.ShadowDOMPolyfill.wrapIfNeeded(e):e},f=h(document),m={get:function(){var e=window.HTMLImports.currentScript||document.currentScript||("complete"!==document.readyState?document.scripts[document.scripts.length-1]:null);return h(e)},configurable:!0};Object.defineProperty(document,"_currentScript",m),Object.defineProperty(f,"_currentScript",m);var v=/Trident/.test(navigator.userAgent),g=v?"complete":"interactive",w="readystatechange";d&&(new MutationObserver(function(e){for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)t.addedNodes&&s(t.addedNodes)}).observe(document.head,{childList:!0}),function(){if("loading"===document.readyState)for(var e,t=document.querySelectorAll("link[rel=import]"),n=0,r=t.length;r>n&&(e=t[n]);n++)u(e)}()),t(function(e){window.HTMLImports.ready=!0,window.HTMLImports.readyTime=(new Date).getTime();var t=f.createEvent("CustomEvent");t.initCustomEvent("HTMLImportsLoaded",!0,!0,e),f.dispatchEvent(t)}),e.IMPORT_LINK_TYPE=l,e.useNative=d,e.rootDocument=f,e.whenReady=t,e.isIE=v}(window.HTMLImports),function(e){var t=[],n=function(e){t.push(e)},r=function(){t.forEach(function(t){t(e)})};e.addModule=n,e.initializeModules=r}(window.HTMLImports),window.HTMLImports.addModule(function(e){var t=/(url\()([^)]*)(\))/g,n=/(@import[\s]+(?!url\())([^;]*)(;)/g,r={resolveUrlsInStyle:function(e,t){var n=e.ownerDocument,r=n.createElement("a");return e.textContent=this.resolveUrlsInCssText(e.textContent,t,r),e},resolveUrlsInCssText:function(e,r,o){var i=this.replaceUrls(e,o,r,t);return i=this.replaceUrls(i,o,r,n)},replaceUrls:function(e,t,n,r){return e.replace(r,function(e,r,o,i){var a=o.replace(/["']/g,"");return n&&(a=new URL(a,n).href),t.href=a,a=t.href,r+"'"+a+"'"+i})}};e.path=r}),window.HTMLImports.addModule(function(e){var t={async:!0,ok:function(e){return e.status>=200&&300>e.status||304===e.status||0===e.status},load:function(n,r,o){var i=new XMLHttpRequest;return(e.flags.debug||e.flags.bust)&&(n+="?"+Math.random()),i.open("GET",n,t.async),i.addEventListener("readystatechange",function(e){if(4===i.readyState){var n=null;try{var a=i.getResponseHeader("Location");a&&(n="/"===a.substr(0,1)?location.origin+a:a)}catch(e){console.error(e.message)}r.call(o,!t.ok(i)&&i,i.response||i.responseText,n)}}),i.send(),i},loadDocument:function(e,t,n){this.load(e,t,n).responseType="document"}};e.xhr=t}),window.HTMLImports.addModule(function(e){var t=e.xhr,n=e.flags,r=function(e,t){this.cache={},this.onload=e,this.oncomplete=t,this.inflight=0,this.pending={}};r.prototype={addNodes:function(e){this.inflight+=e.length;for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)this.require(t);this.checkDone()},addNode:function(e){this.inflight++,this.require(e),this.checkDone()},require:function(e){var t=e.src||e.href;e.__nodeUrl=t,this.dedupe(t,e)||this.fetch(t,e)},dedupe:function(e,t){return this.pending[e]?(this.pending[e].push(t),!0):this.cache[e]?(this.onload(e,t,this.cache[e]),this.tail(),!0):(this.pending[e]=[t],!1)},fetch:function(e,r){if(n.load&&console.log("fetch",e,r),e)if(e.match(/^data:/)){var o=e.split(","),i=o[0],a=o[1];a=i.indexOf(";base64")>-1?atob(a):decodeURIComponent(a),setTimeout(function(){this.receive(e,r,null,a)}.bind(this),0)}else{var s=function(t,n,o){this.receive(e,r,t,n,o)}.bind(this);t.load(e,s)}else setTimeout(function(){this.receive(e,r,{error:"href must be specified"},null)}.bind(this),0)},receive:function(e,t,n,r,o){this.cache[e]=r;for(var i,a=this.pending[e],s=0,c=a.length;c>s&&(i=a[s]);s++)this.onload(e,i,r,n,o),this.tail();this.pending[e]=null},tail:function(){--this.inflight,this.checkDone()},checkDone:function(){this.inflight||this.oncomplete()}},e.Loader=r}),window.HTMLImports.addModule(function(e){var t=function(e){this.addCallback=e,this.mo=new MutationObserver(this.handler.bind(this))};t.prototype={handler:function(e){for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)"childList"===t.type&&t.addedNodes.length&&this.addedNodes(t.addedNodes)},addedNodes:function(e){this.addCallback&&this.addCallback(e);for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)t.children&&t.children.length&&this.addedNodes(t.children)},observe:function(e){this.mo.observe(e,{childList:!0,subtree:!0})}},e.Observer=t}),window.HTMLImports.addModule(function(e){function t(e){return"link"===e.localName&&e.rel===l}function n(e){var t=r(e);return"data:text/javascript;charset=utf-8,"+encodeURIComponent(t)}function r(e){return e.textContent+o(e)}function o(e){var t=e.ownerDocument;t.__importedScripts=t.__importedScripts||0;var n=e.ownerDocument.baseURI,r=t.__importedScripts?"-"+t.__importedScripts:"";return t.__importedScripts++,"\n//# sourceURL="+n+r+".js\n"}function i(e){var t=e.ownerDocument.createElement("style");return t.textContent=e.textContent,a.resolveUrlsInStyle(t),t}var a=e.path,s=e.rootDocument,c=e.flags,u=e.isIE,l=e.IMPORT_LINK_TYPE,d="link[rel="+l+"]",p={documentSelectors:d,importsSelectors:[d,"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 e=this.nextToParse();e&&this.parse(e)},parse:function(e){if(this.isParsed(e))return c.parse&&console.log("[%s] is already parsed",e.localName),void 0;var t=this[this.map[e.localName]];t&&(this.markParsing(e),t.call(this,e))},parseDynamic:function(e,t){this.dynamicElements.push(e),t||this.parseNext()},markParsing:function(e){c.parse&&console.log("parsing",e),this.parsingElement=e},markParsingComplete:function(e){e.__importParsed=!0,this.markDynamicParsingComplete(e),e.__importElement&&(e.__importElement.__importParsed=!0,this.markDynamicParsingComplete(e.__importElement)),this.parsingElement=null,c.parse&&console.log("completed",e)},markDynamicParsingComplete:function(e){var t=this.dynamicElements.indexOf(e);t>=0&&this.dynamicElements.splice(t,1)},parseImport:function(e){if(e.import=e.__doc,window.HTMLImports.__importsParsingHook&&window.HTMLImports.__importsParsingHook(e),e.import&&(e.import.__importParsed=!0),this.markParsingComplete(e),e.__resource&&!e.__error?e.dispatchEvent(new CustomEvent("load",{bubbles:!1})):e.dispatchEvent(new CustomEvent("error",{bubbles:!1})),e.__pending)for(var t;e.__pending.length;)t=e.__pending.shift(),t&&t({target:e});this.parseNext()},parseLink:function(e){t(e)?this.parseImport(e):(e.href=e.href,this.parseGeneric(e))},parseStyle:function(e){var t=e;e=i(e),t.__appliedElement=e,e.__importElement=t,this.parseGeneric(e)},parseGeneric:function(e){this.trackElement(e),this.addElementToDocument(e)},rootImportForElement:function(e){for(var t=e;t.ownerDocument.__importLink;)t=t.ownerDocument.__importLink;return t},addElementToDocument:function(e){var t=this.rootImportForElement(e.__importElement||e);t.parentNode.insertBefore(e,t)},trackElement:function(e,t){var n=this,r=function(o){e.removeEventListener("load",r),e.removeEventListener("error",r),t&&t(o),n.markParsingComplete(e),n.parseNext()};if(e.addEventListener("load",r),e.addEventListener("error",r),u&&"style"===e.localName){var o=!1;if(-1==e.textContent.indexOf("@import"))o=!0;else if(e.sheet){o=!0;for(var i,a=e.sheet.cssRules,s=a?a.length:0,c=0;s>c&&(i=a[c]);c++)i.type===CSSRule.IMPORT_RULE&&(o=o&&Boolean(i.styleSheet))}o&&setTimeout(function(){e.dispatchEvent(new CustomEvent("load",{bubbles:!1}))})}},parseScript:function(t){var r=document.createElement("script");r.__importElement=t,r.src=t.src?t.src:n(t),e.currentScript=t,this.trackElement(r,function(){r.parentNode&&r.parentNode.removeChild(r),e.currentScript=null}),this.addElementToDocument(r)},nextToParse:function(){return this._mayParse=[],!this.parsingElement&&(this.nextToParseInDoc(s)||this.nextToParseDynamic())},nextToParseInDoc:function(e,n){if(e&&0>this._mayParse.indexOf(e)){this._mayParse.push(e);for(var r,o=e.querySelectorAll(this.parseSelectorsForNode(e)),i=0,a=o.length;a>i&&(r=o[i]);i++)if(!this.isParsed(r))return this.hasResource(r)?t(r)?this.nextToParseInDoc(r.__doc,r):r:void 0}return n},nextToParseDynamic:function(){return this.dynamicElements[0]},parseSelectorsForNode:function(e){var t=e.ownerDocument||e;return t===s?this.documentSelectors:this.importsSelectors},isParsed:function(e){return e.__importParsed},needsDynamicParsing:function(e){return this.dynamicElements.indexOf(e)>=0},hasResource:function(e){return t(e)&&void 0===e.__doc?!1:!0}};e.parser=p,e.IMPORT_SELECTOR=d}),window.HTMLImports.addModule(function(e){function t(e){return n(e,a)}function n(e,t){return"link"===e.localName&&e.getAttribute("rel")===t}function r(e){return!!Object.getOwnPropertyDescriptor(e,"baseURI")}function o(e,t){var n=document.implementation.createHTMLDocument(a);n._URL=t;var o=n.createElement("base");o.setAttribute("href",t),n.baseURI||r(n)||Object.defineProperty(n,"baseURI",{value:t});var i=n.createElement("meta");return i.setAttribute("charset","utf-8"),n.head.appendChild(i),n.head.appendChild(o),n.body.innerHTML=e,window.HTMLTemplateElement&&HTMLTemplateElement.bootstrap&&HTMLTemplateElement.bootstrap(n),n}var i=e.flags,a=e.IMPORT_LINK_TYPE,s=e.IMPORT_SELECTOR,c=e.rootDocument,u=e.Loader,l=e.Observer,d=e.parser,p={documents:{},documentPreloadSelectors:s,importsPreloadSelectors:[s].join(","),loadNode:function(e){h.addNode(e)},loadSubtree:function(e){var t=this.marshalNodes(e);h.addNodes(t)},marshalNodes:function(e){return e.querySelectorAll(this.loadSelectorsForNode(e))},loadSelectorsForNode:function(e){var t=e.ownerDocument||e;return t===c?this.documentPreloadSelectors:this.importsPreloadSelectors},loaded:function(e,n,r,a,s){if(i.load&&console.log("loaded",e,n),n.__resource=r,n.__error=a,t(n)){var c=this.documents[e];void 0===c&&(c=a?null:o(r,s||e),c&&(c.__importLink=n,this.bootDocument(c)),this.documents[e]=c),n.__doc=c}d.parseNext()},bootDocument:function(e){this.loadSubtree(e),this.observer.observe(e),d.parseNext()},loadedAll:function(){d.parseNext()}},h=new u(p.loaded.bind(p),p.loadedAll.bind(p));if(p.observer=new l,!document.baseURI){var f={get:function(){var e=document.querySelector("base");return e?e.href:window.location.href},configurable:!0};Object.defineProperty(document,"baseURI",f),Object.defineProperty(c,"baseURI",f)}e.importer=p,e.importLoader=h}),window.HTMLImports.addModule(function(e){var t=e.parser,n=e.importer,r={added:function(e){for(var r,o,i,a,s=0,c=e.length;c>s&&(a=e[s]);s++)r||(r=a.ownerDocument,o=t.isParsed(r)),i=this.shouldLoadNode(a),i&&n.loadNode(a),this.shouldParseNode(a)&&o&&t.parseDynamic(a,i)},shouldLoadNode:function(e){return 1===e.nodeType&&o.call(e,n.loadSelectorsForNode(e))},shouldParseNode:function(e){return 1===e.nodeType&&o.call(e,t.parseSelectorsForNode(e))}};n.observer.addCallback=r.added.bind(r);var o=HTMLElement.prototype.matches||HTMLElement.prototype.matchesSelector||HTMLElement.prototype.webkitMatchesSelector||HTMLElement.prototype.mozMatchesSelector||HTMLElement.prototype.msMatchesSelector}),function(e){function t(){window.HTMLImports.importer.bootDocument(r)}var n=e.initializeModules;if(e.isIE,!e.useNative){n();var r=e.rootDocument;"complete"===document.readyState||"interactive"===document.readyState&&!window.attachEvent?t():document.addEventListener("DOMContentLoaded",t)}}(window.HTMLImports),window.CustomElements=window.CustomElements||{flags:{}},function(e){var t=e.flags,n=[],r=function(e){n.push(e)},o=function(){n.forEach(function(t){t(e)})};e.addModule=r,e.initializeModules=o,e.hasNative=Boolean(document.registerElement),e.isIE=/Trident/.test(navigator.userAgent),e.useNative=!t.register&&e.hasNative&&!window.ShadowDOMPolyfill&&(!window.HTMLImports||window.HTMLImports.useNative)}(window.CustomElements),window.CustomElements.addModule(function(e){function t(e,t){n(e,function(e){return t(e)?!0:(r(e,t),void 0)}),r(e,t)}function n(e,t,r){var o=e.firstElementChild;if(!o)for(o=e.firstChild;o&&o.nodeType!==Node.ELEMENT_NODE;)o=o.nextSibling;for(;o;)t(o,r)!==!0&&n(o,t,r),o=o.nextElementSibling;return null}function r(e,n){for(var r=e.shadowRoot;r;)t(r,n),r=r.olderShadowRoot}function o(e,t){i(e,t,[])}function i(e,t,n){if(e=window.wrap(e),!(n.indexOf(e)>=0)){n.push(e);for(var r,o=e.querySelectorAll("link[rel="+a+"]"),s=0,c=o.length;c>s&&(r=o[s]);s++)r.import&&i(r.import,t,n);t(e)}}var a=window.HTMLImports?window.HTMLImports.IMPORT_LINK_TYPE:"none";e.forDocumentTree=o,e.forSubtree=t}),window.CustomElements.addModule(function(e){function t(e,t){return n(e,t)||r(e,t)}function n(t,n){return e.upgrade(t,n)?!0:(n&&a(t),void 0)}function r(e,t){y(e,function(e){return n(e,t)?!0:void 0})}function o(e){T.push(e),_||(_=!0,setTimeout(i))}function i(){_=!1;for(var e,t=T,n=0,r=t.length;r>n&&(e=t[n]);n++)e();T=[]}function a(e){E?o(function(){s(e)}):s(e)}function s(e){e.__upgraded__&&!e.__attached&&(e.__attached=!0,e.attachedCallback&&e.attachedCallback())}function c(e){u(e),y(e,function(e){u(e)})}function u(e){E?o(function(){l(e)}):l(e)}function l(e){e.__upgraded__&&e.__attached&&(e.__attached=!1,e.detachedCallback&&e.detachedCallback())}function d(e){for(var t=e,n=window.wrap(document);t;){if(t==n)return!0;t=t.parentNode||t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&t.host}}function p(e){if(e.shadowRoot&&!e.shadowRoot.__watched){w.dom&&console.log("watching shadow-root for: ",e.localName);for(var t=e.shadowRoot;t;)m(t),t=t.olderShadowRoot}}function h(e,n){if(w.dom){var r=n[0];if(r&&"childList"===r.type&&r.addedNodes&&r.addedNodes){for(var o=r.addedNodes[0];o&&o!==document&&!o.host;)o=o.parentNode;var i=o&&(o.URL||o._URL||o.host&&o.host.localName)||"";i=i.split("/?").shift().split("/").pop()}console.group("mutations (%d) [%s]",n.length,i||"")}var a=d(e);n.forEach(function(e){"childList"===e.type&&(S(e.addedNodes,function(e){e.localName&&t(e,a)}),S(e.removedNodes,function(e){e.localName&&c(e)}))}),w.dom&&console.groupEnd()}function f(e){for(e=window.wrap(e),e||(e=window.wrap(document));e.parentNode;)e=e.parentNode;var t=e.__observer;t&&(h(e,t.takeRecords()),i())}function m(e){if(!e.__observer){var t=new MutationObserver(h.bind(this,e));t.observe(e,{childList:!0,subtree:!0}),e.__observer=t}}function v(e){e=window.wrap(e),w.dom&&console.group("upgradeDocument: ",e.baseURI.split("/").pop());var n=e===window.wrap(document);t(e,n),m(e),w.dom&&console.groupEnd()}function g(e){b(e,v)}var w=e.flags,y=e.forSubtree,b=e.forDocumentTree,E=window.MutationObserver._isPolyfilled&&w["throttle-attached"];e.hasPolyfillMutations=E,e.hasThrottledAttached=E;var _=!1,T=[],S=Array.prototype.forEach.call.bind(Array.prototype.forEach),M=Element.prototype.createShadowRoot;M&&(Element.prototype.createShadowRoot=function(){var e=M.call(this);return window.CustomElements.watchShadow(this),e}),e.watchShadow=p,e.upgradeDocumentTree=g,e.upgradeDocument=v,e.upgradeSubtree=r,e.upgradeAll=t,e.attached=a,e.takeRecords=f}),window.CustomElements.addModule(function(e){function t(t,r){if("template"===t.localName&&window.HTMLTemplateElement&&HTMLTemplateElement.decorate&&HTMLTemplateElement.decorate(t),!t.__upgraded__&&t.nodeType===Node.ELEMENT_NODE){var o=t.getAttribute("is"),i=e.getRegisteredDefinition(t.localName)||e.getRegisteredDefinition(o);if(i&&(o&&i.tag==t.localName||!o&&!i.extends))return n(t,i,r)}}function n(t,n,o){return a.upgrade&&console.group("upgrade:",t.localName),n.is&&t.setAttribute("is",n.is),r(t,n),t.__upgraded__=!0,i(t),o&&e.attached(t),e.upgradeSubtree(t,o),a.upgrade&&console.groupEnd(),t}function r(e,t){Object.__proto__?e.__proto__=t.prototype:(o(e,t.prototype,t.native),e.__proto__=t.prototype)}function o(e,t,n){for(var r={},o=t;o!==n&&o!==HTMLElement.prototype;){for(var i,a=Object.getOwnPropertyNames(o),s=0;i=a[s];s++)r[i]||(Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(o,i)),r[i]=1);o=Object.getPrototypeOf(o)}}function i(e){e.createdCallback&&e.createdCallback()}var a=e.flags;e.upgrade=t,e.upgradeWithDefinition=n,e.implementPrototype=r}),window.CustomElements.addModule(function(e){function t(t,r){var c=r||{};if(!t)throw Error("document.registerElement: first argument `name` must not be empty");if(0>t.indexOf("-"))throw Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '"+(t+"")+"'.");if(o(t))throw Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '"+(t+"")+"'. The type name is invalid.");if(u(t))throw Error("DuplicateDefinitionError: a type with name '"+(t+"")+"' is already registered");return c.prototype||(c.prototype=Object.create(HTMLElement.prototype)),c.__name=t.toLowerCase(),c.lifecycle=c.lifecycle||{},c.ancestry=i(c.extends),a(c),s(c),n(c.prototype),l(c.__name,c),c.ctor=d(c),c.ctor.prototype=c.prototype,c.prototype.constructor=c.ctor,e.ready&&g(document),c.ctor}function n(e){if(!e.setAttribute._polyfilled){var t=e.setAttribute;e.setAttribute=function(e,n){r.call(this,e,n,t)};var n=e.removeAttribute;e.removeAttribute=function(e){r.call(this,e,null,n)},e.setAttribute._polyfilled=!0}}function r(e,t,n){e=e.toLowerCase();var r=this.getAttribute(e);n.apply(this,arguments);var o=this.getAttribute(e);this.attributeChangedCallback&&o!==r&&this.attributeChangedCallback(e,r,o)}function o(e){for(var t=0;_.length>t;t++)if(e===_[t])return!0}function i(e){var t=u(e);return t?i(t.extends).concat([t]):[]}function a(e){for(var t,n=e.extends,r=0;t=e.ancestry[r];r++)n=t.is&&t.tag;e.tag=n||e.__name,n&&(e.is=e.__name)}function s(e){if(!Object.__proto__){var t=HTMLElement.prototype;if(e.is){var n=document.createElement(e.tag);t=Object.getPrototypeOf(n)}for(var r,o=e.prototype,i=!1;o;)o==t&&(i=!0),r=Object.getPrototypeOf(o),r&&(o.__proto__=r),o=r;i||console.warn(e.tag+" prototype not found in prototype chain for "+e.is),e.native=t}}function c(e){return y(M(e.tag),e)}function u(e){return e?T[e.toLowerCase()]:void 0}function l(e,t){T[e]=t}function d(e){return function(){return c(e)}}function p(e,t,n){return e===S?h(t,n):C(e,t)}function h(e,t){e&&(e=e.toLowerCase()),t&&(t=t.toLowerCase());var n=u(t||e);if(n){if(e==n.tag&&t==n.is)return new n.ctor;if(!t&&!n.is)return new n.ctor}var r;return t?(r=h(e),r.setAttribute("is",t),r):(r=M(e),e.indexOf("-")>=0&&b(r,HTMLElement),r)}function f(e,t){var n=e[t];e[t]=function(){var e=n.apply(this,arguments);return w(e),e}}var m,v=e.isIE,g=e.upgradeDocumentTree,w=e.upgradeAll,y=e.upgradeWithDefinition,b=e.implementPrototype,E=e.useNative,_=["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"],T={},S="http://www.w3.org/1999/xhtml",M=document.createElement.bind(document),C=document.createElementNS.bind(document);m=Object.__proto__||E?function(e,t){return e instanceof t}:function(e,t){if(e instanceof t)return!0;for(var n=e;n;){if(n===t.prototype)return!0;n=n.__proto__}return!1},f(Node.prototype,"cloneNode"),f(document,"importNode"),v&&function(){var e=document.importNode;document.importNode=function(){var t=e.apply(document,arguments);if(t.nodeType==t.DOCUMENT_FRAGMENT_NODE){var n=document.createDocumentFragment();return n.appendChild(t),n}return t}}(),document.registerElement=t,document.createElement=h,document.createElementNS=p,e.registry=T,e.instanceof=m,e.reservedTagList=_,e.getRegisteredDefinition=u,document.register=document.registerElement}),function(e){function t(){i(window.wrap(document)),window.CustomElements.ready=!0;var e=window.requestAnimationFrame||function(e){setTimeout(e,16)};e(function(){setTimeout(function(){window.CustomElements.readyTime=Date.now(),window.HTMLImports&&(window.CustomElements.elapsed=window.CustomElements.readyTime-window.HTMLImports.readyTime),document.dispatchEvent(new CustomEvent("WebComponentsReady",{bubbles:!0}))})})}var n=e.useNative,r=e.initializeModules;if(e.isIE,n){var o=function(){};e.watchShadow=o,e.upgrade=o,e.upgradeAll=o,e.upgradeDocumentTree=o,e.upgradeSubtree=o,e.takeRecords=o,e.instanceof=function(e,t){return e instanceof t}}else r();var i=e.upgradeDocumentTree,a=e.upgradeDocument;if(window.wrap||(window.ShadowDOMPolyfill?(window.wrap=window.ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=window.ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(e){return e}),window.HTMLImports&&(window.HTMLImports.__importsParsingHook=function(e){e.import&&a(wrap(e.import))}),"complete"===document.readyState||e.flags.eager)t();else if("interactive"!==document.readyState||window.attachEvent||window.HTMLImports&&!window.HTMLImports.ready){var s=window.HTMLImports&&!window.HTMLImports.ready?"HTMLImportsLoaded":"DOMContentLoaded";window.addEventListener(s,t)}else t()}(window.CustomElements),function(){Function.prototype.bind||(Function.prototype.bind=function(e){var t=this,n=Array.prototype.slice.call(arguments,1);return function(){var r=n.slice();return r.push.apply(r,arguments),t.apply(e,r)}})}(window.WebComponents),function(){var e=document.createElement("style");e.textContent="body {transition: opacity ease-in 0.2s; } \nbody[unresolved] {opacity: 0; display: block; overflow: hidden; position: relative; } \n";var t=document.querySelector("head");t.insertBefore(e,t.firstChild)}(window.WebComponents),function(e){window.Platform=e}(window.WebComponents),function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.PointerEventsPolyfill=t()}(this,function(){"use strict";function e(e,t){t=t||Object.create(null);var n=document.createEvent("Event");n.initEvent(e,t.bubbles||!1,t.cancelable||!1);for(var r,o=2;l.length>o;o++)r=l[o],n[r]=t[r]||d[o];n.buttons=t.buttons||0;var i=0;return i=t.pressure?t.pressure:n.buttons?.5:0,n.x=n.clientX,n.y=n.clientY,n.pointerId=t.pointerId||0,n.width=t.width||0,n.height=t.height||0,n.pressure=i,n.tiltX=t.tiltX||0,n.tiltY=t.tiltY||0,n.pointerType=t.pointerType||"",n.hwTimestamp=t.hwTimestamp||0,n.isPrimary=t.isPrimary||!1,n}function t(){this.array=[],this.size=0}function n(e,t,n,r){this.addCallback=e.bind(r),this.removeCallback=t.bind(r),this.changedCallback=n.bind(r),L&&(this.observer=new L(this.mutationWatcher.bind(this)))}function r(e){return"body /shadow-deep/ "+o(e)}function o(e){return'[touch-action="'+e+'"]'}function i(e){return"{ -ms-touch-action: "+e+"; touch-action: "+e+"; touch-action-delay: none; }"}function a(){if(I){D.forEach(function(e){e+""===e?(x+=o(e)+i(e)+"\n",R&&(x+=r(e)+i(e)+"\n")):(x+=e.selectors.map(o)+i(e.rule)+"\n",R&&(x+=e.selectors.map(r)+i(e.rule)+"\n"))});var e=document.createElement("style");e.textContent=x,document.head.appendChild(e)}}function s(){if(!window.PointerEvent){if(window.PointerEvent=p,window.navigator.msPointerEnabled){var e=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:e,enumerable:!0}),E.registerSource("ms",ot)}else E.registerSource("mouse",U),void 0!==window.ontouchstart&&E.registerSource("touch",et);E.register(document)}}function c(e){if(!E.pointermap.has(e))throw Error("InvalidPointerId")}function u(){window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:J},releasePointerCapture:{value:Q}})}var l=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],d=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],p=e,h=window.Map&&window.Map.prototype.forEach,f=h?Map:t;t.prototype={set:function(e,t){return void 0===t?this.delete(e):(this.has(e)||this.size++,this.array[e]=t,void 0)},has:function(e){return void 0!==this.array[e]},"delete":function(e){this.has(e)&&(delete this.array[e],this.size--)},get:function(e){return this.array[e]},clear:function(){this.array.length=0,this.size=0},forEach:function(e,t){return this.array.forEach(function(n,r){e.call(t,n,r,this)},this)}};var m=f,v=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","buttons","pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary","type","target","currentTarget","which","pageX","pageY","timeStamp"],g=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0,0,0,0,0,0,"",0,!1,"",null,null,0,0,0,0],w={pointerover:1,pointerout:1,pointerenter:1,pointerleave:1},y="undefined"!=typeof SVGElementInstance,b={pointermap:new m,eventMap:Object.create(null),captureInfo:Object.create(null),eventSources:Object.create(null),eventSourceList:[],registerSource:function(e,t){var n=t,r=n.events;r&&(r.forEach(function(e){n[e]&&(this.eventMap[e]=n[e].bind(n))},this),this.eventSources[e]=n,this.eventSourceList.push(n))},register:function(e){for(var t,n=this.eventSourceList.length,r=0;n>r&&(t=this.eventSourceList[r]);r++)t.register.call(t,e)},unregister:function(e){for(var t,n=this.eventSourceList.length,r=0;n>r&&(t=this.eventSourceList[r]);r++)t.unregister.call(t,e)},contains:function(e,t){try{return e.contains(t)}catch(n){return!1}},down:function(e){e.bubbles=!0,this.fireEvent("pointerdown",e)},move:function(e){e.bubbles=!0,this.fireEvent("pointermove",e)},up:function(e){e.bubbles=!0,this.fireEvent("pointerup",e)},enter:function(e){e.bubbles=!1,this.fireEvent("pointerenter",e)},leave:function(e){e.bubbles=!1,this.fireEvent("pointerleave",e)},over:function(e){e.bubbles=!0,this.fireEvent("pointerover",e)},out:function(e){e.bubbles=!0,this.fireEvent("pointerout",e)},cancel:function(e){e.bubbles=!0,this.fireEvent("pointercancel",e)},leaveOut:function(e){this.out(e),this.contains(e.target,e.relatedTarget)||this.leave(e)},enterOver:function(e){this.over(e),this.contains(e.target,e.relatedTarget)||this.enter(e)},eventHandler:function(e){if(!e._handledByPE){var t=e.type,n=this.eventMap&&this.eventMap[t];n&&n(e),e._handledByPE=!0}},listen:function(e,t){t.forEach(function(t){this.addEvent(e,t)},this)},unlisten:function(e,t){t.forEach(function(t){this.removeEvent(e,t)},this)},addEvent:function(e,t){e.addEventListener(t,this.boundHandler)},removeEvent:function(e,t){e.removeEventListener(t,this.boundHandler)},makeEvent:function(e,t){this.captureInfo[t.pointerId]&&(t.relatedTarget=null);var n=new p(e,t);return t.preventDefault&&(n.preventDefault=t.preventDefault),n._target=n._target||t.target,n},fireEvent:function(e,t){var n=this.makeEvent(e,t);return this.dispatchEvent(n)},cloneEvent:function(e){for(var t,n=Object.create(null),r=0;v.length>r;r++)t=v[r],n[t]=e[t]||g[r],!y||"target"!==t&&"relatedTarget"!==t||n[t]instanceof SVGElementInstance&&(n[t]=n[t].correspondingUseElement);return e.preventDefault&&(n.preventDefault=function(){e.preventDefault()}),n},getTarget:function(e){var t=this.captureInfo[e.pointerId];return t?e._target!==t&&e.type in w?void 0:t:e._target},setCapture:function(e,t){this.captureInfo[e]&&this.releaseCapture(e),this.captureInfo[e]=t;var n=document.createEvent("Event");n.initEvent("gotpointercapture",!0,!1),n.pointerId=e,this.implicitRelease=this.releaseCapture.bind(this,e),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease),n._target=t,this.asyncDispatchEvent(n)},releaseCapture:function(e){var t=this.captureInfo[e];if(t){var n=document.createEvent("Event");n.initEvent("lostpointercapture",!0,!1),n.pointerId=e,this.captureInfo[e]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease),n._target=t,this.asyncDispatchEvent(n)}},dispatchEvent:function(e){var t=this.getTarget(e);return t?t.dispatchEvent(e):void 0},asyncDispatchEvent:function(e){requestAnimationFrame(this.dispatchEvent.bind(this,e))}};b.boundHandler=b.eventHandler.bind(b);var E=b,_={shadow:function(e){return e?e.shadowRoot||e.webkitShadowRoot:void 0},canTarget:function(e){return e&&Boolean(e.elementFromPoint)},targetingShadow:function(e){var t=this.shadow(e);return this.canTarget(t)?t:void 0},olderShadow:function(e){var t=e.olderShadowRoot;if(!t){var n=e.querySelector("shadow");n&&(t=n.olderShadowRoot)}return t},allShadows:function(e){for(var t=[],n=this.shadow(e);n;)t.push(n),n=this.olderShadow(n);return t},searchRoot:function(e,t,n){if(e){var r,o,i=e.elementFromPoint(t,n);for(o=this.targetingShadow(i);o;){if(r=o.elementFromPoint(t,n)){var a=this.targetingShadow(r);return this.searchRoot(a,t,n)||r}o=this.olderShadow(o)}return i}},owner:function(e){for(var t=e;t.parentNode;)t=t.parentNode;return t.nodeType!==Node.DOCUMENT_NODE&&t.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(t=document),t},findTarget:function(e){var t=e.clientX,n=e.clientY,r=this.owner(e.target);return r.elementFromPoint(t,n)||(r=document),this.searchRoot(r,t,n)}},T=Array.prototype.forEach.call.bind(Array.prototype.forEach),S=Array.prototype.map.call.bind(Array.prototype.map),M=Array.prototype.slice.call.bind(Array.prototype.slice),C=Array.prototype.filter.call.bind(Array.prototype.filter),L=window.MutationObserver||window.WebKitMutationObserver,N="[touch-action]",O={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};n.prototype={watchSubtree:function(e){this.observer&&_.canTarget(e)&&this.observer.observe(e,O)},enableOnSubtree:function(e){this.watchSubtree(e),e===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(e)},installNewSubtree:function(e){T(this.findElements(e),this.addElement,this)},findElements:function(e){return e.querySelectorAll?e.querySelectorAll(N):[]},removeElement:function(e){this.removeCallback(e)},addElement:function(e){this.addCallback(e)},elementChanged:function(e,t){this.changedCallback(e,t)},concatLists:function(e,t){return e.concat(M(t))},installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(e){return e.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(e){var t=S(e,this.findElements,this);return t.push(C(e,this.isElement)),t.reduce(this.concatLists,[])},mutationWatcher:function(e){e.forEach(this.mutationHandler,this)},mutationHandler:function(e){if("childList"===e.type){var t=this.flattenMutationTree(e.addedNodes);t.forEach(this.addElement,this);var n=this.flattenMutationTree(e.removedNodes);n.forEach(this.removeElement,this)}else"attributes"===e.type&&this.elementChanged(e.target,e.oldValue)}};var P=n,D=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],x="",I=window.PointerEvent||window.MSPointerEvent,R=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,A=E.pointermap,k=25,H=[1,4,2,8,16],j=!1; -try{j=1===new MouseEvent("test",{buttons:1}).buttons}catch(F){}var q,W={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(e){E.listen(e,this.events)},unregister:function(e){E.unlisten(e,this.events)},lastTouches:[],isEventSimulatedFromTouch:function(e){for(var t,n=this.lastTouches,r=e.clientX,o=e.clientY,i=0,a=n.length;a>i&&(t=n[i]);i++){var s=Math.abs(r-t.x),c=Math.abs(o-t.y);if(k>=s&&k>=c)return!0}},prepareEvent:function(e){var t=E.cloneEvent(e),n=t.preventDefault;return t.preventDefault=function(){e.preventDefault(),n()},t.pointerId=this.POINTER_ID,t.isPrimary=!0,t.pointerType=this.POINTER_TYPE,t},prepareButtonsForMove:function(e,t){var n=A.get(this.POINTER_ID);e.buttons=n?n.buttons:0,t.buttons=e.buttons},mousedown:function(e){if(!this.isEventSimulatedFromTouch(e)){var t=A.get(this.POINTER_ID),n=this.prepareEvent(e);j||(n.buttons=H[n.button],t&&(n.buttons|=t.buttons),e.buttons=n.buttons),A.set(this.POINTER_ID,e),t?E.move(n):E.down(n)}},mousemove:function(e){if(!this.isEventSimulatedFromTouch(e)){var t=this.prepareEvent(e);j||this.prepareButtonsForMove(t,e),E.move(t)}},mouseup:function(e){if(!this.isEventSimulatedFromTouch(e)){var t=A.get(this.POINTER_ID),n=this.prepareEvent(e);if(!j){var r=H[n.button];n.buttons=t?t.buttons&~r:0,e.buttons=n.buttons}A.set(this.POINTER_ID,e),0===n.buttons||n.buttons===H[n.button]?(this.cleanupMouse(),E.up(n)):E.move(n)}},mouseover:function(e){if(!this.isEventSimulatedFromTouch(e)){var t=this.prepareEvent(e);j||this.prepareButtonsForMove(t,e),E.enterOver(t)}},mouseout:function(e){if(!this.isEventSimulatedFromTouch(e)){var t=this.prepareEvent(e);j||this.prepareButtonsForMove(t,e),E.leaveOut(t)}},cancel:function(e){var t=this.prepareEvent(e);E.cancel(t),this.cleanupMouse()},cleanupMouse:function(){A.delete(this.POINTER_ID)}},U=W,B=E.captureInfo,Y=_.findTarget.bind(_),X=_.allShadows.bind(_),V=E.pointermap,z=2500,G=200,K="touch-action",$=!1,Z={events:["touchstart","touchmove","touchend","touchcancel"],register:function(e){$?E.listen(e,this.events):q.enableOnSubtree(e)},unregister:function(e){$&&E.unlisten(e,this.events)},elementAdded:function(e){var t=e.getAttribute(K),n=this.touchActionToScrollType(t);n&&(e._scrollType=n,E.listen(e,this.events),X(e).forEach(function(e){e._scrollType=n,E.listen(e,this.events)},this))},elementRemoved:function(e){e._scrollType=void 0,E.unlisten(e,this.events),X(e).forEach(function(e){e._scrollType=void 0,E.unlisten(e,this.events)},this)},elementChanged:function(e,t){var n=e.getAttribute(K),r=this.touchActionToScrollType(n),o=this.touchActionToScrollType(t);r&&o?(e._scrollType=r,X(e).forEach(function(e){e._scrollType=r},this)):o?this.elementRemoved(e):r&&this.elementAdded(e)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(e){var t=e,n=this.scrollTypes;return"none"===t?"none":t===n.XSCROLLER?"X":t===n.YSCROLLER?"Y":n.SCROLLER.exec(t)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(e){return this.firstTouch===e.identifier},setPrimaryTouch:function(e){(0===V.size||1===V.size&&V.has(1))&&(this.firstTouch=e.identifier,this.firstXY={X:e.clientX,Y:e.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(e){e.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var e=function(){this.clickCount=0,this.resetId=null}.bind(this);this.resetId=setTimeout(e,G)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(e){var t=0;return("touchstart"===e||"touchmove"===e)&&(t=1),t},touchToPointer:function(e){var t=this.currentTouchEvent,n=E.cloneEvent(e),r=n.pointerId=e.identifier+2;n.target=B[r]||Y(n),n.bubbles=!0,n.cancelable=!0,n.detail=this.clickCount,n.button=0,n.buttons=this.typeToButtons(t.type),n.width=e.radiusX||e.webkitRadiusX||0,n.height=e.radiusY||e.webkitRadiusY||0,n.pressure=e.force||e.webkitForce||.5,n.isPrimary=this.isPrimaryTouch(e),n.pointerType=this.POINTER_TYPE;var o=this;return n.preventDefault=function(){o.scrolling=!1,o.firstXY=null,t.preventDefault()},n},processTouches:function(e,t){var n=e.changedTouches;this.currentTouchEvent=e;for(var r,o=0;n.length>o;o++)r=n[o],t.call(this,this.touchToPointer(r))},shouldScroll:function(e){if(this.firstXY){var t,n=e.currentTarget._scrollType;if("none"===n)t=!1;else if("XY"===n)t=!0;else{var r=e.changedTouches[0],o=n,i="Y"===n?"X":"Y",a=Math.abs(r["client"+o]-this.firstXY[o]),s=Math.abs(r["client"+i]-this.firstXY[i]);t=a>=s}return this.firstXY=null,t}},findTouch:function(e,t){for(var n,r=0,o=e.length;o>r&&(n=e[r]);r++)if(n.identifier===t)return!0},vacuumTouches:function(e){var t=e.touches;if(V.size>=t.length){var n=[];V.forEach(function(e,r){if(1!==r&&!this.findTouch(t,r-2)){var o=e.out;n.push(o)}},this),n.forEach(this.cancelOut,this)}},touchstart:function(e){this.vacuumTouches(e),this.setPrimaryTouch(e.changedTouches[0]),this.dedupSynthMouse(e),this.scrolling||(this.clickCount++,this.processTouches(e,this.overDown))},overDown:function(e){V.set(e.pointerId,{target:e.target,out:e,outTarget:e.target}),E.over(e),E.enter(e),E.down(e)},touchmove:function(e){this.scrolling||(this.shouldScroll(e)?(this.scrolling=!0,this.touchcancel(e)):(e.preventDefault(),this.processTouches(e,this.moveOverOut)))},moveOverOut:function(e){var t=e,n=V.get(t.pointerId);if(n){var r=n.out,o=n.outTarget;E.move(t),r&&o!==t.target&&(r.relatedTarget=t.target,t.relatedTarget=o,r.target=o,t.target?(E.leaveOut(r),E.enterOver(t)):(t.target=o,t.relatedTarget=null,this.cancelOut(t))),n.out=t,n.outTarget=t.target}},touchend:function(e){this.dedupSynthMouse(e),this.processTouches(e,this.upOut)},upOut:function(e){this.scrolling||(E.up(e),E.out(e),E.leave(e)),this.cleanUpPointer(e)},touchcancel:function(e){this.processTouches(e,this.cancelOut)},cancelOut:function(e){E.cancel(e),E.out(e),E.leave(e),this.cleanUpPointer(e)},cleanUpPointer:function(e){V.delete(e.pointerId),this.removePrimaryPointer(e)},dedupSynthMouse:function(e){var t=U.lastTouches,n=e.changedTouches[0];if(this.isPrimaryTouch(n)){var r={x:n.clientX,y:n.clientY};t.push(r);var o=function(e,t){var n=e.indexOf(t);n>-1&&e.splice(n,1)}.bind(null,t,r);setTimeout(o,z)}}};$||(q=new P(Z.elementAdded,Z.elementRemoved,Z.elementChanged,Z));var J,Q,et=Z,tt=E.pointermap,nt=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,rt={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(e){E.listen(e,this.events)},unregister:function(e){E.unlisten(e,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(e){var t=e;return nt&&(t=E.cloneEvent(e),t.pointerType=this.POINTER_TYPES[e.pointerType]),t},cleanup:function(e){tt.delete(e)},MSPointerDown:function(e){tt.set(e.pointerId,e);var t=this.prepareEvent(e);E.down(t)},MSPointerMove:function(e){var t=this.prepareEvent(e);E.move(t)},MSPointerUp:function(e){var t=this.prepareEvent(e);E.up(t),this.cleanup(e.pointerId)},MSPointerOut:function(e){var t=this.prepareEvent(e);E.leaveOut(t)},MSPointerOver:function(e){var t=this.prepareEvent(e);E.enterOver(t)},MSPointerCancel:function(e){var t=this.prepareEvent(e);E.cancel(t),this.cleanup(e.pointerId)},MSLostPointerCapture:function(e){var t=E.makeEvent("lostpointercapture",e);E.dispatchEvent(t)},MSGotPointerCapture:function(e){var t=E.makeEvent("gotpointercapture",e);E.dispatchEvent(t)}},ot=rt,it=window.navigator;it.msPointerEnabled?(J=function(e){c(e),this.msSetPointerCapture(e)},Q=function(e){c(e),this.msReleasePointerCapture(e)}):(J=function(e){c(e),E.setCapture(e,this)},Q=function(e){c(e),E.releaseCapture(e,this)}),a(),s(),u();var at={dispatcher:E,Installer:P,PointerEvent:p,PointerMap:m,targetFinding:_};return at}),function(){function e(e){var t=A.call(e);return R[t]||(R[t]=t.match(k)[1].toLowerCase())}function t(n,r){var o=t[r||e(n)];return o?o(n):n}function n(t){return H[e(t)]?[t]:Array.prototype.slice.call(t,0)}function r(e,t){return(t||j).length?n(e.querySelectorAll(t)):[]}function o(e){e()}function i(n,r,o){var i=e(o);return"object"==i&&"object"==e(n[r])?B.merge(n[r],o):n[r]=t(o,i),n}function a(e,t,n){var r,o={};for(var i in t)o[i.split(":")[0]]=i;for(i in n)r=o[i.split(":")[0]],"function"==typeof t[r]?(r.match(":mixins")||(t[r+":mixins"]=t[r],delete t[r],r+=":mixins"),t[r].__mixin__=B.applyPseudos(i+(i.match(":mixins")?"":":mixins"),n[i],e.pseudos,t[r].__mixin__)):(t[i]=n[i],delete t[r])}function s(e,t,n){for(var r in n)t[r+":__mixin__("+F++ +")"]=B.applyPseudos(r,n[r],e.pseudos)}function c(e,t){for(var n=e.length;n--;)t.unshift(e[n]),B.mixins[e[n]].mixins&&c(B.mixins[e[n]].mixins,t);return t}function u(e){return c(e.mixins,[]).forEach(function(t){var n=B.mixins[t];for(var r in n){var o=n[r],i=e[r];if(i)switch(r){case"mixins":break;case"events":s(e,i,o);break;case"accessors":case"prototype":for(var c in o)i[c]?a(e,i[c],o[c],t):i[c]=o[c];break;default:a(e,i,o,t)}else e[r]=o}}),e}function l(e,t){for(var n,r=t.target,o=t.currentTarget;!n&&r&&r!=o;)r.tagName&&I.call(r,e.value)&&(n=r),r=r.parentNode;return!n&&o.tagName&&I.call(o,e.value)&&(n=o),n?e.listener=e.listener.bind(n):null}function d(e){return 0===e.button}function p(e,t,n,r){r?t[e]=n[e]:Object.defineProperty(t,e,{writable:!0,enumerable:!0,value:n[e]})}function h(e,t){var n=Object.getOwnPropertyDescriptor(e,"target");for(var r in t)q[r]||p(r,e,t,n);e.baseEvent=t}function f(e,t,n,r,o){E[o].call(e,n,t&&t.boolean?"":r)}function m(e,t,n,r,o){if(t&&(t.property||t.selector))for(var i=t.property?[e.xtag[t.property]]:t.selector?B.query(e,t.selector):[],a=i.length;a--;)i[a][o](n,r)}function v(e,t,n,r,o,i){var a=n.split(":"),s=a[0];"get"==s?(a[0]=t,e.prototype[t].get=B.applyPseudos(a.join(":"),r[n],e.pseudos,r[n])):"set"==s?(a[0]=t,e.prototype[t].set=B.applyPseudos(a.join(":"),o?function(e){var t,a="setAttribute";o.boolean?(e=!!e,t=this.hasAttribute(i),e||(a="removeAttribute")):(e=o.validate?o.validate.call(this,e):e,t=this.getAttribute(i)),f(this,o,i,e,a),r[n].call(this,e,t),m(this,o,i,e,a)}:r[n]?function(e){r[n].call(this,e)}:null,e.pseudos,r[n]),o&&(o.setter=r[n])):e.prototype[t][n]=r[n]}function g(e,t){e.prototype[t]={};var n,r=e.accessors[t],o=r.attribute;o&&(n=o.name=(o?o.name||t.replace(L,"$1-$2"):t).toLowerCase(),o.key=t,e.attributes[n]=o);for(var i in r)v(e,t,i,r,o,n);if(o){if(!e.prototype[t].get){var a=(o.boolean?"has":"get")+"Attribute";e.prototype[t].get=function(){return this[a](n)}}e.prototype[t].set||(e.prototype[t].set=function(e){e=o.boolean?!!e:o.validate?o.validate.call(this,e):e;var t=o.boolean?e?"setAttribute":"removeAttribute":"setAttribute";f(this,o,n,e,t),m(this,o,n,e,t)})}}function w(e){return"function"==typeof e?U.exec(""+e)[1]:e}var y=window,b=document,E={setAttribute:Element.prototype.setAttribute,removeAttribute:Element.prototype.removeAttribute},_=Element.prototype.createShadowRoot,T=b.createElement("div"),S=function(){},M=function(){return!0},C=/,/g,L=/([a-z])([A-Z])/g,N=/\(|\)/g,O=/:(\w+)\u276A(.+?(?=\u276B))|:(\w+)/g,P=/(\d+)/g,D={action:function(e,t){return e.value.match(P).indexOf(t.keyCode+"")>-1==("keypass"==e.name)||null}},x=function(){var e=Object.keys(window).join(),t=(e.match(/,(ms)/)||e.match(/,(moz)/)||e.match(/,(O)/)||[null,"webkit"])[1].toLowerCase();return{dom:"ms"==t?"MS":t,lowercase:t,css:"-"+t+"-",js:"ms"==t?t:t.charAt(0).toUpperCase()+t.substring(1)}}(),I=Element.prototype.matches||Element.prototype.matchesSelector||Element.prototype[x.lowercase+"MatchesSelector"],R={},A=R.toString,k=/\s([a-zA-Z]+)/;t.object=function(e){var n={};for(var r in e)n[r]=t(e[r]);return n},t.array=function(e){for(var n=e.length,r=Array(n);n--;)r[n]=t(e[n]);return r};var H={undefined:1,"null":1,number:1,"boolean":1,string:1,"function":1},j="",F=0,q={};for(var W in b.createEvent("CustomEvent"))q[W]=1;var U=/\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//,B={tags:{},defaultOptions:{pseudos:[],mixins:[],events:{},methods:{},accessors:{},lifecycle:{},attributes:{},prototype:{xtag:{get:function(){return this.__xtag__?this.__xtag__:this.__xtag__={data:{}}}}}},register:function(e,t){var r;if("string"!=typeof e)throw"First argument must be a Custom Element string name";r=e.toLowerCase(),B.tags[r]=t||{};var o=t.prototype;delete t.prototype;var i=B.tags[r].compiled=u(B.merge({},B.defaultOptions,t)),a=i.prototype,s=i.lifecycle;for(var c in i.events)i.events[c]=B.parseEvent(c,i.events[c]);for(c in s)s[c.split(":")[0]]=B.applyPseudos(c,s[c],i.pseudos,s[c]);for(c in i.methods)a[c.split(":")[0]]={value:B.applyPseudos(c,i.methods[c],i.pseudos,i.methods[c]),enumerable:!0};for(c in i.accessors)g(i,c);i.shadow&&(i.shadow=i.shadow.nodeName?i.shadow:B.createFragment(i.shadow)),i.content&&(i.content=i.content.nodeName?i.content.innerHTML:w(i.content));var l=s.created,d=s.finalized;a.createdCallback={enumerable:!0,value:function(){var e=this;i.shadow&&_&&this.createShadowRoot().appendChild(i.shadow.cloneNode(!0)),i.content&&(this.appendChild(document.createElement("div")).outerHTML=i.content);var t=l?l.apply(this,arguments):null;B.addEvents(this,i.events);for(var n in i.attributes){var r=i.attributes[n],o=this.hasAttribute(n),a=void 0!==r.def;(o||r.boolean||a)&&(this[r.key]=r.boolean?o:!o&&a?r.def:this.getAttribute(n))}return i.pseudos.forEach(function(t){t.onAdd.call(e,t)}),this.xtagComponentReady=!0,d&&d.apply(this,arguments),t}};var p=s.inserted,h=s.removed;(p||h)&&(a.attachedCallback={value:function(){return h&&(this.xtag.__parentNode__=this.parentNode),p?p.apply(this,arguments):void 0},enumerable:!0}),h&&(a.detachedCallback={value:function(){var e=n(arguments);e.unshift(this.xtag.__parentNode__);var t=h.apply(this,e);return delete this.xtag.__parentNode__,t},enumerable:!0}),s.attributeChanged&&(a.attributeChangedCallback={value:s.attributeChanged,enumerable:!0}),a.setAttribute={writable:!0,enumerable:!0,value:function(e,t){var n,r=e.toLowerCase(),o=i.attributes[r];o&&(n=this.getAttribute(r),t=o.boolean?"":o.validate?o.validate.call(this,t):t),f(this,o,r,t,"setAttribute"),o&&(o.setter&&o.setter.call(this,o.boolean?!0:t,n),m(this,o,r,t,"setAttribute"))}},a.removeAttribute={writable:!0,enumerable:!0,value:function(e){var t=e.toLowerCase(),n=i.attributes[t],r=this.hasAttribute(t);f(this,n,t,"","removeAttribute"),n&&(n.setter&&n.setter.call(this,n.boolean?!1:void 0,r),m(this,n,t,"","removeAttribute"))}};var v={},E=o instanceof y.HTMLElement,T=i["extends"]&&(v["extends"]=i["extends"]);return o&&Object.getOwnPropertyNames(o).forEach(function(e){var t=a[e],n=E?Object.getOwnPropertyDescriptor(o,e):o[e];if(t)for(var r in n)t[r]="function"==typeof n[r]&&t[r]?B.wrap(n[r],t[r]):n[r];a[e]=t||n}),v.prototype=Object.create(T?Object.create(b.createElement(T).constructor).prototype:y.HTMLElement.prototype,a),b.registerElement(r,v)},mixins:{},prefix:x,captureEvents:{focus:1,blur:1,scroll:1,DOMMouseScroll:1},customEvents:{animationstart:{attach:[x.dom+"AnimationStart"]},animationend:{attach:[x.dom+"AnimationEnd"]},transitionend:{attach:[x.dom+"TransitionEnd"]},move:{attach:["pointermove"]},enter:{attach:["pointerenter"]},leave:{attach:["pointerleave"]},scrollwheel:{attach:["DOMMouseScroll","mousewheel"],condition:function(e){return e.delta=e.wheelDelta?e.wheelDelta/40:Math.round(-1*(e.detail/3.5)),!0}},tap:{attach:["pointerdown","pointerup"],condition:function(e,t){if("pointerdown"==e.type)t.startX=e.clientX,t.startY=e.clientY;else if(0===e.button&&10>Math.abs(t.startX-e.clientX)&&10>Math.abs(t.startY-e.clientY))return!0}},tapstart:{attach:["pointerdown"],condition:d},tapend:{attach:["pointerup"],condition:d},tapmove:{attach:["pointerdown"],condition:function(e,t){if("pointerdown"==e.type){var n=t.listener.bind(this);t.tapmoveListeners||(t.tapmoveListeners=B.addEvents(document,{pointermove:n,pointerup:n,pointercancel:n}))}else("pointerup"==e.type||"pointercancel"==e.type)&&(B.removeEvents(document,t.tapmoveListeners),t.tapmoveListeners=null);return!0}},taphold:{attach:["pointerdown","pointerup"],condition:function(e,t){if("pointerdown"==e.type)(t.pointers=t.pointers||{})[e.pointerId]=setTimeout(B.fireEvent.bind(null,this,"taphold"),t.duration||1e3);else{if("pointerup"!=e.type)return!0;t.pointers&&(clearTimeout(t.pointers[e.pointerId]),delete t.pointers[e.pointerId])}}}},pseudos:{__mixin__:{},mixins:{onCompiled:function(e,t){var n=t.source&&t.source.__mixin__||t.source;if(!n)return e;switch(t.value){case null:case"":case"before":return function(){return n.apply(this,arguments),e.apply(this,arguments)};case"after":return function(){var t=e.apply(this,arguments);return n.apply(this,arguments),t};case"none":return e}}},keypass:D,keyfail:D,delegate:{action:l},preventable:{action:function(e,t){return!t.defaultPrevented}},duration:{onAdd:function(e){e.source.duration=Number(e.value)}},capture:{onCompiled:function(e,t){t.source&&(t.source.capture=!0)}}},clone:t,typeOf:e,toArray:n,wrap:function(e,t){return function(){var n=e.apply(this,arguments);return t.apply(this,arguments),n}},merge:function(t,n,r){if("string"==e(n))return i(t,n,r);for(var o=1,a=arguments.length;a>o;o++){var s=arguments[o];for(var c in s)i(t,c,s[c])}return t},uid:function(){return Math.random().toString(36).substr(2,10)},query:r,skipTransition:function(e,t,n){var r=x.js+"TransitionProperty";e.style[r]=e.style.transitionProperty="none";var o=t?t.call(n||e):null;return B.skipFrame(function(){e.style[r]=e.style.transitionProperty="",o&&o.call(n||e)})},requestFrame:function(){var e=y.requestAnimationFrame||y[x.lowercase+"RequestAnimationFrame"]||function(e){return y.setTimeout(e,20)};return function(t){return e(t)}}(),cancelFrame:function(){var e=y.cancelAnimationFrame||y[x.lowercase+"CancelAnimationFrame"]||y.clearTimeout;return function(t){return e(t)}}(),skipFrame:function(e){var t=B.requestFrame(function(){t=B.requestFrame(e)});return t},matchSelector:function(e,t){return I.call(e,t)},set:function(e,t,n){e[t]=n,window.CustomElements&&CustomElements.upgradeAll(e)},innerHTML:function(e,t){B.set(e,"innerHTML",t)},hasClass:function(e,t){return e.className.split(" ").indexOf(t.trim())>-1},addClass:function(e,t){var n=e.className.trim().split(" ");return t.trim().split(" ").forEach(function(e){~n.indexOf(e)||n.push(e)}),e.className=n.join(" ").trim(),e},removeClass:function(e,t){var n=t.trim().split(" ");return e.className=e.className.trim().split(" ").filter(function(e){return e&&!~n.indexOf(e)}).join(" "),e},toggleClass:function(e,t){return B[B.hasClass(e,t)?"removeClass":"addClass"].call(null,e,t)},queryChildren:function(e,t){var r=e.id,o="#"+(e.id=r||"x_"+B.uid())+" > ",i=e.parentNode||!T.appendChild(e);t=o+(t+"").replace(C,","+o);var a=e.parentNode.querySelectorAll(t);return r||e.removeAttribute("id"),i||T.removeChild(e),n(a)},createFragment:function(e){var t=document.createElement("template");return e&&(e.nodeName?n(arguments).forEach(function(e){t.content.appendChild(e)}):t.innerHTML=w(e)),document.importNode(t.content,!0)},manipulate:function(e,t){var n=e.nextSibling,r=e.parentNode,o=t.call(e)||e;n?r.insertBefore(o,n):r.appendChild(o)},applyPseudos:function(e,t,r,i){var a=t,s={};if(e.match(":")){var c=[],u=0;e.replace(N,function(e){return"("==e?1==++u?"❪":"(":--u?")":"❫"}).replace(O,function(e,t,n,r){c.push([t||r,n])});for(var l=c.length;l--;)o(function(){var o=c[l][0],u=c[l][1];if(!B.pseudos[o])throw"pseudo not found: "+o+" "+u;u=""===u||u===void 0?null:u;var d=s[l]=Object.create(B.pseudos[o]);d.key=e,d.name=o,d.value=u,d.arguments=(u||"").split(","),d.action=d.action||M,d.source=i,d.onAdd=d.onAdd||S,d.onRemove=d.onRemove||S;var p=d.listener=a;a=function(){var e=d.action.apply(this,[d].concat(n(arguments)));return null===e||e===!1?e:(e=d.listener.apply(this,arguments),d.listener=p,e)},r?r.push(d):d.onAdd.call(t,d)})}for(var d in s)s[d].onCompiled&&(a=s[d].onCompiled(a,s[d])||a);return a},removePseudos:function(e,t){t.forEach(function(t){t.onRemove.call(e,t)})},parseEvent:function(e,t){var r=e.split(":"),o=r.shift(),i=B.customEvents[o],a=B.merge({type:o,stack:S,condition:M,capture:B.captureEvents[o],attach:[],_attach:[],pseudos:"",_pseudos:[],onAdd:S,onRemove:S},i||{});a.attach=n(a.base||a.attach),a.chain=o+(a.pseudos.length?":"+a.pseudos:"")+(r.length?":"+r.join(":"):"");var s=B.applyPseudos(a.chain,t,a._pseudos,a);return a.stack=function(e){e.currentTarget=e.currentTarget||this;var t=e.detail||{};return t.__stack__?t.__stack__==s?(e.stopPropagation(),e.cancelBubble=!0,s.apply(this,arguments)):void 0:s.apply(this,arguments)},a.listener=function(e){var t=n(arguments),r=a.condition.apply(this,t.concat([a]));return r?e.type!=o&&e.baseEvent&&e.type!=e.baseEvent.type?(B.fireEvent(e.target,o,{baseEvent:e,detail:r!==!0&&(r.__stack__=s)?r:{__stack__:s}}),void 0):a.stack.apply(this,t):r},a.attach.forEach(function(e){a._attach.push(B.parseEvent(e,a.listener))}),a},addEvent:function(e,t,n,r){var o="function"==typeof n?B.parseEvent(t,n):n;return o._pseudos.forEach(function(t){t.onAdd.call(e,t)}),o._attach.forEach(function(t){B.addEvent(e,t.type,t)}),o.onAdd.call(e,o,o.listener),e.addEventListener(o.type,o.stack,r||o.capture),o},addEvents:function(e,t){var n={};for(var r in t)n[r]=B.addEvent(e,r,t[r]);return n},removeEvent:function(e,t,n){n=n||t,n.onRemove.call(e,n,n.listener),B.removePseudos(e,n._pseudos),n._attach.forEach(function(t){B.removeEvent(e,t)}),e.removeEventListener(n.type,n.stack)},removeEvents:function(e,t){for(var n in t)B.removeEvent(e,t[n])},fireEvent:function(e,t,n){var r=b.createEvent("CustomEvent");n=n||{},r.initCustomEvent(t,n.bubbles!==!1,n.cancelable!==!1,n.detail),n.baseEvent&&h(r,n.baseEvent),e.dispatchEvent(r)}};"function"==typeof define&&define.amd?define(B):"undefined"!=typeof module&&module.exports?module.exports=B:y.xtag=B,b.addEventListener("WebComponentsReady",function(){B.fireEvent(b.body,"DOMComponentsLoaded")})}(); \ No newline at end of file diff --git a/dist/x-tag-core.js b/dist/x-tag-core.js deleted file mode 100644 index 74ba7d1..0000000 --- a/dist/x-tag-core.js +++ /dev/null @@ -1,4810 +0,0 @@ -// DOMTokenList polyfill for IE9 -(function () { - -if (typeof window.Element === "undefined" || "classList" in document.documentElement) return; - -var prototype = Array.prototype, - indexOf = prototype.indexOf, - slice = prototype.slice, - push = prototype.push, - splice = prototype.splice, - join = prototype.join; - -function DOMTokenList(el) { - this._element = el; - if (el.className != this._classCache) { - this._classCache = el.className; - - if (!this._classCache) return; - - // The className needs to be trimmed and split on whitespace - // to retrieve a list of classes. - var classes = this._classCache.replace(/^\s+|\s+$/g,'').split(/\s+/), - i; - for (i = 0; i < classes.length; i++) { - push.call(this, classes[i]); - } - } -}; - -function setToClassName(el, classes) { - el.className = classes.join(' '); -} - -DOMTokenList.prototype = { - add: function(token) { - if(this.contains(token)) return; - push.call(this, token); - setToClassName(this._element, slice.call(this, 0)); - }, - contains: function(token) { - return indexOf.call(this, token) !== -1; - }, - item: function(index) { - return this[index] || null; - }, - remove: function(token) { - var i = indexOf.call(this, token); - if (i === -1) { - return; - } - splice.call(this, i, 1); - setToClassName(this._element, slice.call(this, 0)); - }, - toString: function() { - return join.call(this, ' '); - }, - toggle: function(token) { - if (indexOf.call(this, token) === -1) { - this.add(token); - } else { - this.remove(token); - } - } -}; - -window.DOMTokenList = DOMTokenList; - -function defineElementGetter (obj, prop, getter) { - if (Object.defineProperty) { - Object.defineProperty(obj, prop,{ - get : getter - }) - } else { - obj.__defineGetter__(prop, getter); - } -} - -defineElementGetter(Element.prototype, 'classList', function () { - return new DOMTokenList(this); -}); - -})(); - - -/** - * @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.20 -(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 && " " != 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 (" " == 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 (" " == 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 (" " != 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 (" " == 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 (" " != c && "\n" != c && "\r" != c) { - buffer += percentEscape(c); - } - break; - - case "query": - if (!stateOverride && "#" == c) { - this._fragment = "#"; - state = "fragment"; - } else if (EOF != c && " " != c && "\n" != c && "\r" != c) { - this._query += percentEscapeQuery(c); - } - break; - - case "fragment": - if (EOF != c && " " != 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); - -if (typeof HTMLTemplateElement === "undefined") { - (function() { - var TEMPLATE_TAG = "template"; - var contentDoc = document.implementation.createHTMLDocument("template"); - var canDecorate = true; - HTMLTemplateElement = function() {}; - HTMLTemplateElement.prototype = Object.create(HTMLElement.prototype); - HTMLTemplateElement.decorate = function(template) { - if (template.content) { - return; - } - template.content = contentDoc.createDocumentFragment(); - var child; - while (child = template.firstChild) { - template.content.appendChild(child); - } - 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; - HTMLTemplateElement.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; - } - } - HTMLTemplateElement.bootstrap(template.content); - }; - HTMLTemplateElement.bootstrap = function(doc) { - var templates = doc.querySelectorAll(TEMPLATE_TAG); - for (var i = 0, l = templates.length, t; i < l && (t = templates[i]); i++) { - HTMLTemplateElement.decorate(t); - } - }; - document.addEventListener("DOMContentLoaded", function() { - HTMLTemplateElement.bootstrap(document); - }); - var createElement = document.createElement; - document.createElement = function() { - "use strict"; - var el = createElement.apply(document, arguments); - if (el.localName == "template") { - HTMLTemplateElement.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); - } - })(); -} - -(function(scope) { - "use strict"; - if (!window.performance) { - 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.HTMLImports.__importsParsingHook) { - window.HTMLImports.__importsParsingHook(elt); - } - if (elt.import) { - elt.import.__importParsed = true; - } - this.markParsingComplete(elt); - if (elt.__resource && !elt.__error) { - elt.dispatchEvent(new CustomEvent("load", { - bubbles: false - })); - } else { - elt.dispatchEvent(new CustomEvent("error", { - bubbles: false - })); - } - if (elt.__pending) { - var fn; - while (elt.__pending.length) { - fn = elt.__pending.shift(); - if (fn) { - fn({ - target: elt - }); - } - } - } - this.parseNext(); - }, - parseLink: function(linkElt) { - if (nodeIsImport(linkElt)) { - this.parseImport(linkElt); - } else { - linkElt.href = linkElt.href; - this.parseGeneric(linkElt); - } - }, - parseStyle: function(elt) { - var src = elt; - elt = cloneStyle(elt); - src.__appliedElement = elt; - elt.__importElement = src; - this.parseGeneric(elt); - }, - parseGeneric: function(elt) { - this.trackElement(elt); - this.addElementToDocument(elt); - }, - rootImportForElement: function(elt) { - var n = elt; - while (n.ownerDocument.__importLink) { - n = n.ownerDocument.__importLink; - } - return n; - }, - addElementToDocument: function(elt) { - var port = this.rootImportForElement(elt.__importElement || elt); - port.parentNode.insertBefore(elt, port); - }, - trackElement: function(elt, callback) { - var self = this; - var done = function(e) { - elt.removeEventListener("load", done); - elt.removeEventListener("error", done); - if (callback) { - callback(e); - } - self.markParsingComplete(elt); - self.parseNext(); - }; - elt.addEventListener("load", done); - elt.addEventListener("error", done); - if (isIE && elt.localName === "style") { - var fakeLoad = false; - if (elt.textContent.indexOf("@import") == -1) { - fakeLoad = true; - } else if (elt.sheet) { - fakeLoad = true; - var csr = elt.sheet.cssRules; - var len = csr ? csr.length : 0; - for (var i = 0, r; i < len && (r = csr[i]); i++) { - if (r.type === CSSRule.IMPORT_RULE) { - fakeLoad = fakeLoad && Boolean(r.styleSheet); - } - } - } - if (fakeLoad) { - setTimeout(function() { - elt.dispatchEvent(new CustomEvent("load", { - bubbles: false - })); - }); - } - } - }, - parseScript: function(scriptElt) { - var script = document.createElement("script"); - script.__importElement = scriptElt; - script.src = scriptElt.src ? scriptElt.src : generateScriptDataUrl(scriptElt); - scope.currentScript = scriptElt; - this.trackElement(script, function(e) { - if (script.parentNode) { - script.parentNode.removeChild(script); - } - scope.currentScript = null; - }); - this.addElementToDocument(script); - }, - nextToParse: function() { - this._mayParse = []; - return !this.parsingElement && (this.nextToParseInDoc(rootDocument) || this.nextToParseDynamic()); - }, - nextToParseInDoc: function(doc, link) { - if (doc && this._mayParse.indexOf(doc) < 0) { - this._mayParse.push(doc); - var nodes = doc.querySelectorAll(this.parseSelectorsForNode(doc)); - for (var i = 0, l = nodes.length, p = 0, n; i < l && (n = nodes[i]); i++) { - if (!this.isParsed(n)) { - if (this.hasResource(n)) { - return nodeIsImport(n) ? this.nextToParseInDoc(n.__doc, n) : n; - } else { - return; - } - } - } - } - return link; - }, - nextToParseDynamic: function() { - return this.dynamicElements[0]; - }, - parseSelectorsForNode: function(node) { - var doc = node.ownerDocument || node; - return doc === rootDocument ? this.documentSelectors : this.importsSelectors; - }, - isParsed: function(node) { - return node.__importParsed; - }, - needsDynamicParsing: function(elt) { - return this.dynamicElements.indexOf(elt) >= 0; - }, - hasResource: function(node) { - if (nodeIsImport(node) && node.__doc === undefined) { - return false; - } - return true; - } - }; - function nodeIsImport(elt) { - return elt.localName === "link" && elt.rel === IMPORT_LINK_TYPE; - } - function generateScriptDataUrl(script) { - var scriptContent = generateScriptContent(script); - return "data:text/javascript;charset=utf-8," + encodeURIComponent(scriptContent); - } - function generateScriptContent(script) { - return script.textContent + generateSourceMapHint(script); - } - function generateSourceMapHint(script) { - var owner = script.ownerDocument; - owner.__importedScripts = owner.__importedScripts || 0; - var moniker = script.ownerDocument.baseURI; - var num = owner.__importedScripts ? "-" + owner.__importedScripts : ""; - owner.__importedScripts++; - return "\n//# sourceURL=" + moniker + num + ".js\n"; - } - function cloneStyle(style) { - var clone = style.ownerDocument.createElement("style"); - clone.textContent = style.textContent; - path.resolveUrlsInStyle(clone); - return clone; - } - scope.parser = importParser; - scope.IMPORT_SELECTOR = IMPORT_SELECTOR; -}); - -window.HTMLImports.addModule(function(scope) { - var flags = scope.flags; - var IMPORT_LINK_TYPE = scope.IMPORT_LINK_TYPE; - var IMPORT_SELECTOR = scope.IMPORT_SELECTOR; - var rootDocument = scope.rootDocument; - var Loader = scope.Loader; - var Observer = scope.Observer; - var parser = scope.parser; - var importer = { - documents: {}, - documentPreloadSelectors: IMPORT_SELECTOR, - importsPreloadSelectors: [ IMPORT_SELECTOR ].join(","), - loadNode: function(node) { - importLoader.addNode(node); - }, - loadSubtree: function(parent) { - var nodes = this.marshalNodes(parent); - importLoader.addNodes(nodes); - }, - marshalNodes: function(parent) { - return parent.querySelectorAll(this.loadSelectorsForNode(parent)); - }, - loadSelectorsForNode: function(node) { - var doc = node.ownerDocument || node; - return doc === rootDocument ? this.documentPreloadSelectors : this.importsPreloadSelectors; - }, - loaded: function(url, elt, resource, err, redirectedUrl) { - flags.load && console.log("loaded", url, elt); - elt.__resource = resource; - elt.__error = err; - if (isImportLink(elt)) { - var doc = this.documents[url]; - if (doc === undefined) { - doc = err ? null : makeDocument(resource, redirectedUrl || url); - if (doc) { - doc.__importLink = elt; - this.bootDocument(doc); - } - this.documents[url] = doc; - } - elt.__doc = doc; - } - parser.parseNext(); - }, - bootDocument: function(doc) { - this.loadSubtree(doc); - this.observer.observe(doc); - parser.parseNext(); - }, - loadedAll: function() { - parser.parseNext(); - } - }; - var importLoader = new Loader(importer.loaded.bind(importer), importer.loadedAll.bind(importer)); - importer.observer = new Observer(); - function isImportLink(elt) { - return isLinkRel(elt, IMPORT_LINK_TYPE); - } - function isLinkRel(elt, rel) { - return elt.localName === "link" && elt.getAttribute("rel") === rel; - } - function hasBaseURIAccessor(doc) { - return !!Object.getOwnPropertyDescriptor(doc, "baseURI"); - } - function makeDocument(resource, url) { - var doc = document.implementation.createHTMLDocument(IMPORT_LINK_TYPE); - doc._URL = url; - var base = doc.createElement("base"); - base.setAttribute("href", url); - if (!doc.baseURI && !hasBaseURIAccessor(doc)) { - Object.defineProperty(doc, "baseURI", { - value: url - }); - } - var meta = doc.createElement("meta"); - meta.setAttribute("charset", "utf-8"); - doc.head.appendChild(meta); - doc.head.appendChild(base); - doc.body.innerHTML = resource; - if (window.HTMLTemplateElement && HTMLTemplateElement.bootstrap) { - HTMLTemplateElement.bootstrap(doc); - } - return doc; - } - if (!document.baseURI) { - var baseURIDescriptor = { - get: function() { - var base = document.querySelector("base"); - return base ? base.href : window.location.href; - }, - configurable: true - }; - Object.defineProperty(document, "baseURI", baseURIDescriptor); - Object.defineProperty(rootDocument, "baseURI", baseURIDescriptor); - } - scope.importer = importer; - scope.importLoader = importLoader; -}); - -window.HTMLImports.addModule(function(scope) { - var parser = scope.parser; - var importer = scope.importer; - var dynamic = { - added: function(nodes) { - var owner, parsed, loading; - for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) { - if (!owner) { - owner = n.ownerDocument; - parsed = parser.isParsed(owner); - } - loading = this.shouldLoadNode(n); - if (loading) { - importer.loadNode(n); - } - if (this.shouldParseNode(n) && parsed) { - parser.parseDynamic(n, loading); - } - } - }, - shouldLoadNode: function(node) { - return node.nodeType === 1 && matches.call(node, importer.loadSelectorsForNode(node)); - }, - shouldParseNode: function(node) { - return node.nodeType === 1 && matches.call(node, parser.parseSelectorsForNode(node)); - } - }; - importer.observer.addCallback = dynamic.added.bind(dynamic); - var matches = HTMLElement.prototype.matches || HTMLElement.prototype.matchesSelector || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector || HTMLElement.prototype.msMatchesSelector; -}); - -(function(scope) { - var initializeModules = scope.initializeModules; - var isIE = scope.isIE; - if (scope.useNative) { - return; - } - initializeModules(); - var rootDocument = scope.rootDocument; - function bootstrap() { - window.HTMLImports.importer.bootDocument(rootDocument); - } - if (document.readyState === "complete" || document.readyState === "interactive" && !window.attachEvent) { - bootstrap(); - } else { - document.addEventListener("DOMContentLoaded", bootstrap); - } -})(window.HTMLImports); - -window.CustomElements = window.CustomElements || { - flags: {} -}; - -(function(scope) { - var flags = scope.flags; - var modules = []; - var addModule = function(module) { - modules.push(module); - }; - var initializeModules = function() { - modules.forEach(function(module) { - module(scope); - }); - }; - scope.addModule = addModule; - scope.initializeModules = initializeModules; - scope.hasNative = Boolean(document.registerElement); - scope.isIE = /Trident/.test(navigator.userAgent); - scope.useNative = !flags.register && scope.hasNative && !window.ShadowDOMPolyfill && (!window.HTMLImports || window.HTMLImports.useNative); -})(window.CustomElements); - -window.CustomElements.addModule(function(scope) { - var IMPORT_LINK_TYPE = window.HTMLImports ? window.HTMLImports.IMPORT_LINK_TYPE : "none"; - function forSubtree(node, cb) { - findAllElements(node, function(e) { - if (cb(e)) { - return true; - } - forRoots(e, cb); - }); - forRoots(node, cb); - } - function findAllElements(node, find, data) { - var e = node.firstElementChild; - if (!e) { - e = node.firstChild; - while (e && e.nodeType !== Node.ELEMENT_NODE) { - e = e.nextSibling; - } - } - while (e) { - if (find(e, data) !== true) { - findAllElements(e, find, data); - } - e = e.nextElementSibling; - } - return null; - } - function forRoots(node, cb) { - var root = node.shadowRoot; - while (root) { - forSubtree(root, cb); - root = root.olderShadowRoot; - } - } - function forDocumentTree(doc, cb) { - _forDocumentTree(doc, cb, []); - } - function _forDocumentTree(doc, cb, processingDocuments) { - doc = window.wrap(doc); - if (processingDocuments.indexOf(doc) >= 0) { - return; - } - processingDocuments.push(doc); - var imports = doc.querySelectorAll("link[rel=" + IMPORT_LINK_TYPE + "]"); - for (var i = 0, l = imports.length, n; i < l && (n = imports[i]); i++) { - if (n.import) { - _forDocumentTree(n.import, cb, processingDocuments); - } - } - cb(doc); - } - scope.forDocumentTree = forDocumentTree; - scope.forSubtree = forSubtree; -}); - -window.CustomElements.addModule(function(scope) { - var flags = scope.flags; - var forSubtree = scope.forSubtree; - var forDocumentTree = scope.forDocumentTree; - function addedNode(node, isAttached) { - return added(node, isAttached) || addedSubtree(node, isAttached); - } - function added(node, isAttached) { - if (scope.upgrade(node, isAttached)) { - return true; - } - if (isAttached) { - attached(node); - } - } - function addedSubtree(node, isAttached) { - forSubtree(node, function(e) { - if (added(e, isAttached)) { - return true; - } - }); - } - var hasThrottledAttached = window.MutationObserver._isPolyfilled && flags["throttle-attached"]; - scope.hasPolyfillMutations = hasThrottledAttached; - scope.hasThrottledAttached = hasThrottledAttached; - var isPendingMutations = false; - var pendingMutations = []; - function deferMutation(fn) { - pendingMutations.push(fn); - if (!isPendingMutations) { - isPendingMutations = true; - setTimeout(takeMutations); - } - } - function takeMutations() { - isPendingMutations = false; - var $p = pendingMutations; - for (var i = 0, l = $p.length, p; i < l && (p = $p[i]); i++) { - p(); - } - pendingMutations = []; - } - function attached(element) { - if (hasThrottledAttached) { - deferMutation(function() { - _attached(element); - }); - } else { - _attached(element); - } - } - function _attached(element) { - if (element.__upgraded__ && !element.__attached) { - element.__attached = true; - if (element.attachedCallback) { - element.attachedCallback(); - } - } - } - function detachedNode(node) { - detached(node); - forSubtree(node, function(e) { - detached(e); - }); - } - function detached(element) { - if (hasThrottledAttached) { - deferMutation(function() { - _detached(element); - }); - } else { - _detached(element); - } - } - function _detached(element) { - if (element.__upgraded__ && element.__attached) { - element.__attached = false; - if (element.detachedCallback) { - element.detachedCallback(); - } - } - } - function inDocument(element) { - var p = element; - var doc = window.wrap(document); - while (p) { - if (p == doc) { - return true; - } - p = p.parentNode || p.nodeType === Node.DOCUMENT_FRAGMENT_NODE && p.host; - } - } - function watchShadow(node) { - if (node.shadowRoot && !node.shadowRoot.__watched) { - flags.dom && console.log("watching shadow-root for: ", node.localName); - var root = node.shadowRoot; - while (root) { - observe(root); - root = root.olderShadowRoot; - } - } - } - function handler(root, mutations) { - if (flags.dom) { - var mx = mutations[0]; - if (mx && mx.type === "childList" && mx.addedNodes) { - if (mx.addedNodes) { - var d = mx.addedNodes[0]; - while (d && d !== document && !d.host) { - d = d.parentNode; - } - var u = d && (d.URL || d._URL || d.host && d.host.localName) || ""; - u = u.split("/?").shift().split("/").pop(); - } - } - console.group("mutations (%d) [%s]", mutations.length, u || ""); - } - var isAttached = inDocument(root); - mutations.forEach(function(mx) { - if (mx.type === "childList") { - forEach(mx.addedNodes, function(n) { - if (!n.localName) { - return; - } - addedNode(n, isAttached); - }); - forEach(mx.removedNodes, function(n) { - if (!n.localName) { - return; - } - detachedNode(n); - }); - } - }); - flags.dom && console.groupEnd(); - } - function takeRecords(node) { - node = window.wrap(node); - if (!node) { - node = window.wrap(document); - } - while (node.parentNode) { - node = node.parentNode; - } - var observer = node.__observer; - if (observer) { - handler(node, observer.takeRecords()); - takeMutations(); - } - } - var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); - function observe(inRoot) { - if (inRoot.__observer) { - return; - } - var observer = new MutationObserver(handler.bind(this, inRoot)); - observer.observe(inRoot, { - childList: true, - subtree: true - }); - inRoot.__observer = observer; - } - function upgradeDocument(doc) { - doc = window.wrap(doc); - flags.dom && console.group("upgradeDocument: ", doc.baseURI.split("/").pop()); - var isMainDocument = doc === window.wrap(document); - addedNode(doc, isMainDocument); - observe(doc); - flags.dom && console.groupEnd(); - } - function upgradeDocumentTree(doc) { - forDocumentTree(doc, upgradeDocument); - } - var originalCreateShadowRoot = Element.prototype.createShadowRoot; - if (originalCreateShadowRoot) { - Element.prototype.createShadowRoot = function() { - var root = originalCreateShadowRoot.call(this); - window.CustomElements.watchShadow(this); - return root; - }; - } - scope.watchShadow = watchShadow; - scope.upgradeDocumentTree = upgradeDocumentTree; - scope.upgradeDocument = upgradeDocument; - scope.upgradeSubtree = addedSubtree; - scope.upgradeAll = addedNode; - scope.attached = attached; - scope.takeRecords = takeRecords; -}); - -window.CustomElements.addModule(function(scope) { - var flags = scope.flags; - function upgrade(node, isAttached) { - if (node.localName === "template") { - if (window.HTMLTemplateElement && HTMLTemplateElement.decorate) { - HTMLTemplateElement.decorate(node); - } - } - if (!node.__upgraded__ && node.nodeType === Node.ELEMENT_NODE) { - var is = node.getAttribute("is"); - var definition = scope.getRegisteredDefinition(node.localName) || scope.getRegisteredDefinition(is); - if (definition) { - if (is && definition.tag == node.localName || !is && !definition.extends) { - return upgradeWithDefinition(node, definition, isAttached); - } - } - } - } - function upgradeWithDefinition(element, definition, isAttached) { - flags.upgrade && console.group("upgrade:", element.localName); - if (definition.is) { - element.setAttribute("is", definition.is); - } - implementPrototype(element, definition); - element.__upgraded__ = true; - created(element); - if (isAttached) { - scope.attached(element); - } - scope.upgradeSubtree(element, isAttached); - flags.upgrade && console.groupEnd(); - return element; - } - function implementPrototype(element, definition) { - if (Object.__proto__) { - element.__proto__ = definition.prototype; - } else { - customMixin(element, definition.prototype, definition.native); - element.__proto__ = definition.prototype; - } - } - function customMixin(inTarget, inSrc, inNative) { - var used = {}; - var p = inSrc; - while (p !== inNative && p !== HTMLElement.prototype) { - var keys = Object.getOwnPropertyNames(p); - for (var i = 0, k; k = keys[i]; i++) { - if (!used[k]) { - Object.defineProperty(inTarget, k, Object.getOwnPropertyDescriptor(p, k)); - used[k] = 1; - } - } - p = Object.getPrototypeOf(p); - } - } - function created(element) { - if (element.createdCallback) { - element.createdCallback(); - } - } - scope.upgrade = upgrade; - scope.upgradeWithDefinition = upgradeWithDefinition; - scope.implementPrototype = implementPrototype; -}); - -window.CustomElements.addModule(function(scope) { - var isIE = scope.isIE; - var upgradeDocumentTree = scope.upgradeDocumentTree; - var upgradeAll = scope.upgradeAll; - var upgradeWithDefinition = scope.upgradeWithDefinition; - var implementPrototype = scope.implementPrototype; - var useNative = scope.useNative; - function register(name, options) { - var definition = options || {}; - if (!name) { - throw new Error("document.registerElement: first argument `name` must not be empty"); - } - if (name.indexOf("-") < 0) { - throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '" + String(name) + "'."); - } - if (isReservedTag(name)) { - throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '" + String(name) + "'. The type name is invalid."); - } - if (getRegisteredDefinition(name)) { - throw new Error("DuplicateDefinitionError: a type with name '" + String(name) + "' is already registered"); - } - if (!definition.prototype) { - definition.prototype = Object.create(HTMLElement.prototype); - } - definition.__name = name.toLowerCase(); - definition.lifecycle = definition.lifecycle || {}; - definition.ancestry = ancestry(definition.extends); - resolveTagName(definition); - resolvePrototypeChain(definition); - overrideAttributeApi(definition.prototype); - registerDefinition(definition.__name, definition); - definition.ctor = generateConstructor(definition); - definition.ctor.prototype = definition.prototype; - definition.prototype.constructor = definition.ctor; - if (scope.ready) { - upgradeDocumentTree(document); - } - return definition.ctor; - } - function overrideAttributeApi(prototype) { - if (prototype.setAttribute._polyfilled) { - return; - } - var setAttribute = prototype.setAttribute; - prototype.setAttribute = function(name, value) { - changeAttribute.call(this, name, value, setAttribute); - }; - var removeAttribute = prototype.removeAttribute; - prototype.removeAttribute = function(name) { - changeAttribute.call(this, name, null, removeAttribute); - }; - prototype.setAttribute._polyfilled = true; - } - function changeAttribute(name, value, operation) { - name = name.toLowerCase(); - var oldValue = this.getAttribute(name); - operation.apply(this, arguments); - var newValue = this.getAttribute(name); - if (this.attributeChangedCallback && newValue !== oldValue) { - this.attributeChangedCallback(name, oldValue, newValue); - } - } - function isReservedTag(name) { - for (var i = 0; i < reservedTagList.length; i++) { - if (name === reservedTagList[i]) { - return true; - } - } - } - var reservedTagList = [ "annotation-xml", "color-profile", "font-face", "font-face-src", "font-face-uri", "font-face-format", "font-face-name", "missing-glyph" ]; - function ancestry(extnds) { - var extendee = getRegisteredDefinition(extnds); - if (extendee) { - return ancestry(extendee.extends).concat([ extendee ]); - } - return []; - } - function resolveTagName(definition) { - var baseTag = definition.extends; - for (var i = 0, a; a = definition.ancestry[i]; i++) { - baseTag = a.is && a.tag; - } - definition.tag = baseTag || definition.__name; - if (baseTag) { - definition.is = definition.__name; - } - } - function resolvePrototypeChain(definition) { - if (!Object.__proto__) { - var nativePrototype = HTMLElement.prototype; - if (definition.is) { - var inst = document.createElement(definition.tag); - nativePrototype = Object.getPrototypeOf(inst); - } - var proto = definition.prototype, ancestor; - var foundPrototype = false; - while (proto) { - if (proto == nativePrototype) { - foundPrototype = true; - } - ancestor = Object.getPrototypeOf(proto); - if (ancestor) { - proto.__proto__ = ancestor; - } - proto = ancestor; - } - if (!foundPrototype) { - console.warn(definition.tag + " prototype not found in prototype chain for " + definition.is); - } - definition.native = nativePrototype; - } - } - function instantiate(definition) { - return upgradeWithDefinition(domCreateElement(definition.tag), definition); - } - var registry = {}; - function getRegisteredDefinition(name) { - if (name) { - return registry[name.toLowerCase()]; - } - } - function registerDefinition(name, definition) { - registry[name] = definition; - } - function generateConstructor(definition) { - return function() { - return instantiate(definition); - }; - } - var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; - function createElementNS(namespace, tag, typeExtension) { - if (namespace === HTML_NAMESPACE) { - return createElement(tag, typeExtension); - } else { - return domCreateElementNS(namespace, tag); - } - } - function createElement(tag, typeExtension) { - if (tag) { - tag = tag.toLowerCase(); - } - if (typeExtension) { - typeExtension = typeExtension.toLowerCase(); - } - var definition = getRegisteredDefinition(typeExtension || tag); - if (definition) { - if (tag == definition.tag && typeExtension == definition.is) { - return new definition.ctor(); - } - if (!typeExtension && !definition.is) { - return new definition.ctor(); - } - } - var element; - if (typeExtension) { - element = createElement(tag); - element.setAttribute("is", typeExtension); - return element; - } - element = domCreateElement(tag); - if (tag.indexOf("-") >= 0) { - implementPrototype(element, HTMLElement); - } - return element; - } - var domCreateElement = document.createElement.bind(document); - var domCreateElementNS = document.createElementNS.bind(document); - var isInstance; - if (!Object.__proto__ && !useNative) { - isInstance = function(obj, ctor) { - if (obj instanceof ctor) { - return true; - } - var p = obj; - while (p) { - if (p === ctor.prototype) { - return true; - } - p = p.__proto__; - } - return false; - }; - } else { - isInstance = function(obj, base) { - return obj instanceof base; - }; - } - function wrapDomMethodToForceUpgrade(obj, methodName) { - var orig = obj[methodName]; - obj[methodName] = function() { - var n = orig.apply(this, arguments); - upgradeAll(n); - return n; - }; - } - wrapDomMethodToForceUpgrade(Node.prototype, "cloneNode"); - wrapDomMethodToForceUpgrade(document, "importNode"); - if (isIE) { - (function() { - var importNode = document.importNode; - document.importNode = function() { - var n = importNode.apply(document, arguments); - if (n.nodeType == n.DOCUMENT_FRAGMENT_NODE) { - var f = document.createDocumentFragment(); - f.appendChild(n); - return f; - } else { - return n; - } - }; - })(); - } - document.registerElement = register; - document.createElement = createElement; - document.createElementNS = createElementNS; - scope.registry = registry; - scope.instanceof = isInstance; - scope.reservedTagList = reservedTagList; - scope.getRegisteredDefinition = getRegisteredDefinition; - document.register = document.registerElement; -}); - -(function(scope) { - var useNative = scope.useNative; - var initializeModules = scope.initializeModules; - var isIE = scope.isIE; - if (useNative) { - var nop = function() {}; - scope.watchShadow = nop; - scope.upgrade = nop; - scope.upgradeAll = nop; - scope.upgradeDocumentTree = nop; - scope.upgradeSubtree = nop; - scope.takeRecords = nop; - scope.instanceof = function(obj, base) { - return obj instanceof base; - }; - } else { - initializeModules(); - } - var upgradeDocumentTree = scope.upgradeDocumentTree; - var upgradeDocument = scope.upgradeDocument; - if (!window.wrap) { - if (window.ShadowDOMPolyfill) { - window.wrap = window.ShadowDOMPolyfill.wrapIfNeeded; - window.unwrap = window.ShadowDOMPolyfill.unwrapIfNeeded; - } else { - window.wrap = window.unwrap = function(node) { - return node; - }; - } - } - if (window.HTMLImports) { - window.HTMLImports.__importsParsingHook = function(elt) { - if (elt.import) { - upgradeDocument(wrap(elt.import)); - } - }; - } - function bootstrap() { - upgradeDocumentTree(window.wrap(document)); - window.CustomElements.ready = true; - var requestAnimationFrame = window.requestAnimationFrame || function(f) { - setTimeout(f, 16); - }; - requestAnimationFrame(function() { - setTimeout(function() { - window.CustomElements.readyTime = Date.now(); - if (window.HTMLImports) { - window.CustomElements.elapsed = window.CustomElements.readyTime - window.HTMLImports.readyTime; - } - document.dispatchEvent(new CustomEvent("WebComponentsReady", { - bubbles: true - })); - }); - }); - } - if (document.readyState === "complete" || scope.flags.eager) { - bootstrap(); - } else if (document.readyState === "interactive" && !window.attachEvent && (!window.HTMLImports || window.HTMLImports.ready)) { - bootstrap(); - } else { - var loadEvent = window.HTMLImports && !window.HTMLImports.ready ? "HTMLImportsLoaded" : "DOMContentLoaded"; - window.addEventListener(loadEvent, bootstrap); - } -})(window.CustomElements); - -(function(scope) { - var style = document.createElement("style"); - style.textContent = "" + "body {" + "transition: opacity ease-in 0.2s;" + " } \n" + "body[unresolved] {" + "opacity: 0; display: block; overflow: hidden; position: relative;" + " } \n"; - var head = document.querySelector("head"); - head.insertBefore(style, head.firstChild); -})(window.WebComponents); -/*! - * PEP v0.4.1 | https://github.com/jquery/PEP - * Copyright jQuery Foundation and other contributors | http://jquery.org/license - */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - global.PointerEventsPolyfill = factory() -}(this, function () { 'use strict'; - - /** - * This is the constructor for new PointerEvents. - * - * New Pointer Events must be given a type, and an optional dictionary of - * initialization properties. - * - * Due to certain platform requirements, events returned from the constructor - * identify as MouseEvents. - * - * @constructor - * @param {String} inType The type of the event to create. - * @param {Object} [inDict] An optional dictionary of initial event properties. - * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`. - */ - var MOUSE_PROPS = [ - 'bubbles', - 'cancelable', - 'view', - 'detail', - 'screenX', - 'screenY', - 'clientX', - 'clientY', - 'ctrlKey', - 'altKey', - 'shiftKey', - 'metaKey', - 'button', - 'relatedTarget', - 'pageX', - 'pageY' - ]; - - var MOUSE_DEFAULTS = [ - false, - false, - null, - null, - 0, - 0, - 0, - 0, - false, - false, - false, - false, - 0, - null, - 0, - 0 - ]; - - function PointerEvent(inType, inDict) { - inDict = inDict || Object.create(null); - - var e = document.createEvent('Event'); - e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false); - - // define inherited MouseEvent properties - // skip bubbles and cancelable since they're set above in initEvent() - for (var i = 2, p; i < MOUSE_PROPS.length; i++) { - p = MOUSE_PROPS[i]; - e[p] = inDict[p] || MOUSE_DEFAULTS[i]; - } - e.buttons = inDict.buttons || 0; - - // Spec requires that pointers without pressure specified use 0.5 for down - // state and 0 for up state. - var pressure = 0; - if (inDict.pressure) { - pressure = inDict.pressure; - } else { - pressure = e.buttons ? 0.5 : 0; - } - - // add x/y properties aliased to clientX/Y - e.x = e.clientX; - e.y = e.clientY; - - // define the properties of the PointerEvent interface - e.pointerId = inDict.pointerId || 0; - e.width = inDict.width || 0; - e.height = inDict.height || 0; - e.pressure = pressure; - e.tiltX = inDict.tiltX || 0; - e.tiltY = inDict.tiltY || 0; - e.pointerType = inDict.pointerType || ''; - e.hwTimestamp = inDict.hwTimestamp || 0; - e.isPrimary = inDict.isPrimary || false; - return e; - } - - var _PointerEvent = PointerEvent; - - /** - * This module implements a map of pointer states - */ - var USE_MAP = window.Map && window.Map.prototype.forEach; - var PointerMap = USE_MAP ? Map : SparseArrayMap; - - function SparseArrayMap() { - this.array = []; - this.size = 0; - } - - SparseArrayMap.prototype = { - set: function(k, v) { - if (v === undefined) { - return this.delete(k); - } - if (!this.has(k)) { - this.size++; - } - this.array[k] = v; - }, - has: function(k) { - return this.array[k] !== undefined; - }, - delete: function(k) { - if (this.has(k)) { - delete this.array[k]; - this.size--; - } - }, - get: function(k) { - return this.array[k]; - }, - clear: function() { - this.array.length = 0; - this.size = 0; - }, - - // return value, key, map - forEach: function(callback, thisArg) { - return this.array.forEach(function(v, k) { - callback.call(thisArg, v, k, this); - }, this); - } - }; - - var _pointermap = PointerMap; - - var CLONE_PROPS = [ - - // MouseEvent - 'bubbles', - 'cancelable', - 'view', - 'detail', - 'screenX', - 'screenY', - 'clientX', - 'clientY', - 'ctrlKey', - 'altKey', - 'shiftKey', - 'metaKey', - 'button', - 'relatedTarget', - - // DOM Level 3 - 'buttons', - - // PointerEvent - 'pointerId', - 'width', - 'height', - 'pressure', - 'tiltX', - 'tiltY', - 'pointerType', - 'hwTimestamp', - 'isPrimary', - - // event instance - 'type', - 'target', - 'currentTarget', - 'which', - 'pageX', - 'pageY', - 'timeStamp' - ]; - - var CLONE_DEFAULTS = [ - - // MouseEvent - false, - false, - null, - null, - 0, - 0, - 0, - 0, - false, - false, - false, - false, - 0, - null, - - // DOM Level 3 - 0, - - // PointerEvent - 0, - 0, - 0, - 0, - 0, - 0, - '', - 0, - false, - - // event instance - '', - null, - null, - 0, - 0, - 0, - 0 - ]; - - var BOUNDARY_EVENTS = { - 'pointerover': 1, - 'pointerout': 1, - 'pointerenter': 1, - 'pointerleave': 1 - }; - - var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined'); - - /** - * This module is for normalizing events. Mouse and Touch events will be - * collected here, and fire PointerEvents that have the same semantics, no - * matter the source. - * Events fired: - * - pointerdown: a pointing is added - * - pointerup: a pointer is removed - * - pointermove: a pointer is moved - * - pointerover: a pointer crosses into an element - * - pointerout: a pointer leaves an element - * - pointercancel: a pointer will no longer generate events - */ - var dispatcher = { - pointermap: new _pointermap(), - eventMap: Object.create(null), - captureInfo: Object.create(null), - - // Scope objects for native events. - // This exists for ease of testing. - eventSources: Object.create(null), - eventSourceList: [], - /** - * Add a new event source that will generate pointer events. - * - * `inSource` must contain an array of event names named `events`, and - * functions with the names specified in the `events` array. - * @param {string} name A name for the event source - * @param {Object} source A new source of platform events. - */ - registerSource: function(name, source) { - var s = source; - var newEvents = s.events; - if (newEvents) { - newEvents.forEach(function(e) { - if (s[e]) { - this.eventMap[e] = s[e].bind(s); - } - }, this); - this.eventSources[name] = s; - this.eventSourceList.push(s); - } - }, - register: function(element) { - var l = this.eventSourceList.length; - for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) { - - // call eventsource register - es.register.call(es, element); - } - }, - unregister: function(element) { - var l = this.eventSourceList.length; - for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) { - - // call eventsource register - es.unregister.call(es, element); - } - }, - contains: /*scope.external.contains || */function(container, contained) { - try { - return container.contains(contained); - } catch (ex) { - - // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427 - return false; - } - }, - - // EVENTS - down: function(inEvent) { - inEvent.bubbles = true; - this.fireEvent('pointerdown', inEvent); - }, - move: function(inEvent) { - inEvent.bubbles = true; - this.fireEvent('pointermove', inEvent); - }, - up: function(inEvent) { - inEvent.bubbles = true; - this.fireEvent('pointerup', inEvent); - }, - enter: function(inEvent) { - inEvent.bubbles = false; - this.fireEvent('pointerenter', inEvent); - }, - leave: function(inEvent) { - inEvent.bubbles = false; - this.fireEvent('pointerleave', inEvent); - }, - over: function(inEvent) { - inEvent.bubbles = true; - this.fireEvent('pointerover', inEvent); - }, - out: function(inEvent) { - inEvent.bubbles = true; - this.fireEvent('pointerout', inEvent); - }, - cancel: function(inEvent) { - inEvent.bubbles = true; - this.fireEvent('pointercancel', inEvent); - }, - leaveOut: function(event) { - this.out(event); - if (!this.contains(event.target, event.relatedTarget)) { - this.leave(event); - } - }, - enterOver: function(event) { - this.over(event); - if (!this.contains(event.target, event.relatedTarget)) { - this.enter(event); - } - }, - - // LISTENER LOGIC - eventHandler: function(inEvent) { - - // This is used to prevent multiple dispatch of pointerevents from - // platform events. This can happen when two elements in different scopes - // are set up to create pointer events, which is relevant to Shadow DOM. - if (inEvent._handledByPE) { - return; - } - var type = inEvent.type; - var fn = this.eventMap && this.eventMap[type]; - if (fn) { - fn(inEvent); - } - inEvent._handledByPE = true; - }, - - // set up event listeners - listen: function(target, events) { - events.forEach(function(e) { - this.addEvent(target, e); - }, this); - }, - - // remove event listeners - unlisten: function(target, events) { - events.forEach(function(e) { - this.removeEvent(target, e); - }, this); - }, - addEvent: /*scope.external.addEvent || */function(target, eventName) { - target.addEventListener(eventName, this.boundHandler); - }, - removeEvent: /*scope.external.removeEvent || */function(target, eventName) { - target.removeEventListener(eventName, this.boundHandler); - }, - - // EVENT CREATION AND TRACKING - /** - * Creates a new Event of type `inType`, based on the information in - * `inEvent`. - * - * @param {string} inType A string representing the type of event to create - * @param {Event} inEvent A platform event with a target - * @return {Event} A PointerEvent of type `inType` - */ - makeEvent: function(inType, inEvent) { - - // relatedTarget must be null if pointer is captured - if (this.captureInfo[inEvent.pointerId]) { - inEvent.relatedTarget = null; - } - var e = new _PointerEvent(inType, inEvent); - if (inEvent.preventDefault) { - e.preventDefault = inEvent.preventDefault; - } - e._target = e._target || inEvent.target; - return e; - }, - - // make and dispatch an event in one call - fireEvent: function(inType, inEvent) { - var e = this.makeEvent(inType, inEvent); - return this.dispatchEvent(e); - }, - /** - * Returns a snapshot of inEvent, with writable properties. - * - * @param {Event} inEvent An event that contains properties to copy. - * @return {Object} An object containing shallow copies of `inEvent`'s - * properties. - */ - cloneEvent: function(inEvent) { - var eventCopy = Object.create(null); - var p; - for (var i = 0; i < CLONE_PROPS.length; i++) { - p = CLONE_PROPS[i]; - eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i]; - - // Work around SVGInstanceElement shadow tree - // Return the element that is represented by the instance for Safari, Chrome, IE. - // This is the behavior implemented by Firefox. - if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) { - if (eventCopy[p] instanceof SVGElementInstance) { - eventCopy[p] = eventCopy[p].correspondingUseElement; - } - } - } - - // keep the semantics of preventDefault - if (inEvent.preventDefault) { - eventCopy.preventDefault = function() { - inEvent.preventDefault(); - }; - } - return eventCopy; - }, - getTarget: function(inEvent) { - var capture = this.captureInfo[inEvent.pointerId]; - if (!capture) { - return inEvent._target; - } - if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) { - return capture; - } - }, - setCapture: function(inPointerId, inTarget) { - if (this.captureInfo[inPointerId]) { - this.releaseCapture(inPointerId); - } - this.captureInfo[inPointerId] = inTarget; - var e = document.createEvent('Event'); - e.initEvent('gotpointercapture', true, false); - e.pointerId = inPointerId; - this.implicitRelease = this.releaseCapture.bind(this, inPointerId); - document.addEventListener('pointerup', this.implicitRelease); - document.addEventListener('pointercancel', this.implicitRelease); - e._target = inTarget; - this.asyncDispatchEvent(e); - }, - releaseCapture: function(inPointerId) { - var t = this.captureInfo[inPointerId]; - if (t) { - var e = document.createEvent('Event'); - e.initEvent('lostpointercapture', true, false); - e.pointerId = inPointerId; - this.captureInfo[inPointerId] = undefined; - document.removeEventListener('pointerup', this.implicitRelease); - document.removeEventListener('pointercancel', this.implicitRelease); - e._target = t; - this.asyncDispatchEvent(e); - } - }, - /** - * Dispatches the event to its target. - * - * @param {Event} inEvent The event to be dispatched. - * @return {Boolean} True if an event handler returns true, false otherwise. - */ - dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) { - var t = this.getTarget(inEvent); - if (t) { - return t.dispatchEvent(inEvent); - } - }, - asyncDispatchEvent: function(inEvent) { - requestAnimationFrame(this.dispatchEvent.bind(this, inEvent)); - } - }; - dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher); - - var _dispatcher = dispatcher; - - var targeting = { - shadow: function(inEl) { - if (inEl) { - return inEl.shadowRoot || inEl.webkitShadowRoot; - } - }, - canTarget: function(shadow) { - return shadow && Boolean(shadow.elementFromPoint); - }, - targetingShadow: function(inEl) { - var s = this.shadow(inEl); - if (this.canTarget(s)) { - return s; - } - }, - olderShadow: function(shadow) { - var os = shadow.olderShadowRoot; - if (!os) { - var se = shadow.querySelector('shadow'); - if (se) { - os = se.olderShadowRoot; - } - } - return os; - }, - allShadows: function(element) { - var shadows = []; - var s = this.shadow(element); - while (s) { - shadows.push(s); - s = this.olderShadow(s); - } - return shadows; - }, - searchRoot: function(inRoot, x, y) { - if (inRoot) { - var t = inRoot.elementFromPoint(x, y); - var st, sr; - - // is element a shadow host? - sr = this.targetingShadow(t); - while (sr) { - - // find the the element inside the shadow root - st = sr.elementFromPoint(x, y); - if (!st) { - - // check for older shadows - sr = this.olderShadow(sr); - } else { - - // shadowed element may contain a shadow root - var ssr = this.targetingShadow(st); - return this.searchRoot(ssr, x, y) || st; - } - } - - // light dom element is the target - return t; - } - }, - owner: function(element) { - var s = element; - - // walk up until you hit the shadow root or document - while (s.parentNode) { - s = s.parentNode; - } - - // the owner element is expected to be a Document or ShadowRoot - if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) { - s = document; - } - return s; - }, - findTarget: function(inEvent) { - var x = inEvent.clientX; - var y = inEvent.clientY; - - // if the listener is in the shadow root, it is much faster to start there - var s = this.owner(inEvent.target); - - // if x, y is not in this root, fall back to document search - if (!s.elementFromPoint(x, y)) { - s = document; - } - return this.searchRoot(s, x, y); - } - }; - - /** - * This module uses Mutation Observers to dynamically adjust which nodes will - * generate Pointer Events. - * - * All nodes that wish to generate Pointer Events must have the attribute - * `touch-action` set to `none`. - */ - var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); - var map = Array.prototype.map.call.bind(Array.prototype.map); - var toArray = Array.prototype.slice.call.bind(Array.prototype.slice); - var filter = Array.prototype.filter.call.bind(Array.prototype.filter); - var MO = window.MutationObserver || window.WebKitMutationObserver; - var SELECTOR = '[touch-action]'; - var OBSERVER_INIT = { - subtree: true, - childList: true, - attributes: true, - attributeOldValue: true, - attributeFilter: ['touch-action'] - }; - - function Installer(add, remove, changed, binder) { - this.addCallback = add.bind(binder); - this.removeCallback = remove.bind(binder); - this.changedCallback = changed.bind(binder); - if (MO) { - this.observer = new MO(this.mutationWatcher.bind(this)); - } - } - - Installer.prototype = { - watchSubtree: function(target) { - - // Only watch scopes that can target find, as these are top-level. - // Otherwise we can see duplicate additions and removals that add noise. - // - // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see - // a removal without an insertion when a node is redistributed among - // shadows. Since it all ends up correct in the document, watching only - // the document will yield the correct mutations to watch. - if (this.observer && targeting.canTarget(target)) { - this.observer.observe(target, OBSERVER_INIT); - } - }, - enableOnSubtree: function(target) { - this.watchSubtree(target); - if (target === document && document.readyState !== 'complete') { - this.installOnLoad(); - } else { - this.installNewSubtree(target); - } - }, - installNewSubtree: function(target) { - forEach(this.findElements(target), this.addElement, this); - }, - findElements: function(target) { - if (target.querySelectorAll) { - return target.querySelectorAll(SELECTOR); - } - return []; - }, - removeElement: function(el) { - this.removeCallback(el); - }, - addElement: function(el) { - this.addCallback(el); - }, - elementChanged: function(el, oldValue) { - this.changedCallback(el, oldValue); - }, - concatLists: function(accum, list) { - return accum.concat(toArray(list)); - }, - - // register all touch-action = none nodes on document load - installOnLoad: function() { - document.addEventListener('readystatechange', function() { - if (document.readyState === 'complete') { - this.installNewSubtree(document); - } - }.bind(this)); - }, - isElement: function(n) { - return n.nodeType === Node.ELEMENT_NODE; - }, - flattenMutationTree: function(inNodes) { - - // find children with touch-action - var tree = map(inNodes, this.findElements, this); - - // make sure the added nodes are accounted for - tree.push(filter(inNodes, this.isElement)); - - // flatten the list - return tree.reduce(this.concatLists, []); - }, - mutationWatcher: function(mutations) { - mutations.forEach(this.mutationHandler, this); - }, - mutationHandler: function(m) { - if (m.type === 'childList') { - var added = this.flattenMutationTree(m.addedNodes); - added.forEach(this.addElement, this); - var removed = this.flattenMutationTree(m.removedNodes); - removed.forEach(this.removeElement, this); - } else if (m.type === 'attributes') { - this.elementChanged(m.target, m.oldValue); - } - } - }; - - var installer = Installer; - - function shadowSelector(v) { - return 'body /shadow-deep/ ' + selector(v); - } - function selector(v) { - return '[touch-action="' + v + '"]'; - } - function rule(v) { - return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; touch-action-delay: none; }'; - } - var attrib2css = [ - 'none', - 'auto', - 'pan-x', - 'pan-y', - { - rule: 'pan-x pan-y', - selectors: [ - 'pan-x pan-y', - 'pan-y pan-x' - ] - } - ]; - var styles = ''; - - // only install stylesheet if the browser has touch action support - var hasNativePE = window.PointerEvent || window.MSPointerEvent; - - // only add shadow selectors if shadowdom is supported - var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot; - - function applyAttributeStyles() { - if (hasNativePE) { - attrib2css.forEach(function(r) { - if (String(r) === r) { - styles += selector(r) + rule(r) + '\n'; - if (hasShadowRoot) { - styles += shadowSelector(r) + rule(r) + '\n'; - } - } else { - styles += r.selectors.map(selector) + rule(r.rule) + '\n'; - if (hasShadowRoot) { - styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n'; - } - } - }); - - var el = document.createElement('style'); - el.textContent = styles; - document.head.appendChild(el); - } - } - - var mouse__pointermap = _dispatcher.pointermap; - - // radius around touchend that swallows mouse events - var DEDUP_DIST = 25; - - // left, middle, right, back, forward - var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16]; - - var HAS_BUTTONS = false; - try { - HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1; - } catch (e) {} - - // handler block for native mouse events - var mouseEvents = { - POINTER_ID: 1, - POINTER_TYPE: 'mouse', - events: [ - 'mousedown', - 'mousemove', - 'mouseup', - 'mouseover', - 'mouseout' - ], - register: function(target) { - _dispatcher.listen(target, this.events); - }, - unregister: function(target) { - _dispatcher.unlisten(target, this.events); - }, - lastTouches: [], - - // collide with the global mouse listener - isEventSimulatedFromTouch: function(inEvent) { - var lts = this.lastTouches; - var x = inEvent.clientX; - var y = inEvent.clientY; - for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) { - - // simulated mouse events will be swallowed near a primary touchend - var dx = Math.abs(x - t.x); - var dy = Math.abs(y - t.y); - if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) { - return true; - } - } - }, - prepareEvent: function(inEvent) { - var e = _dispatcher.cloneEvent(inEvent); - - // forward mouse preventDefault - var pd = e.preventDefault; - e.preventDefault = function() { - inEvent.preventDefault(); - pd(); - }; - e.pointerId = this.POINTER_ID; - e.isPrimary = true; - e.pointerType = this.POINTER_TYPE; - return e; - }, - prepareButtonsForMove: function(e, inEvent) { - var p = mouse__pointermap.get(this.POINTER_ID); - e.buttons = p ? p.buttons : 0; - inEvent.buttons = e.buttons; - }, - mousedown: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var p = mouse__pointermap.get(this.POINTER_ID); - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { - e.buttons = BUTTON_TO_BUTTONS[e.button]; - if (p) { e.buttons |= p.buttons; } - inEvent.buttons = e.buttons; - } - mouse__pointermap.set(this.POINTER_ID, inEvent); - if (!p) { - _dispatcher.down(e); - } else { - _dispatcher.move(e); - } - } - }, - mousemove: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); } - _dispatcher.move(e); - } - }, - mouseup: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var p = mouse__pointermap.get(this.POINTER_ID); - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { - var up = BUTTON_TO_BUTTONS[e.button]; - - // Produces wrong state of buttons in Browsers without `buttons` support - // when a mouse button that was pressed outside the document is released - // inside and other buttons are still pressed down. - e.buttons = p ? p.buttons & ~up : 0; - inEvent.buttons = e.buttons; - } - mouse__pointermap.set(this.POINTER_ID, inEvent); - - // Support: Firefox <=44 only - // FF Ubuntu includes the lifted button in the `buttons` property on - // mouseup. - // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366 - if (e.buttons === 0 || e.buttons === BUTTON_TO_BUTTONS[e.button]) { - this.cleanupMouse(); - _dispatcher.up(e); - } else { - _dispatcher.move(e); - } - } - }, - mouseover: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); } - _dispatcher.enterOver(e); - } - }, - mouseout: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); } - _dispatcher.leaveOut(e); - } - }, - cancel: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.cancel(e); - this.cleanupMouse(); - }, - cleanupMouse: function() { - mouse__pointermap.delete(this.POINTER_ID); - } - }; - - var mouse = mouseEvents; - - var captureInfo = _dispatcher.captureInfo; - var findTarget = targeting.findTarget.bind(targeting); - var allShadows = targeting.allShadows.bind(targeting); - var touch__pointermap = _dispatcher.pointermap; - - // This should be long enough to ignore compat mouse events made by touch - var DEDUP_TIMEOUT = 2500; - var CLICK_COUNT_TIMEOUT = 200; - var ATTRIB = 'touch-action'; - var INSTALLER; - - // The presence of touch event handlers blocks scrolling, and so we must be careful to - // avoid adding handlers unnecessarily. Chrome plans to add a touch-action-delay property - // (crbug.com/329559) to address this, and once we have that we can opt-in to a simpler - // handler registration mechanism. Rather than try to predict how exactly to opt-in to - // that we'll just leave this disabled until there is a build of Chrome to test. - var HAS_TOUCH_ACTION_DELAY = false; - - // handler block for native touch events - var touchEvents = { - events: [ - 'touchstart', - 'touchmove', - 'touchend', - 'touchcancel' - ], - register: function(target) { - if (HAS_TOUCH_ACTION_DELAY) { - _dispatcher.listen(target, this.events); - } else { - INSTALLER.enableOnSubtree(target); - } - }, - unregister: function(target) { - if (HAS_TOUCH_ACTION_DELAY) { - _dispatcher.unlisten(target, this.events); - } else { - - // TODO(dfreedman): is it worth it to disconnect the MO? - } - }, - elementAdded: function(el) { - var a = el.getAttribute(ATTRIB); - var st = this.touchActionToScrollType(a); - if (st) { - el._scrollType = st; - _dispatcher.listen(el, this.events); - - // set touch-action on shadows as well - allShadows(el).forEach(function(s) { - s._scrollType = st; - _dispatcher.listen(s, this.events); - }, this); - } - }, - elementRemoved: function(el) { - el._scrollType = undefined; - _dispatcher.unlisten(el, this.events); - - // remove touch-action from shadow - allShadows(el).forEach(function(s) { - s._scrollType = undefined; - _dispatcher.unlisten(s, this.events); - }, this); - }, - elementChanged: function(el, oldValue) { - var a = el.getAttribute(ATTRIB); - var st = this.touchActionToScrollType(a); - var oldSt = this.touchActionToScrollType(oldValue); - - // simply update scrollType if listeners are already established - if (st && oldSt) { - el._scrollType = st; - allShadows(el).forEach(function(s) { - s._scrollType = st; - }, this); - } else if (oldSt) { - this.elementRemoved(el); - } else if (st) { - this.elementAdded(el); - } - }, - scrollTypes: { - EMITTER: 'none', - XSCROLLER: 'pan-x', - YSCROLLER: 'pan-y', - SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/ - }, - touchActionToScrollType: function(touchAction) { - var t = touchAction; - var st = this.scrollTypes; - if (t === 'none') { - return 'none'; - } else if (t === st.XSCROLLER) { - return 'X'; - } else if (t === st.YSCROLLER) { - return 'Y'; - } else if (st.SCROLLER.exec(t)) { - return 'XY'; - } - }, - POINTER_TYPE: 'touch', - firstTouch: null, - isPrimaryTouch: function(inTouch) { - return this.firstTouch === inTouch.identifier; - }, - setPrimaryTouch: function(inTouch) { - - // set primary touch if there no pointers, or the only pointer is the mouse - if (touch__pointermap.size === 0 || (touch__pointermap.size === 1 && touch__pointermap.has(1))) { - this.firstTouch = inTouch.identifier; - this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY }; - this.scrolling = false; - this.cancelResetClickCount(); - } - }, - removePrimaryPointer: function(inPointer) { - if (inPointer.isPrimary) { - this.firstTouch = null; - this.firstXY = null; - this.resetClickCount(); - } - }, - clickCount: 0, - resetId: null, - resetClickCount: function() { - var fn = function() { - this.clickCount = 0; - this.resetId = null; - }.bind(this); - this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT); - }, - cancelResetClickCount: function() { - if (this.resetId) { - clearTimeout(this.resetId); - } - }, - typeToButtons: function(type) { - var ret = 0; - if (type === 'touchstart' || type === 'touchmove') { - ret = 1; - } - return ret; - }, - touchToPointer: function(inTouch) { - var cte = this.currentTouchEvent; - var e = _dispatcher.cloneEvent(inTouch); - - // We reserve pointerId 1 for Mouse. - // Touch identifiers can start at 0. - // Add 2 to the touch identifier for compatibility. - var id = e.pointerId = inTouch.identifier + 2; - e.target = captureInfo[id] || findTarget(e); - e.bubbles = true; - e.cancelable = true; - e.detail = this.clickCount; - e.button = 0; - e.buttons = this.typeToButtons(cte.type); - e.width = inTouch.radiusX || inTouch.webkitRadiusX || 0; - e.height = inTouch.radiusY || inTouch.webkitRadiusY || 0; - e.pressure = inTouch.force || inTouch.webkitForce || 0.5; - e.isPrimary = this.isPrimaryTouch(inTouch); - e.pointerType = this.POINTER_TYPE; - - // forward touch preventDefaults - var self = this; - e.preventDefault = function() { - self.scrolling = false; - self.firstXY = null; - cte.preventDefault(); - }; - return e; - }, - processTouches: function(inEvent, inFunction) { - var tl = inEvent.changedTouches; - this.currentTouchEvent = inEvent; - for (var i = 0, t; i < tl.length; i++) { - t = tl[i]; - inFunction.call(this, this.touchToPointer(t)); - } - }, - - // For single axis scrollers, determines whether the element should emit - // pointer events or behave as a scroller - shouldScroll: function(inEvent) { - if (this.firstXY) { - var ret; - var scrollAxis = inEvent.currentTarget._scrollType; - if (scrollAxis === 'none') { - - // this element is a touch-action: none, should never scroll - ret = false; - } else if (scrollAxis === 'XY') { - - // this element should always scroll - ret = true; - } else { - var t = inEvent.changedTouches[0]; - - // check the intended scroll axis, and other axis - var a = scrollAxis; - var oa = scrollAxis === 'Y' ? 'X' : 'Y'; - var da = Math.abs(t['client' + a] - this.firstXY[a]); - var doa = Math.abs(t['client' + oa] - this.firstXY[oa]); - - // if delta in the scroll axis > delta other axis, scroll instead of - // making events - ret = da >= doa; - } - this.firstXY = null; - return ret; - } - }, - findTouch: function(inTL, inId) { - for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) { - if (t.identifier === inId) { - return true; - } - } - }, - - // In some instances, a touchstart can happen without a touchend. This - // leaves the pointermap in a broken state. - // Therefore, on every touchstart, we remove the touches that did not fire a - // touchend event. - // To keep state globally consistent, we fire a - // pointercancel for this "abandoned" touch - vacuumTouches: function(inEvent) { - var tl = inEvent.touches; - - // pointermap.size should be < tl.length here, as the touchstart has not - // been processed yet. - if (touch__pointermap.size >= tl.length) { - var d = []; - touch__pointermap.forEach(function(value, key) { - - // Never remove pointerId == 1, which is mouse. - // Touch identifiers are 2 smaller than their pointerId, which is the - // index in pointermap. - if (key !== 1 && !this.findTouch(tl, key - 2)) { - var p = value.out; - d.push(p); - } - }, this); - d.forEach(this.cancelOut, this); - } - }, - touchstart: function(inEvent) { - this.vacuumTouches(inEvent); - this.setPrimaryTouch(inEvent.changedTouches[0]); - this.dedupSynthMouse(inEvent); - if (!this.scrolling) { - this.clickCount++; - this.processTouches(inEvent, this.overDown); - } - }, - overDown: function(inPointer) { - touch__pointermap.set(inPointer.pointerId, { - target: inPointer.target, - out: inPointer, - outTarget: inPointer.target - }); - _dispatcher.over(inPointer); - _dispatcher.enter(inPointer); - _dispatcher.down(inPointer); - }, - touchmove: function(inEvent) { - if (!this.scrolling) { - if (this.shouldScroll(inEvent)) { - this.scrolling = true; - this.touchcancel(inEvent); - } else { - inEvent.preventDefault(); - this.processTouches(inEvent, this.moveOverOut); - } - } - }, - moveOverOut: function(inPointer) { - var event = inPointer; - var pointer = touch__pointermap.get(event.pointerId); - - // a finger drifted off the screen, ignore it - if (!pointer) { - return; - } - var outEvent = pointer.out; - var outTarget = pointer.outTarget; - _dispatcher.move(event); - if (outEvent && outTarget !== event.target) { - outEvent.relatedTarget = event.target; - event.relatedTarget = outTarget; - - // recover from retargeting by shadow - outEvent.target = outTarget; - if (event.target) { - _dispatcher.leaveOut(outEvent); - _dispatcher.enterOver(event); - } else { - - // clean up case when finger leaves the screen - event.target = outTarget; - event.relatedTarget = null; - this.cancelOut(event); - } - } - pointer.out = event; - pointer.outTarget = event.target; - }, - touchend: function(inEvent) { - this.dedupSynthMouse(inEvent); - this.processTouches(inEvent, this.upOut); - }, - upOut: function(inPointer) { - if (!this.scrolling) { - _dispatcher.up(inPointer); - _dispatcher.out(inPointer); - _dispatcher.leave(inPointer); - } - this.cleanUpPointer(inPointer); - }, - touchcancel: function(inEvent) { - this.processTouches(inEvent, this.cancelOut); - }, - cancelOut: function(inPointer) { - _dispatcher.cancel(inPointer); - _dispatcher.out(inPointer); - _dispatcher.leave(inPointer); - this.cleanUpPointer(inPointer); - }, - cleanUpPointer: function(inPointer) { - touch__pointermap.delete(inPointer.pointerId); - this.removePrimaryPointer(inPointer); - }, - - // prevent synth mouse events from creating pointer events - dedupSynthMouse: function(inEvent) { - var lts = mouse.lastTouches; - var t = inEvent.changedTouches[0]; - - // only the primary finger will synth mouse events - if (this.isPrimaryTouch(t)) { - - // remember x/y of last touch - var lt = { x: t.clientX, y: t.clientY }; - lts.push(lt); - var fn = (function(lts, lt) { - var i = lts.indexOf(lt); - if (i > -1) { - lts.splice(i, 1); - } - }).bind(null, lts, lt); - setTimeout(fn, DEDUP_TIMEOUT); - } - } - }; - - if (!HAS_TOUCH_ACTION_DELAY) { - INSTALLER = new installer(touchEvents.elementAdded, touchEvents.elementRemoved, - touchEvents.elementChanged, touchEvents); - } - - var touch = touchEvents; - - var ms__pointermap = _dispatcher.pointermap; - var HAS_BITMAP_TYPE = window.MSPointerEvent && - typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number'; - var msEvents = { - events: [ - 'MSPointerDown', - 'MSPointerMove', - 'MSPointerUp', - 'MSPointerOut', - 'MSPointerOver', - 'MSPointerCancel', - 'MSGotPointerCapture', - 'MSLostPointerCapture' - ], - register: function(target) { - _dispatcher.listen(target, this.events); - }, - unregister: function(target) { - _dispatcher.unlisten(target, this.events); - }, - POINTER_TYPES: [ - '', - 'unavailable', - 'touch', - 'pen', - 'mouse' - ], - prepareEvent: function(inEvent) { - var e = inEvent; - if (HAS_BITMAP_TYPE) { - e = _dispatcher.cloneEvent(inEvent); - e.pointerType = this.POINTER_TYPES[inEvent.pointerType]; - } - return e; - }, - cleanup: function(id) { - ms__pointermap.delete(id); - }, - MSPointerDown: function(inEvent) { - ms__pointermap.set(inEvent.pointerId, inEvent); - var e = this.prepareEvent(inEvent); - _dispatcher.down(e); - }, - MSPointerMove: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.move(e); - }, - MSPointerUp: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.up(e); - this.cleanup(inEvent.pointerId); - }, - MSPointerOut: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.leaveOut(e); - }, - MSPointerOver: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.enterOver(e); - }, - MSPointerCancel: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.cancel(e); - this.cleanup(inEvent.pointerId); - }, - MSLostPointerCapture: function(inEvent) { - var e = _dispatcher.makeEvent('lostpointercapture', inEvent); - _dispatcher.dispatchEvent(e); - }, - MSGotPointerCapture: function(inEvent) { - var e = _dispatcher.makeEvent('gotpointercapture', inEvent); - _dispatcher.dispatchEvent(e); - } - }; - - var ms = msEvents; - - function platform_events__applyPolyfill() { - - // only activate if this platform does not have pointer events - if (!window.PointerEvent) { - window.PointerEvent = _PointerEvent; - - if (window.navigator.msPointerEnabled) { - var tp = window.navigator.msMaxTouchPoints; - Object.defineProperty(window.navigator, 'maxTouchPoints', { - value: tp, - enumerable: true - }); - _dispatcher.registerSource('ms', ms); - } else { - _dispatcher.registerSource('mouse', mouse); - if (window.ontouchstart !== undefined) { - _dispatcher.registerSource('touch', touch); - } - } - - _dispatcher.register(document); - } - } - - var n = window.navigator; - var s, r; - function assertDown(id) { - if (!_dispatcher.pointermap.has(id)) { - throw new Error('InvalidPointerId'); - } - } - if (n.msPointerEnabled) { - s = function(pointerId) { - assertDown(pointerId); - this.msSetPointerCapture(pointerId); - }; - r = function(pointerId) { - assertDown(pointerId); - this.msReleasePointerCapture(pointerId); - }; - } else { - s = function setPointerCapture(pointerId) { - assertDown(pointerId); - _dispatcher.setCapture(pointerId, this); - }; - r = function releasePointerCapture(pointerId) { - assertDown(pointerId); - _dispatcher.releaseCapture(pointerId, this); - }; - } - - function _capture__applyPolyfill() { - if (window.Element && !Element.prototype.setPointerCapture) { - Object.defineProperties(Element.prototype, { - 'setPointerCapture': { - value: s - }, - 'releasePointerCapture': { - value: r - } - }); - } - } - - applyAttributeStyles(); - platform_events__applyPolyfill(); - _capture__applyPolyfill(); - - var pointerevents = { - dispatcher: _dispatcher, - Installer: installer, - PointerEvent: _PointerEvent, - PointerMap: _pointermap, - targetFinding: targeting - }; - - return pointerevents; - -})); - -(function () { - -/*** Variables ***/ - - var win = window, - doc = document, - attrProto = { - setAttribute: Element.prototype.setAttribute, - removeAttribute: Element.prototype.removeAttribute - }, - hasShadow = Element.prototype.createShadowRoot, - container = doc.createElement('div'), - noop = function(){}, - trueop = function(){ return true; }, - regexReplaceCommas = /,/g, - regexCamelToDash = /([a-z])([A-Z])/g, - regexPseudoParens = /\(|\)/g, - regexPseudoCapture = /:(\w+)\u276A(.+?(?=\u276B))|:(\w+)/g, - regexDigits = /(\d+)/g, - keypseudo = { - action: function (pseudo, event) { - return pseudo.value.match(regexDigits).indexOf(String(event.keyCode)) > -1 == (pseudo.name == 'keypass') || null; - } - }, - /* - - The prefix object generated here is added to the xtag object as xtag.prefix later in the code - - Prefix provides a variety of prefix variations for the browser in which your code is running - - The 4 variations of prefix are as follows: - * prefix.dom: the correct prefix case and form when used on DOM elements/style properties - * prefix.lowercase: a lowercase version of the prefix for use in various user-code situations - * prefix.css: the lowercase, dashed version of the prefix - * prefix.js: addresses prefixed APIs present in global and non-Element contexts - */ - prefix = (function () { - var keys = Object.keys(window).join(); - var pre = ((keys.match(/,(ms)/) || keys.match(/,(moz)/) || keys.match(/,(O)/)) || [null, 'webkit'])[1].toLowerCase(); - return { - dom: pre == 'ms' ? 'MS' : pre, - lowercase: pre, - css: '-' + pre + '-', - js: pre == 'ms' ? pre : pre.charAt(0).toUpperCase() + pre.substring(1) - }; - })(), - matchSelector = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype[prefix.lowercase + 'MatchesSelector']; - -/*** Functions ***/ - -// Utilities - - /* - This is an enhanced typeof check for all types of objects. Where typeof would normaly return - 'object' for many common DOM objects (like NodeLists and HTMLCollections). - - For example: typeOf(document.children) will correctly return 'htmlcollection' - */ - var typeCache = {}, - typeString = typeCache.toString, - typeRegexp = /\s([a-zA-Z]+)/; - function typeOf(obj) { - var type = typeString.call(obj); - return typeCache[type] || (typeCache[type] = type.match(typeRegexp)[1].toLowerCase()); - } - - function clone(item, type){ - var fn = clone[type || typeOf(item)]; - return fn ? fn(item) : item; - } - clone.object = function(src){ - var obj = {}; - for (var key in src) obj[key] = clone(src[key]); - return obj; - }; - clone.array = function(src){ - var i = src.length, array = new Array(i); - while (i--) array[i] = clone(src[i]); - return array; - }; - - /* - The toArray() method allows for conversion of any object to a true array. For types that - cannot be converted to an array, the method returns a 1 item array containing the passed-in object. - */ - var unsliceable = { 'undefined': 1, 'null': 1, 'number': 1, 'boolean': 1, 'string': 1, 'function': 1 }; - function toArray(obj){ - return unsliceable[typeOf(obj)] ? [obj] : Array.prototype.slice.call(obj, 0); - } - -// DOM - - var str = ''; - function query(element, selector){ - return (selector || str).length ? toArray(element.querySelectorAll(selector)) : []; - } - -// Pseudos - - function parsePseudo(fn){fn();} - -// Mixins - - function mergeOne(source, key, current){ - var type = typeOf(current); - if (type == 'object' && typeOf(source[key]) == 'object') xtag.merge(source[key], current); - else source[key] = clone(current, type); - return source; - } - - function mergeMixin(tag, original, mixin, name) { - var key, keys = {}; - for (var z in original) keys[z.split(':')[0]] = z; - for (z in mixin) { - key = keys[z.split(':')[0]]; - if (typeof original[key] == 'function') { - if (!key.match(':mixins')) { - original[key + ':mixins'] = original[key]; - delete original[key]; - key = key + ':mixins'; - } - original[key].__mixin__ = xtag.applyPseudos(z + (z.match(':mixins') ? '' : ':mixins'), mixin[z], tag.pseudos, original[key].__mixin__); - } - else { - original[z] = mixin[z]; - delete original[key]; - } - } - } - - var uniqueMixinCount = 0; - function addMixin(tag, original, mixin){ - for (var z in mixin){ - original[z + ':__mixin__(' + (uniqueMixinCount++) + ')'] = xtag.applyPseudos(z, mixin[z], tag.pseudos); - } - } - - function resolveMixins(mixins, output){ - var index = mixins.length; - while (index--){ - output.unshift(mixins[index]); - if (xtag.mixins[mixins[index]].mixins) resolveMixins(xtag.mixins[mixins[index]].mixins, output); - } - return output; - } - - function applyMixins(tag) { - resolveMixins(tag.mixins, []).forEach(function(name){ - var mixin = xtag.mixins[name]; - for (var type in mixin) { - var item = mixin[type], - original = tag[type]; - if (!original) tag[type] = item; - else { - switch (type){ - case 'mixins': break; - case 'events': addMixin(tag, original, item); break; - case 'accessors': - case 'prototype': - for (var z in item) { - if (!original[z]) original[z] = item[z]; - else mergeMixin(tag, original[z], item[z], name); - } - break; - default: mergeMixin(tag, original, item, name); - } - } - } - }); - return tag; - } - -// Events - - function delegateAction(pseudo, event) { - var match, - target = event.target, - root = event.currentTarget; - while (!match && target && target != root) { - if (target.tagName && matchSelector.call(target, pseudo.value)) match = target; - target = target.parentNode; - } - if (!match && root.tagName && matchSelector.call(root, pseudo.value)) match = root; - return match ? pseudo.listener = pseudo.listener.bind(match) : null; - } - - function touchFilter(event){ - return event.button === 0; - } - - function writeProperty(key, event, base, desc){ - if (desc) event[key] = base[key]; - else Object.defineProperty(event, key, { - writable: true, - enumerable: true, - value: base[key] - }); - } - - var skipProps = {}; - for (var z in doc.createEvent('CustomEvent')) skipProps[z] = 1; - function inheritEvent(event, base){ - var desc = Object.getOwnPropertyDescriptor(event, 'target'); - for (var z in base) { - if (!skipProps[z]) writeProperty(z, event, base, desc); - } - event.baseEvent = base; - } - -// Accessors - - function modAttr(element, attr, name, value, method){ - attrProto[method].call(element, name, attr && attr.boolean ? '' : value); - } - - function syncAttr(element, attr, name, value, method){ - if (attr && (attr.property || attr.selector)) { - var nodes = attr.property ? [element.xtag[attr.property]] : attr.selector ? xtag.query(element, attr.selector) : [], - index = nodes.length; - while (index--) nodes[index][method](name, value); - } - } - - function attachProperties(tag, prop, z, accessor, attr, name){ - var key = z.split(':'), type = key[0]; - if (type == 'get') { - key[0] = prop; - tag.prototype[prop].get = xtag.applyPseudos(key.join(':'), accessor[z], tag.pseudos, accessor[z]); - } - else if (type == 'set') { - key[0] = prop; - var setter = tag.prototype[prop].set = xtag.applyPseudos(key.join(':'), attr ? function(value){ - var old, method = 'setAttribute'; - if (attr.boolean){ - value = !!value; - old = this.hasAttribute(name); - if (!value) method = 'removeAttribute'; - } - else { - value = attr.validate ? attr.validate.call(this, value) : value; - old = this.getAttribute(name); - } - modAttr(this, attr, name, value, method); - accessor[z].call(this, value, old); - syncAttr(this, attr, name, value, method); - } : accessor[z] ? function(value){ - accessor[z].call(this, value); - } : null, tag.pseudos, accessor[z]); - - if (attr) attr.setter = accessor[z]; - } - else tag.prototype[prop][z] = accessor[z]; - } - - function parseAccessor(tag, prop){ - tag.prototype[prop] = {}; - var accessor = tag.accessors[prop], - attr = accessor.attribute, - name; - - if (attr) { - name = attr.name = (attr ? (attr.name || prop.replace(regexCamelToDash, '$1-$2')) : prop).toLowerCase(); - attr.key = prop; - tag.attributes[name] = attr; - } - - for (var z in accessor) attachProperties(tag, prop, z, accessor, attr, name); - - if (attr) { - if (!tag.prototype[prop].get) { - var method = (attr.boolean ? 'has' : 'get') + 'Attribute'; - tag.prototype[prop].get = function(){ - return this[method](name); - }; - } - if (!tag.prototype[prop].set) tag.prototype[prop].set = function(value){ - value = attr.boolean ? !!value : attr.validate ? attr.validate.call(this, value) : value; - var method = attr.boolean ? (value ? 'setAttribute' : 'removeAttribute') : 'setAttribute'; - modAttr(this, attr, name, value, method); - syncAttr(this, attr, name, value, method); - }; - } - } - - var unwrapComment = /\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//; - function parseMultiline(fn){ - return typeof fn == 'function' ? unwrapComment.exec(fn.toString())[1] : fn; - } - -/*** X-Tag Object Definition ***/ - - var xtag = { - tags: {}, - defaultOptions: { - pseudos: [], - mixins: [], - events: {}, - methods: {}, - accessors: {}, - lifecycle: {}, - attributes: {}, - 'prototype': { - xtag: { - get: function(){ - return this.__xtag__ ? this.__xtag__ : (this.__xtag__ = { data: {} }); - } - } - } - }, - register: function (name, options) { - var _name; - if (typeof name == 'string') _name = name.toLowerCase(); - else throw 'First argument must be a Custom Element string name'; - xtag.tags[_name] = options || {}; - - var basePrototype = options.prototype; - delete options.prototype; - var tag = xtag.tags[_name].compiled = applyMixins(xtag.merge({}, xtag.defaultOptions, options)); - var proto = tag.prototype; - var lifecycle = tag.lifecycle; - - for (var z in tag.events) tag.events[z] = xtag.parseEvent(z, tag.events[z]); - for (z in lifecycle) lifecycle[z.split(':')[0]] = xtag.applyPseudos(z, lifecycle[z], tag.pseudos, lifecycle[z]); - for (z in tag.methods) proto[z.split(':')[0]] = { value: xtag.applyPseudos(z, tag.methods[z], tag.pseudos, tag.methods[z]), enumerable: true }; - for (z in tag.accessors) parseAccessor(tag, z); - - if (tag.shadow) tag.shadow = tag.shadow.nodeName ? tag.shadow : xtag.createFragment(tag.shadow); - if (tag.content) tag.content = tag.content.nodeName ? tag.content.innerHTML : parseMultiline(tag.content); - var created = lifecycle.created; - var finalized = lifecycle.finalized; - proto.createdCallback = { - enumerable: true, - value: function(){ - var element = this; - if (tag.shadow && hasShadow) this.createShadowRoot().appendChild(tag.shadow.cloneNode(true)); - if (tag.content) this.appendChild(document.createElement('div')).outerHTML = tag.content; - var output = created ? created.apply(this, arguments) : null; - xtag.addEvents(this, tag.events); - for (var name in tag.attributes) { - var attr = tag.attributes[name], - hasAttr = this.hasAttribute(name), - hasDefault = attr.def !== undefined; - if (hasAttr || attr.boolean || hasDefault) { - this[attr.key] = attr.boolean ? hasAttr : !hasAttr && hasDefault ? attr.def : this.getAttribute(name); - } - } - tag.pseudos.forEach(function(obj){ - obj.onAdd.call(element, obj); - }); - this.xtagComponentReady = true; - if (finalized) finalized.apply(this, arguments); - return output; - } - }; - - var inserted = lifecycle.inserted; - var removed = lifecycle.removed; - if (inserted || removed) { - proto.attachedCallback = { value: function(){ - if (removed) this.xtag.__parentNode__ = this.parentNode; - if (inserted) return inserted.apply(this, arguments); - }, enumerable: true }; - } - if (removed) { - proto.detachedCallback = { value: function(){ - var args = toArray(arguments); - args.unshift(this.xtag.__parentNode__); - var output = removed.apply(this, args); - delete this.xtag.__parentNode__; - return output; - }, enumerable: true }; - } - if (lifecycle.attributeChanged) proto.attributeChangedCallback = { value: lifecycle.attributeChanged, enumerable: true }; - - proto.setAttribute = { - writable: true, - enumerable: true, - value: function (name, value){ - var old; - var _name = name.toLowerCase(); - var attr = tag.attributes[_name]; - if (attr) { - old = this.getAttribute(_name); - value = attr.boolean ? '' : attr.validate ? attr.validate.call(this, value) : value; - } - modAttr(this, attr, _name, value, 'setAttribute'); - if (attr) { - if (attr.setter) attr.setter.call(this, attr.boolean ? true : value, old); - syncAttr(this, attr, _name, value, 'setAttribute'); - } - } - }; - - proto.removeAttribute = { - writable: true, - enumerable: true, - value: function (name){ - var _name = name.toLowerCase(); - var attr = tag.attributes[_name]; - var old = this.hasAttribute(_name); - modAttr(this, attr, _name, '', 'removeAttribute'); - if (attr) { - if (attr.setter) attr.setter.call(this, attr.boolean ? false : undefined, old); - syncAttr(this, attr, _name, '', 'removeAttribute'); - } - } - }; - - var definition = {}; - var instance = basePrototype instanceof win.HTMLElement; - var extended = tag['extends'] && (definition['extends'] = tag['extends']); - - if (basePrototype) Object.getOwnPropertyNames(basePrototype).forEach(function(z){ - var prop = proto[z]; - var desc = instance ? Object.getOwnPropertyDescriptor(basePrototype, z) : basePrototype[z]; - if (prop) { - for (var y in desc) { - if (typeof desc[y] == 'function' && prop[y]) prop[y] = xtag.wrap(desc[y], prop[y]); - else prop[y] = desc[y]; - } - } - proto[z] = prop || desc; - }); - - definition['prototype'] = Object.create( - extended ? Object.create(doc.createElement(extended).constructor).prototype : win.HTMLElement.prototype, - proto - ); - - return doc.registerElement(_name, definition); - }, - - /* Exposed Variables */ - - mixins: {}, - prefix: prefix, - captureEvents: { focus: 1, blur: 1, scroll: 1, DOMMouseScroll: 1 }, - customEvents: { - animationstart: { - attach: [prefix.dom + 'AnimationStart'] - }, - animationend: { - attach: [prefix.dom + 'AnimationEnd'] - }, - transitionend: { - attach: [prefix.dom + 'TransitionEnd'] - }, - move: { - attach: ['pointermove'] - }, - enter: { - attach: ['pointerenter'] - }, - leave: { - attach: ['pointerleave'] - }, - scrollwheel: { - attach: ['DOMMouseScroll', 'mousewheel'], - condition: function(event){ - event.delta = event.wheelDelta ? event.wheelDelta / 40 : Math.round(event.detail / 3.5 * -1); - return true; - } - }, - tap: { - attach: ['pointerdown', 'pointerup'], - condition: function(event, custom){ - if (event.type == 'pointerdown') { - custom.startX = event.clientX; - custom.startY = event.clientY; - } - else if (event.button === 0 && - Math.abs(custom.startX - event.clientX) < 10 && - Math.abs(custom.startY - event.clientY) < 10) return true; - } - }, - tapstart: { - attach: ['pointerdown'], - condition: touchFilter - }, - tapend: { - attach: ['pointerup'], - condition: touchFilter - }, - tapmove: { - attach: ['pointerdown'], - condition: function(event, custom){ - if (event.type == 'pointerdown') { - var listener = custom.listener.bind(this); - if (!custom.tapmoveListeners) custom.tapmoveListeners = xtag.addEvents(document, { - pointermove: listener, - pointerup: listener, - pointercancel: listener - }); - } - else if (event.type == 'pointerup' || event.type == 'pointercancel') { - xtag.removeEvents(document, custom.tapmoveListeners); - custom.tapmoveListeners = null; - } - return true; - } - }, - taphold: { - attach: ['pointerdown', 'pointerup'], - condition: function(event, custom){ - if (event.type == 'pointerdown') { - (custom.pointers = custom.pointers || {})[event.pointerId] = setTimeout( - xtag.fireEvent.bind(null, this, 'taphold'), - custom.duration || 1000 - ); - } - else if (event.type == 'pointerup') { - if (custom.pointers) { - clearTimeout(custom.pointers[event.pointerId]); - delete custom.pointers[event.pointerId]; - } - } - else return true; - } - } - }, - pseudos: { - __mixin__: {}, - mixins: { - onCompiled: function(fn, pseudo){ - var mixin = pseudo.source && pseudo.source.__mixin__ || pseudo.source; - if (mixin) switch (pseudo.value) { - case null: case '': case 'before': return function(){ - mixin.apply(this, arguments); - return fn.apply(this, arguments); - }; - case 'after': return function(){ - var returns = fn.apply(this, arguments); - mixin.apply(this, arguments); - return returns; - }; - case 'none': return fn; - } - else return fn; - } - }, - keypass: keypseudo, - keyfail: keypseudo, - delegate: { - action: delegateAction - }, - preventable: { - action: function (pseudo, event) { - return !event.defaultPrevented; - } - }, - duration: { - onAdd: function(pseudo){ - pseudo.source.duration = Number(pseudo.value); - } - }, - capture: { - onCompiled: function(fn, pseudo){ - if (pseudo.source) pseudo.source.capture = true; - } - } - }, - - /* UTILITIES */ - - clone: clone, - typeOf: typeOf, - toArray: toArray, - - wrap: function (original, fn) { - return function(){ - var output = original.apply(this, arguments); - fn.apply(this, arguments); - return output; - }; - }, - /* - Recursively merges one object with another. The first argument is the destination object, - all other objects passed in as arguments are merged from right to left, conflicts are overwritten - */ - merge: function(source, k, v){ - if (typeOf(k) == 'string') return mergeOne(source, k, v); - for (var i = 1, l = arguments.length; i < l; i++){ - var object = arguments[i]; - for (var key in object) mergeOne(source, key, object[key]); - } - return source; - }, - - /* - ----- This should be simplified! ----- - Generates a random ID string - */ - uid: function(){ - return Math.random().toString(36).substr(2,10); - }, - - /* DOM */ - - query: query, - - skipTransition: function(element, fn, bind){ - var prop = prefix.js + 'TransitionProperty'; - element.style[prop] = element.style.transitionProperty = 'none'; - var callback = fn ? fn.call(bind || element) : null; - return xtag.skipFrame(function(){ - element.style[prop] = element.style.transitionProperty = ''; - if (callback) callback.call(bind || element); - }); - }, - - requestFrame: (function(){ - var raf = win.requestAnimationFrame || - win[prefix.lowercase + 'RequestAnimationFrame'] || - function(fn){ return win.setTimeout(fn, 20); }; - return function(fn){ return raf(fn); }; - })(), - - cancelFrame: (function(){ - var cancel = win.cancelAnimationFrame || - win[prefix.lowercase + 'CancelAnimationFrame'] || - win.clearTimeout; - return function(id){ return cancel(id); }; - })(), - - skipFrame: function(fn){ - var id = xtag.requestFrame(function(){ id = xtag.requestFrame(fn); }); - return id; - }, - - matchSelector: function (element, selector) { - return matchSelector.call(element, selector); - }, - - set: function (element, method, value) { - element[method] = value; - if (window.CustomElements) CustomElements.upgradeAll(element); - }, - - innerHTML: function(el, html){ - xtag.set(el, 'innerHTML', html); - }, - - hasClass: function (element, klass) { - return element.className.split(' ').indexOf(klass.trim())>-1; - }, - - addClass: function (element, klass) { - var list = element.className.trim().split(' '); - klass.trim().split(' ').forEach(function (name) { - if (!~list.indexOf(name)) list.push(name); - }); - element.className = list.join(' ').trim(); - return element; - }, - - removeClass: function (element, klass) { - var classes = klass.trim().split(' '); - element.className = element.className.trim().split(' ').filter(function (name) { - return name && !~classes.indexOf(name); - }).join(' '); - return element; - }, - - toggleClass: function (element, klass) { - return xtag[xtag.hasClass(element, klass) ? 'removeClass' : 'addClass'].call(null, element, klass); - }, - - /* - Runs a query on only the children of an element - */ - queryChildren: function (element, selector) { - var id = element.id, - attr = '#' + (element.id = id || 'x_' + xtag.uid()) + ' > ', - parent = element.parentNode || !container.appendChild(element); - selector = attr + (selector + '').replace(regexReplaceCommas, ',' + attr); - var result = element.parentNode.querySelectorAll(selector); - if (!id) element.removeAttribute('id'); - if (!parent) container.removeChild(element); - return toArray(result); - }, - - /* - Creates a document fragment with the content passed in - content can be - a string of HTML, an element, or an array/collection of elements - */ - createFragment: function(content) { - var template = document.createElement('template'); - if (content) { - if (content.nodeName) toArray(arguments).forEach(function(e){ - template.content.appendChild(e); - }); - else template.innerHTML = parseMultiline(content); - } - return document.importNode(template.content, true); - }, - - /* - Removes an element from the DOM for more performant node manipulation. The element - is placed back into the DOM at the place it was taken from. - */ - manipulate: function(element, fn){ - var next = element.nextSibling, - parent = element.parentNode, - returned = fn.call(element) || element; - if (next) parent.insertBefore(returned, next); - else parent.appendChild(returned); - }, - - /* PSEUDOS */ - - applyPseudos: function(key, fn, target, source) { - var listener = fn, - pseudos = {}; - if (key.match(':')) { - var matches = [], - valueFlag = 0; - key.replace(regexPseudoParens, function(match){ - if (match == '(') return ++valueFlag == 1 ? '\u276A' : '('; - return !--valueFlag ? '\u276B' : ')'; - }).replace(regexPseudoCapture, function(z, name, value, solo){ - matches.push([name || solo, value]); - }); - var i = matches.length; - while (i--) parsePseudo(function(){ - var name = matches[i][0], - value = matches[i][1]; - if (!xtag.pseudos[name]) throw "pseudo not found: " + name + " " + value; - value = (value === '' || typeof value == 'undefined') ? null : value; - var pseudo = pseudos[i] = Object.create(xtag.pseudos[name]); - pseudo.key = key; - pseudo.name = name; - pseudo.value = value; - pseudo['arguments'] = (value || '').split(','); - pseudo.action = pseudo.action || trueop; - pseudo.source = source; - pseudo.onAdd = pseudo.onAdd || noop; - pseudo.onRemove = pseudo.onRemove || noop; - var original = pseudo.listener = listener; - listener = function(){ - var output = pseudo.action.apply(this, [pseudo].concat(toArray(arguments))); - if (output === null || output === false) return output; - output = pseudo.listener.apply(this, arguments); - pseudo.listener = original; - return output; - }; - if (!target) pseudo.onAdd.call(fn, pseudo); - else target.push(pseudo); - }); - } - for (var z in pseudos) { - if (pseudos[z].onCompiled) listener = pseudos[z].onCompiled(listener, pseudos[z]) || listener; - } - return listener; - }, - - removePseudos: function(target, pseudos){ - pseudos.forEach(function(obj){ - obj.onRemove.call(target, obj); - }); - }, - - /*** Events ***/ - - parseEvent: function(type, fn) { - var pseudos = type.split(':'), - key = pseudos.shift(), - custom = xtag.customEvents[key], - event = xtag.merge({ - type: key, - stack: noop, - condition: trueop, - capture: xtag.captureEvents[key], - attach: [], - _attach: [], - pseudos: '', - _pseudos: [], - onAdd: noop, - onRemove: noop - }, custom || {}); - event.attach = toArray(event.base || event.attach); - event.chain = key + (event.pseudos.length ? ':' + event.pseudos : '') + (pseudos.length ? ':' + pseudos.join(':') : ''); - var stack = xtag.applyPseudos(event.chain, fn, event._pseudos, event); - event.stack = function(e){ - e.currentTarget = e.currentTarget || this; - var detail = e.detail || {}; - if (!detail.__stack__) return stack.apply(this, arguments); - else if (detail.__stack__ == stack) { - e.stopPropagation(); - e.cancelBubble = true; - return stack.apply(this, arguments); - } - }; - event.listener = function(e){ - var args = toArray(arguments), - output = event.condition.apply(this, args.concat([event])); - if (!output) return output; - // The second condition in this IF is to address the following Blink regression: https://code.google.com/p/chromium/issues/detail?id=367537 - // Remove this when affected browser builds with this regression fall below 5% marketshare - if (e.type != key && (e.baseEvent && e.type != e.baseEvent.type)) { - xtag.fireEvent(e.target, key, { - baseEvent: e, - detail: output !== true && (output.__stack__ = stack) ? output : { __stack__: stack } - }); - } - else return event.stack.apply(this, args); - }; - event.attach.forEach(function(name) { - event._attach.push(xtag.parseEvent(name, event.listener)); - }); - return event; - }, - - addEvent: function (element, type, fn, capture) { - var event = typeof fn == 'function' ? xtag.parseEvent(type, fn) : fn; - event._pseudos.forEach(function(obj){ - obj.onAdd.call(element, obj); - }); - event._attach.forEach(function(obj) { - xtag.addEvent(element, obj.type, obj); - }); - event.onAdd.call(element, event, event.listener); - element.addEventListener(event.type, event.stack, capture || event.capture); - return event; - }, - - addEvents: function (element, obj) { - var events = {}; - for (var z in obj) { - events[z] = xtag.addEvent(element, z, obj[z]); - } - return events; - }, - - removeEvent: function (element, type, event) { - event = event || type; - event.onRemove.call(element, event, event.listener); - xtag.removePseudos(element, event._pseudos); - event._attach.forEach(function(obj) { - xtag.removeEvent(element, obj); - }); - element.removeEventListener(event.type, event.stack); - }, - - removeEvents: function(element, obj){ - for (var z in obj) xtag.removeEvent(element, obj[z]); - }, - - fireEvent: function(element, type, options){ - var event = doc.createEvent('CustomEvent'); - options = options || {}; - event.initCustomEvent(type, - options.bubbles !== false, - options.cancelable !== false, - options.detail - ); - if (options.baseEvent) inheritEvent(event, options.baseEvent); - element.dispatchEvent(event); - } - - }; - - if (typeof define === 'function' && define.amd) define(xtag); - else if (typeof module !== 'undefined' && module.exports) module.exports = xtag; - else win.xtag = xtag; - - doc.addEventListener('WebComponentsReady', function(){ - xtag.fireEvent(doc.body, 'DOMComponentsLoaded'); - }); - -})(); diff --git a/dist/x-tag-core.min.js b/dist/x-tag-core.min.js deleted file mode 100644 index c2d58dd..0000000 --- a/dist/x-tag-core.min.js +++ /dev/null @@ -1,3 +0,0 @@ -(function(){function e(e){if(this._element=e,e.className!=this._classCache){if(this._classCache=e.className,!this._classCache)return;var t,n=this._classCache.replace(/^\s+|\s+$/g,"").split(/\s+/);for(t=0;n.length>t;t++)a.call(this,n[t])}}function t(e,t){e.className=t.join(" ")}function n(e,t,n){Object.defineProperty?Object.defineProperty(e,t,{get:n}):e.__defineGetter__(t,n)}if(!(window.Element===void 0||"classList"in document.documentElement)){var r=Array.prototype,o=r.indexOf,i=r.slice,a=r.push,s=r.splice,c=r.join;e.prototype={add:function(e){this.contains(e)||(a.call(this,e),t(this._element,i.call(this,0)))},contains:function(e){return-1!==o.call(this,e)},item:function(e){return this[e]||null},remove:function(e){var n=o.call(this,e);-1!==n&&(s.call(this,n,1),t(this._element,i.call(this,0)))},toString:function(){return c.call(this," ")},toggle:function(e){-1===o.call(this,e)?this.add(e):this.remove(e)}},window.DOMTokenList=e,n(Element.prototype,"classList",function(){return new e(this)})}})(),function(){window.WebComponents=window.WebComponents||{flags:{}};var e="webcomponents-lite.js",t=document.querySelector('script[src*="'+e+'"]'),n={};if(!n.noOpts){if(location.search.slice(1).split("&").forEach(function(e){var t,r=e.split("=");r[0]&&(t=r[0].match(/wc-(.+)/))&&(n[t[1]]=r[1]||!0)}),t)for(var r,o=0;r=t.attributes[o];o++)"src"!==r.name&&(n[r.name]=r.value||!0);if(n.log&&n.log.split){var i=n.log.split(",");n.log={},i.forEach(function(e){n.log[e]=!0})}else n.log={}}n.register&&(window.CustomElements=window.CustomElements||{flags:{}},window.CustomElements.flags.register=n.register),WebComponents.flags=n}(),function(e){"use strict";function t(e){return void 0!==h[e]}function n(){s.call(this),this._isInvalid=!0}function r(e){return""==e&&n.call(this),e.toLowerCase()}function o(e){var t=e.charCodeAt(0);return t>32&&127>t&&-1==[34,35,60,62,63,96].indexOf(t)?e:encodeURIComponent(e)}function i(e){var t=e.charCodeAt(0);return t>32&&127>t&&-1==[34,35,60,62,96].indexOf(t)?e:encodeURIComponent(e)}function a(e,a,s){function c(e){y.push(e)}var u=a||"scheme start",l=0,d="",b=!1,g=!1,y=[];e:for(;(e[l-1]!=f||0==l)&&!this._isInvalid;){var w=e[l];switch(u){case"scheme start":if(!w||!m.test(w)){if(a){c("Invalid scheme.");break e}d="",u="no scheme";continue}d+=w.toLowerCase(),u="scheme";break;case"scheme":if(w&&v.test(w))d+=w.toLowerCase();else{if(":"!=w){if(a){if(f==w)break e;c("Code point not allowed in scheme: "+w);break e}d="",l=0,u="no scheme";continue}if(this._scheme=d,d="",a)break e;t(this._scheme)&&(this._isRelative=!0),u="file"==this._scheme?"relative":this._isRelative&&s&&s._scheme==this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"==w?(this._query="?",u="query"):"#"==w?(this._fragment="#",u="fragment"):f!=w&&" "!=w&&"\n"!=w&&"\r"!=w&&(this._schemeData+=o(w));break;case"no scheme":if(s&&t(s._scheme)){u="relative";continue}c("Missing scheme."),n.call(this);break;case"relative or authority":if("/"!=w||"/"!=e[l+1]){c("Expected /, got: "+w),u="relative";continue}u="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!=this._scheme&&(this._scheme=s._scheme),f==w){this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query=s._query,this._username=s._username,this._password=s._password;break e}if("/"==w||"\\"==w)"\\"==w&&c("\\ is an invalid code point."),u="relative slash";else if("?"==w)this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query="?",this._username=s._username,this._password=s._password,u="query";else{if("#"!=w){var _=e[l+1],E=e[l+2];("file"!=this._scheme||!m.test(w)||":"!=_&&"|"!=_||f!=E&&"/"!=E&&"\\"!=E&&"?"!=E&&"#"!=E)&&(this._host=s._host,this._port=s._port,this._username=s._username,this._password=s._password,this._path=s._path.slice(),this._path.pop()),u="relative path";continue}this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query=s._query,this._fragment="#",this._username=s._username,this._password=s._password,u="fragment"}break;case"relative slash":if("/"!=w&&"\\"!=w){"file"!=this._scheme&&(this._host=s._host,this._port=s._port,this._username=s._username,this._password=s._password),u="relative path";continue}"\\"==w&&c("\\ is an invalid code point."),u="file"==this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!=w){c("Expected '/', got: "+w),u="authority ignore slashes";continue}u="authority second slash";break;case"authority second slash":if(u="authority ignore slashes","/"!=w){c("Expected '/', got: "+w);continue}break;case"authority ignore slashes":if("/"!=w&&"\\"!=w){u="authority";continue}c("Expected authority, got: "+w);break;case"authority":if("@"==w){b&&(c("@ already seen."),d+="%40"),b=!0;for(var T=0;d.length>T;T++){var C=d[T];if(" "!=C&&"\n"!=C&&"\r"!=C)if(":"!=C||null!==this._password){var M=o(C);null!==this._password?this._password+=M:this._username+=M}else this._password="";else c("Invalid whitespace in authority.")}d=""}else{if(f==w||"/"==w||"\\"==w||"?"==w||"#"==w){l-=d.length,d="",u="host";continue}d+=w}break;case"file host":if(f==w||"/"==w||"\\"==w||"?"==w||"#"==w){2!=d.length||!m.test(d[0])||":"!=d[1]&&"|"!=d[1]?0==d.length?u="relative path start":(this._host=r.call(this,d),d="",u="relative path start"):u="relative path";continue}" "==w||"\n"==w||"\r"==w?c("Invalid whitespace in file host."):d+=w;break;case"host":case"hostname":if(":"!=w||g){if(f==w||"/"==w||"\\"==w||"?"==w||"#"==w){if(this._host=r.call(this,d),d="",u="relative path start",a)break e;continue}" "!=w&&"\n"!=w&&"\r"!=w?("["==w?g=!0:"]"==w&&(g=!1),d+=w):c("Invalid code point in host/hostname: "+w)}else if(this._host=r.call(this,d),d="",u="port","hostname"==a)break e;break;case"port":if(/[0-9]/.test(w))d+=w;else{if(f==w||"/"==w||"\\"==w||"?"==w||"#"==w||a){if(""!=d){var L=parseInt(d,10);L!=h[this._scheme]&&(this._port=L+""),d=""}if(a)break e;u="relative path start";continue}" "==w||"\n"==w||"\r"==w?c("Invalid code point in port: "+w):n.call(this)}break;case"relative path start":if("\\"==w&&c("'\\' not allowed in path."),u="relative path","/"!=w&&"\\"!=w)continue;break;case"relative path":if(f!=w&&"/"!=w&&"\\"!=w&&(a||"?"!=w&&"#"!=w))" "!=w&&"\n"!=w&&"\r"!=w&&(d+=o(w));else{"\\"==w&&c("\\ not allowed in relative path.");var O;(O=p[d.toLowerCase()])&&(d=O),".."==d?(this._path.pop(),"/"!=w&&"\\"!=w&&this._path.push("")):"."==d&&"/"!=w&&"\\"!=w?this._path.push(""):"."!=d&&("file"==this._scheme&&0==this._path.length&&2==d.length&&m.test(d[0])&&"|"==d[1]&&(d=d[0]+":"),this._path.push(d)),d="","?"==w?(this._query="?",u="query"):"#"==w&&(this._fragment="#",u="fragment")}break;case"query":a||"#"!=w?f!=w&&" "!=w&&"\n"!=w&&"\r"!=w&&(this._query+=i(w)):(this._fragment="#",u="fragment");break;case"fragment":f!=w&&" "!=w&&"\n"!=w&&"\r"!=w&&(this._fragment+=w)}l++}}function s(){this._scheme="",this._schemeData="",this._username="",this._password=null,this._host="",this._port="",this._path=[],this._query="",this._fragment="",this._isInvalid=!1,this._isRelative=!1}function c(e,t){void 0===t||t instanceof c||(t=new c(t+"")),this._url=e,s.call(this);var n=e.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");a.call(this,n,null,t)}var u=!1;if(!e.forceJURL)try{var l=new URL("b","http://a");l.pathname="c%20d",u="http://a/c%20d"===l.href}catch(d){}if(!u){var h=Object.create(null);h.ftp=21,h.file=0,h.gopher=70,h.http=80,h.https=443,h.ws=80,h.wss=443;var p=Object.create(null);p["%2e"]=".",p[".%2e"]="..",p["%2e."]="..",p["%2e%2e"]="..";var f=void 0,m=/[a-zA-Z]/,v=/[a-zA-Z0-9\+\-\.]/;c.prototype={toString:function(){return this.href},get href(){if(this._isInvalid)return this._url;var e="";return(""!=this._username||null!=this._password)&&(e=this._username+(null!=this._password?":"+this._password:"")+"@"),this.protocol+(this._isRelative?"//"+e+this.host:"")+this.pathname+this._query+this._fragment},set href(e){s.call(this),a.call(this,e)},get protocol(){return this._scheme+":"},set protocol(e){this._isInvalid||a.call(this,e+":","scheme start")},get host(){return this._isInvalid?"":this._port?this._host+":"+this._port:this._host},set host(e){!this._isInvalid&&this._isRelative&&a.call(this,e,"host")},get hostname(){return this._host},set hostname(e){!this._isInvalid&&this._isRelative&&a.call(this,e,"hostname")},get port(){return this._port},set port(e){!this._isInvalid&&this._isRelative&&a.call(this,e,"port")},get pathname(){return this._isInvalid?"":this._isRelative?"/"+this._path.join("/"):this._schemeData},set pathname(e){!this._isInvalid&&this._isRelative&&(this._path=[],a.call(this,e,"relative path start"))},get search(){return this._isInvalid||!this._query||"?"==this._query?"":this._query},set search(e){!this._isInvalid&&this._isRelative&&(this._query="?","?"==e[0]&&(e=e.slice(1)),a.call(this,e,"query"))},get hash(){return this._isInvalid||!this._fragment||"#"==this._fragment?"":this._fragment},set hash(e){this._isInvalid||(this._fragment="#","#"==e[0]&&(e=e.slice(1)),a.call(this,e,"fragment"))},get origin(){var e;if(this._isInvalid||!this._scheme)return"";switch(this._scheme){case"data":case"file":case"javascript":case"mailto":return"null"}return e=this.host,e?this._scheme+"://"+e:""}};var b=e.URL;b&&(c.createObjectURL=function(){return b.createObjectURL.apply(b,arguments)},c.revokeObjectURL=function(e){b.revokeObjectURL(e)}),e.URL=c}}(self),"undefined"==typeof WeakMap&&function(){var e=Object.defineProperty,t=Date.now()%1e9,n=function(){this.name="__st"+(1e9*Math.random()>>>0)+(t++ +"__")};n.prototype={set:function(t,n){var r=t[this.name];return r&&r[0]===t?r[1]=n:e(t,this.name,{value:[t,n],writable:!0}),this},get:function(e){var t;return(t=e[this.name])&&t[0]===e?t[1]:void 0},"delete":function(e){var t=e[this.name];return t&&t[0]===e?(t[0]=t[1]=void 0,!0):!1},has:function(e){var t=e[this.name];return t?t[0]===e:!1}},window.WeakMap=n}(),function(e){function t(e){w.push(e),y||(y=!0,m(r))}function n(e){return window.ShadowDOMPolyfill&&window.ShadowDOMPolyfill.wrapIfNeeded(e)||e}function r(){y=!1;var e=w;w=[],e.sort(function(e,t){return e.uid_-t.uid_});var t=!1;e.forEach(function(e){var n=e.takeRecords();o(e),n.length&&(e.callback_(n,e),t=!0)}),t&&r()}function o(e){e.nodes_.forEach(function(t){var n=v.get(t);n&&n.forEach(function(t){t.observer===e&&t.removeTransientObservers()})})}function i(e,t){for(var n=e;n;n=n.parentNode){var r=v.get(n);if(r)for(var o=0;r.length>o;o++){var i=r[o],a=i.options;if(n===e||a.subtree){var s=t(a);s&&i.enqueue(s)}}}}function a(e){this.callback_=e,this.nodes_=[],this.records_=[],this.uid_=++_}function s(e,t){this.type=e,this.target=t,this.addedNodes=[],this.removedNodes=[],this.previousSibling=null,this.nextSibling=null,this.attributeName=null,this.attributeNamespace=null,this.oldValue=null}function c(e){var t=new s(e.type,e.target);return t.addedNodes=e.addedNodes.slice(),t.removedNodes=e.removedNodes.slice(),t.previousSibling=e.previousSibling,t.nextSibling=e.nextSibling,t.attributeName=e.attributeName,t.attributeNamespace=e.attributeNamespace,t.oldValue=e.oldValue,t}function u(e,t){return E=new s(e,t)}function l(e){return T?T:(T=c(E),T.oldValue=e,T)}function d(){E=T=void 0}function h(e){return e===T||e===E}function p(e,t){return e===t?e:T&&h(e)?T:null}function f(e,t,n){this.observer=e,this.target=t,this.options=n,this.transientObservedNodes=[]}if(!e.JsMutationObserver){var m,v=new WeakMap;if(/Trident|Edge/.test(navigator.userAgent))m=setTimeout;else if(window.setImmediate)m=window.setImmediate;else{var b=[],g=Math.random()+"";window.addEventListener("message",function(e){if(e.data===g){var t=b;b=[],t.forEach(function(e){e()})}}),m=function(e){b.push(e),window.postMessage(g,"*")}}var y=!1,w=[],_=0;a.prototype={observe:function(e,t){if(e=n(e),!t.childList&&!t.attributes&&!t.characterData||t.attributeOldValue&&!t.attributes||t.attributeFilter&&t.attributeFilter.length&&!t.attributes||t.characterDataOldValue&&!t.characterData)throw new SyntaxError;var r=v.get(e);r||v.set(e,r=[]);for(var o,i=0;r.length>i;i++)if(r[i].observer===this){o=r[i],o.removeListeners(),o.options=t;break}o||(o=new f(this,e,t),r.push(o),this.nodes_.push(e)),o.addListeners()},disconnect:function(){this.nodes_.forEach(function(e){for(var t=v.get(e),n=0;t.length>n;n++){var r=t[n];if(r.observer===this){r.removeListeners(),t.splice(n,1);break}}},this),this.records_=[]},takeRecords:function(){var e=this.records_;return this.records_=[],e}};var E,T;f.prototype={enqueue:function(e){var n=this.observer.records_,r=n.length;if(n.length>0){var o=n[r-1],i=p(o,e);if(i)return n[r-1]=i,void 0}else t(this.observer);n[r]=e},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(e){var t=this.options;t.attributes&&e.addEventListener("DOMAttrModified",this,!0),t.characterData&&e.addEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.addEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(e){var t=this.options;t.attributes&&e.removeEventListener("DOMAttrModified",this,!0),t.characterData&&e.removeEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.removeEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(e){if(e!==this.target){this.addListeners_(e),this.transientObservedNodes.push(e);var t=v.get(e);t||v.set(e,t=[]),t.push(this)}},removeTransientObservers:function(){var e=this.transientObservedNodes;this.transientObservedNodes=[],e.forEach(function(e){this.removeListeners_(e);for(var t=v.get(e),n=0;t.length>n;n++)if(t[n]===this){t.splice(n,1);break}},this)},handleEvent:function(e){switch(e.stopImmediatePropagation(),e.type){case"DOMAttrModified":var t=e.attrName,n=e.relatedNode.namespaceURI,r=e.target,o=new u("attributes",r);o.attributeName=t,o.attributeNamespace=n;var a=e.attrChange===MutationEvent.ADDITION?null:e.prevValue;i(r,function(e){return!e.attributes||e.attributeFilter&&e.attributeFilter.length&&-1===e.attributeFilter.indexOf(t)&&-1===e.attributeFilter.indexOf(n)?void 0:e.attributeOldValue?l(a):o});break;case"DOMCharacterDataModified":var r=e.target,o=u("characterData",r),a=e.prevValue;i(r,function(e){return e.characterData?e.characterDataOldValue?l(a):o:void 0});break;case"DOMNodeRemoved":this.addTransientObserver(e.target);case"DOMNodeInserted":var s,c,h=e.target;"DOMNodeInserted"===e.type?(s=[h],c=[]):(s=[],c=[h]);var p=h.previousSibling,f=h.nextSibling,o=u("childList",e.target.parentNode);o.addedNodes=s,o.removedNodes=c,o.previousSibling=p,o.nextSibling=f,i(e.relatedNode,function(e){return e.childList?o:void 0})}d()}},e.JsMutationObserver=a,e.MutationObserver||(e.MutationObserver=a,a._isPolyfilled=!0)}}(self),"undefined"==typeof HTMLTemplateElement&&function(){function e(e){switch(e){case"&":return"&";case"<":return"<";case">":return">";case" ":return" "}}function t(t){return t.replace(a,e)}var n="template",r=document.implementation.createHTMLDocument("template"),o=!0;HTMLTemplateElement=function(){},HTMLTemplateElement.prototype=Object.create(HTMLElement.prototype),HTMLTemplateElement.decorate=function(e){if(!e.content){e.content=r.createDocumentFragment();for(var n;n=e.firstChild;)e.content.appendChild(n);if(o)try{Object.defineProperty(e,"innerHTML",{get:function(){for(var e="",n=this.content.firstChild;n;n=n.nextSibling)e+=n.outerHTML||t(n.data);return e},set:function(e){for(r.body.innerHTML=e,HTMLTemplateElement.bootstrap(r);this.content.firstChild;)this.content.removeChild(this.content.firstChild);for(;r.body.firstChild;)this.content.appendChild(r.body.firstChild)},configurable:!0})}catch(i){o=!1}HTMLTemplateElement.bootstrap(e.content)}},HTMLTemplateElement.bootstrap=function(e){for(var t,r=e.querySelectorAll(n),o=0,i=r.length;i>o&&(t=r[o]);o++)HTMLTemplateElement.decorate(t)},document.addEventListener("DOMContentLoaded",function(){HTMLTemplateElement.bootstrap(document)});var i=document.createElement;document.createElement=function(){"use strict";var e=i.apply(document,arguments);return"template"==e.localName&&HTMLTemplateElement.decorate(e),e};var a=/[&\u00A0<>]/g}(),function(){"use strict";if(!window.performance){var e=Date.now();window.performance={now:function(){return Date.now()-e}}}window.requestAnimationFrame||(window.requestAnimationFrame=function(){var e=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame;return e?function(t){return e(function(){t(performance.now())})}:function(e){return window.setTimeout(e,1e3/60)}}()),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(){return window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(e){clearTimeout(e)}}());var t=function(){var e=document.createEvent("Event");return e.initEvent("foo",!0,!0),e.preventDefault(),e.defaultPrevented}();if(!t){var n=Event.prototype.preventDefault;Event.prototype.preventDefault=function(){this.cancelable&&(n.call(this),Object.defineProperty(this,"defaultPrevented",{get:function(){return!0},configurable:!0}))}}var r=/Trident/.test(navigator.userAgent);if((!window.CustomEvent||r&&"function"!=typeof window.CustomEvent)&&(window.CustomEvent=function(e,t){t=t||{};var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,Boolean(t.bubbles),Boolean(t.cancelable),t.detail),n},window.CustomEvent.prototype=window.Event.prototype),!window.Event||r&&"function"!=typeof window.Event){var o=window.Event;window.Event=function(e,t){t=t||{};var n=document.createEvent("Event");return n.initEvent(e,Boolean(t.bubbles),Boolean(t.cancelable)),n},window.Event.prototype=o.prototype}}(window.WebComponents),window.HTMLImports=window.HTMLImports||{flags:{}},function(e){function t(e,t){t=t||f,r(function(){i(e,t)},t)}function n(e){return"complete"===e.readyState||e.readyState===b}function r(e,t){if(n(t))e&&e();else{var o=function(){("complete"===t.readyState||t.readyState===b)&&(t.removeEventListener(g,o),r(e,t))};t.addEventListener(g,o)}}function o(e){e.target.__loaded=!0}function i(e,t){function n(){c==u&&e&&e({allImports:s,loadedImports:l,errorImports:d})}function r(e){o(e),l.push(this),c++,n()}function i(){d.push(this),c++,n()}var s=t.querySelectorAll("link[rel=import]"),c=0,u=s.length,l=[],d=[];if(u)for(var h,p=0;u>p&&(h=s[p]);p++)a(h)?(l.push(this),c++,n()):(h.addEventListener("load",r),h.addEventListener("error",i));else n()}function a(e){return d?e.__loaded||e.import&&"loading"!==e.import.readyState:e.__importParsed}function s(e){for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)c(t)&&u(t)}function c(e){return"link"===e.localName&&"import"===e.rel}function u(e){var t=e.import;t?o({target:e}):(e.addEventListener("load",o),e.addEventListener("error",o))}var l="import",d=Boolean(l in document.createElement("link")),h=Boolean(window.ShadowDOMPolyfill),p=function(e){return h?window.ShadowDOMPolyfill.wrapIfNeeded(e):e},f=p(document),m={get:function(){var e=window.HTMLImports.currentScript||document.currentScript||("complete"!==document.readyState?document.scripts[document.scripts.length-1]:null);return p(e)},configurable:!0};Object.defineProperty(document,"_currentScript",m),Object.defineProperty(f,"_currentScript",m);var v=/Trident/.test(navigator.userAgent),b=v?"complete":"interactive",g="readystatechange";d&&(new MutationObserver(function(e){for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)t.addedNodes&&s(t.addedNodes)}).observe(document.head,{childList:!0}),function(){if("loading"===document.readyState)for(var e,t=document.querySelectorAll("link[rel=import]"),n=0,r=t.length;r>n&&(e=t[n]);n++)u(e)}()),t(function(e){window.HTMLImports.ready=!0,window.HTMLImports.readyTime=(new Date).getTime();var t=f.createEvent("CustomEvent");t.initCustomEvent("HTMLImportsLoaded",!0,!0,e),f.dispatchEvent(t)}),e.IMPORT_LINK_TYPE=l,e.useNative=d,e.rootDocument=f,e.whenReady=t,e.isIE=v}(window.HTMLImports),function(e){var t=[],n=function(e){t.push(e)},r=function(){t.forEach(function(t){t(e)})};e.addModule=n,e.initializeModules=r}(window.HTMLImports),window.HTMLImports.addModule(function(e){var t=/(url\()([^)]*)(\))/g,n=/(@import[\s]+(?!url\())([^;]*)(;)/g,r={resolveUrlsInStyle:function(e,t){var n=e.ownerDocument,r=n.createElement("a");return e.textContent=this.resolveUrlsInCssText(e.textContent,t,r),e},resolveUrlsInCssText:function(e,r,o){var i=this.replaceUrls(e,o,r,t);return i=this.replaceUrls(i,o,r,n)},replaceUrls:function(e,t,n,r){return e.replace(r,function(e,r,o,i){var a=o.replace(/["']/g,"");return n&&(a=new URL(a,n).href),t.href=a,a=t.href,r+"'"+a+"'"+i})}};e.path=r}),window.HTMLImports.addModule(function(e){var t={async:!0,ok:function(e){return e.status>=200&&300>e.status||304===e.status||0===e.status},load:function(n,r,o){var i=new XMLHttpRequest;return(e.flags.debug||e.flags.bust)&&(n+="?"+Math.random()),i.open("GET",n,t.async),i.addEventListener("readystatechange",function(e){if(4===i.readyState){var n=null;try{var a=i.getResponseHeader("Location");a&&(n="/"===a.substr(0,1)?location.origin+a:a)}catch(e){console.error(e.message)}r.call(o,!t.ok(i)&&i,i.response||i.responseText,n)}}),i.send(),i},loadDocument:function(e,t,n){this.load(e,t,n).responseType="document"}};e.xhr=t}),window.HTMLImports.addModule(function(e){var t=e.xhr,n=e.flags,r=function(e,t){this.cache={},this.onload=e,this.oncomplete=t,this.inflight=0,this.pending={}};r.prototype={addNodes:function(e){this.inflight+=e.length;for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)this.require(t);this.checkDone()},addNode:function(e){this.inflight++,this.require(e),this.checkDone()},require:function(e){var t=e.src||e.href;e.__nodeUrl=t,this.dedupe(t,e)||this.fetch(t,e)},dedupe:function(e,t){return this.pending[e]?(this.pending[e].push(t),!0):this.cache[e]?(this.onload(e,t,this.cache[e]),this.tail(),!0):(this.pending[e]=[t],!1)},fetch:function(e,r){if(n.load&&console.log("fetch",e,r),e)if(e.match(/^data:/)){var o=e.split(","),i=o[0],a=o[1];a=i.indexOf(";base64")>-1?atob(a):decodeURIComponent(a),setTimeout(function(){this.receive(e,r,null,a)}.bind(this),0)}else{var s=function(t,n,o){this.receive(e,r,t,n,o)}.bind(this);t.load(e,s)}else setTimeout(function(){this.receive(e,r,{error:"href must be specified"},null)}.bind(this),0)},receive:function(e,t,n,r,o){this.cache[e]=r;for(var i,a=this.pending[e],s=0,c=a.length;c>s&&(i=a[s]);s++)this.onload(e,i,r,n,o),this.tail();this.pending[e]=null},tail:function(){--this.inflight,this.checkDone()},checkDone:function(){this.inflight||this.oncomplete()}},e.Loader=r}),window.HTMLImports.addModule(function(e){var t=function(e){this.addCallback=e,this.mo=new MutationObserver(this.handler.bind(this))};t.prototype={handler:function(e){for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)"childList"===t.type&&t.addedNodes.length&&this.addedNodes(t.addedNodes)},addedNodes:function(e){this.addCallback&&this.addCallback(e);for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)t.children&&t.children.length&&this.addedNodes(t.children)},observe:function(e){this.mo.observe(e,{childList:!0,subtree:!0})}},e.Observer=t}),window.HTMLImports.addModule(function(e){function t(e){return"link"===e.localName&&e.rel===l}function n(e){var t=r(e);return"data:text/javascript;charset=utf-8,"+encodeURIComponent(t)}function r(e){return e.textContent+o(e)}function o(e){var t=e.ownerDocument;t.__importedScripts=t.__importedScripts||0;var n=e.ownerDocument.baseURI,r=t.__importedScripts?"-"+t.__importedScripts:"";return t.__importedScripts++,"\n//# sourceURL="+n+r+".js\n"}function i(e){var t=e.ownerDocument.createElement("style");return t.textContent=e.textContent,a.resolveUrlsInStyle(t),t}var a=e.path,s=e.rootDocument,c=e.flags,u=e.isIE,l=e.IMPORT_LINK_TYPE,d="link[rel="+l+"]",h={documentSelectors:d,importsSelectors:[d,"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 e=this.nextToParse();e&&this.parse(e)},parse:function(e){if(this.isParsed(e))return c.parse&&console.log("[%s] is already parsed",e.localName),void 0;var t=this[this.map[e.localName]];t&&(this.markParsing(e),t.call(this,e))},parseDynamic:function(e,t){this.dynamicElements.push(e),t||this.parseNext()},markParsing:function(e){c.parse&&console.log("parsing",e),this.parsingElement=e},markParsingComplete:function(e){e.__importParsed=!0,this.markDynamicParsingComplete(e),e.__importElement&&(e.__importElement.__importParsed=!0,this.markDynamicParsingComplete(e.__importElement)),this.parsingElement=null,c.parse&&console.log("completed",e)},markDynamicParsingComplete:function(e){var t=this.dynamicElements.indexOf(e);t>=0&&this.dynamicElements.splice(t,1)},parseImport:function(e){if(e.import=e.__doc,window.HTMLImports.__importsParsingHook&&window.HTMLImports.__importsParsingHook(e),e.import&&(e.import.__importParsed=!0),this.markParsingComplete(e),e.__resource&&!e.__error?e.dispatchEvent(new CustomEvent("load",{bubbles:!1})):e.dispatchEvent(new CustomEvent("error",{bubbles:!1})),e.__pending)for(var t;e.__pending.length;)t=e.__pending.shift(),t&&t({target:e});this.parseNext()},parseLink:function(e){t(e)?this.parseImport(e):(e.href=e.href,this.parseGeneric(e))},parseStyle:function(e){var t=e;e=i(e),t.__appliedElement=e,e.__importElement=t,this.parseGeneric(e)},parseGeneric:function(e){this.trackElement(e),this.addElementToDocument(e)},rootImportForElement:function(e){for(var t=e;t.ownerDocument.__importLink;)t=t.ownerDocument.__importLink;return t},addElementToDocument:function(e){var t=this.rootImportForElement(e.__importElement||e);t.parentNode.insertBefore(e,t)},trackElement:function(e,t){var n=this,r=function(o){e.removeEventListener("load",r),e.removeEventListener("error",r),t&&t(o),n.markParsingComplete(e),n.parseNext()};if(e.addEventListener("load",r),e.addEventListener("error",r),u&&"style"===e.localName){var o=!1;if(-1==e.textContent.indexOf("@import"))o=!0;else if(e.sheet){o=!0;for(var i,a=e.sheet.cssRules,s=a?a.length:0,c=0;s>c&&(i=a[c]);c++)i.type===CSSRule.IMPORT_RULE&&(o=o&&Boolean(i.styleSheet))}o&&setTimeout(function(){e.dispatchEvent(new CustomEvent("load",{bubbles:!1}))})}},parseScript:function(t){var r=document.createElement("script");r.__importElement=t,r.src=t.src?t.src:n(t),e.currentScript=t,this.trackElement(r,function(){r.parentNode&&r.parentNode.removeChild(r),e.currentScript=null}),this.addElementToDocument(r)},nextToParse:function(){return this._mayParse=[],!this.parsingElement&&(this.nextToParseInDoc(s)||this.nextToParseDynamic())},nextToParseInDoc:function(e,n){if(e&&0>this._mayParse.indexOf(e)){this._mayParse.push(e);for(var r,o=e.querySelectorAll(this.parseSelectorsForNode(e)),i=0,a=o.length;a>i&&(r=o[i]);i++)if(!this.isParsed(r))return this.hasResource(r)?t(r)?this.nextToParseInDoc(r.__doc,r):r:void 0}return n},nextToParseDynamic:function(){return this.dynamicElements[0]},parseSelectorsForNode:function(e){var t=e.ownerDocument||e;return t===s?this.documentSelectors:this.importsSelectors},isParsed:function(e){return e.__importParsed},needsDynamicParsing:function(e){return this.dynamicElements.indexOf(e)>=0},hasResource:function(e){return t(e)&&void 0===e.__doc?!1:!0}};e.parser=h,e.IMPORT_SELECTOR=d}),window.HTMLImports.addModule(function(e){function t(e){return n(e,a)}function n(e,t){return"link"===e.localName&&e.getAttribute("rel")===t}function r(e){return!!Object.getOwnPropertyDescriptor(e,"baseURI")}function o(e,t){var n=document.implementation.createHTMLDocument(a);n._URL=t;var o=n.createElement("base");o.setAttribute("href",t),n.baseURI||r(n)||Object.defineProperty(n,"baseURI",{value:t});var i=n.createElement("meta");return i.setAttribute("charset","utf-8"),n.head.appendChild(i),n.head.appendChild(o),n.body.innerHTML=e,window.HTMLTemplateElement&&HTMLTemplateElement.bootstrap&&HTMLTemplateElement.bootstrap(n),n}var i=e.flags,a=e.IMPORT_LINK_TYPE,s=e.IMPORT_SELECTOR,c=e.rootDocument,u=e.Loader,l=e.Observer,d=e.parser,h={documents:{},documentPreloadSelectors:s,importsPreloadSelectors:[s].join(","),loadNode:function(e){p.addNode(e)},loadSubtree:function(e){var t=this.marshalNodes(e);p.addNodes(t)},marshalNodes:function(e){return e.querySelectorAll(this.loadSelectorsForNode(e))},loadSelectorsForNode:function(e){var t=e.ownerDocument||e;return t===c?this.documentPreloadSelectors:this.importsPreloadSelectors},loaded:function(e,n,r,a,s){if(i.load&&console.log("loaded",e,n),n.__resource=r,n.__error=a,t(n)){var c=this.documents[e];void 0===c&&(c=a?null:o(r,s||e),c&&(c.__importLink=n,this.bootDocument(c)),this.documents[e]=c),n.__doc=c}d.parseNext()},bootDocument:function(e){this.loadSubtree(e),this.observer.observe(e),d.parseNext()},loadedAll:function(){d.parseNext()}},p=new u(h.loaded.bind(h),h.loadedAll.bind(h));if(h.observer=new l,!document.baseURI){var f={get:function(){var e=document.querySelector("base");return e?e.href:window.location.href},configurable:!0};Object.defineProperty(document,"baseURI",f),Object.defineProperty(c,"baseURI",f)}e.importer=h,e.importLoader=p}),window.HTMLImports.addModule(function(e){var t=e.parser,n=e.importer,r={added:function(e){for(var r,o,i,a,s=0,c=e.length;c>s&&(a=e[s]);s++)r||(r=a.ownerDocument,o=t.isParsed(r)),i=this.shouldLoadNode(a),i&&n.loadNode(a),this.shouldParseNode(a)&&o&&t.parseDynamic(a,i)},shouldLoadNode:function(e){return 1===e.nodeType&&o.call(e,n.loadSelectorsForNode(e))},shouldParseNode:function(e){return 1===e.nodeType&&o.call(e,t.parseSelectorsForNode(e))}};n.observer.addCallback=r.added.bind(r);var o=HTMLElement.prototype.matches||HTMLElement.prototype.matchesSelector||HTMLElement.prototype.webkitMatchesSelector||HTMLElement.prototype.mozMatchesSelector||HTMLElement.prototype.msMatchesSelector}),function(e){function t(){window.HTMLImports.importer.bootDocument(r)}var n=e.initializeModules;if(e.isIE,!e.useNative){n();var r=e.rootDocument;"complete"===document.readyState||"interactive"===document.readyState&&!window.attachEvent?t():document.addEventListener("DOMContentLoaded",t)}}(window.HTMLImports),window.CustomElements=window.CustomElements||{flags:{}},function(e){var t=e.flags,n=[],r=function(e){n.push(e)},o=function(){n.forEach(function(t){t(e)})};e.addModule=r,e.initializeModules=o,e.hasNative=Boolean(document.registerElement),e.isIE=/Trident/.test(navigator.userAgent),e.useNative=!t.register&&e.hasNative&&!window.ShadowDOMPolyfill&&(!window.HTMLImports||window.HTMLImports.useNative)}(window.CustomElements),window.CustomElements.addModule(function(e){function t(e,t){n(e,function(e){return t(e)?!0:(r(e,t),void 0)}),r(e,t)}function n(e,t,r){var o=e.firstElementChild;if(!o)for(o=e.firstChild;o&&o.nodeType!==Node.ELEMENT_NODE;)o=o.nextSibling;for(;o;)t(o,r)!==!0&&n(o,t,r),o=o.nextElementSibling;return null}function r(e,n){for(var r=e.shadowRoot;r;)t(r,n),r=r.olderShadowRoot}function o(e,t){i(e,t,[])}function i(e,t,n){if(e=window.wrap(e),!(n.indexOf(e)>=0)){n.push(e);for(var r,o=e.querySelectorAll("link[rel="+a+"]"),s=0,c=o.length;c>s&&(r=o[s]);s++)r.import&&i(r.import,t,n);t(e)}}var a=window.HTMLImports?window.HTMLImports.IMPORT_LINK_TYPE:"none";e.forDocumentTree=o,e.forSubtree=t}),window.CustomElements.addModule(function(e){function t(e,t){return n(e,t)||r(e,t)}function n(t,n){return e.upgrade(t,n)?!0:(n&&a(t),void 0)}function r(e,t){y(e,function(e){return n(e,t)?!0:void 0})}function o(e){T.push(e),E||(E=!0,setTimeout(i))}function i(){E=!1;for(var e,t=T,n=0,r=t.length;r>n&&(e=t[n]);n++)e();T=[]}function a(e){_?o(function(){s(e)}):s(e)}function s(e){e.__upgraded__&&!e.__attached&&(e.__attached=!0,e.attachedCallback&&e.attachedCallback())}function c(e){u(e),y(e,function(e){u(e)})}function u(e){_?o(function(){l(e)}):l(e)}function l(e){e.__upgraded__&&e.__attached&&(e.__attached=!1,e.detachedCallback&&e.detachedCallback())}function d(e){for(var t=e,n=window.wrap(document);t;){if(t==n)return!0;t=t.parentNode||t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&t.host}}function h(e){if(e.shadowRoot&&!e.shadowRoot.__watched){g.dom&&console.log("watching shadow-root for: ",e.localName); -for(var t=e.shadowRoot;t;)m(t),t=t.olderShadowRoot}}function p(e,n){if(g.dom){var r=n[0];if(r&&"childList"===r.type&&r.addedNodes&&r.addedNodes){for(var o=r.addedNodes[0];o&&o!==document&&!o.host;)o=o.parentNode;var i=o&&(o.URL||o._URL||o.host&&o.host.localName)||"";i=i.split("/?").shift().split("/").pop()}console.group("mutations (%d) [%s]",n.length,i||"")}var a=d(e);n.forEach(function(e){"childList"===e.type&&(C(e.addedNodes,function(e){e.localName&&t(e,a)}),C(e.removedNodes,function(e){e.localName&&c(e)}))}),g.dom&&console.groupEnd()}function f(e){for(e=window.wrap(e),e||(e=window.wrap(document));e.parentNode;)e=e.parentNode;var t=e.__observer;t&&(p(e,t.takeRecords()),i())}function m(e){if(!e.__observer){var t=new MutationObserver(p.bind(this,e));t.observe(e,{childList:!0,subtree:!0}),e.__observer=t}}function v(e){e=window.wrap(e),g.dom&&console.group("upgradeDocument: ",e.baseURI.split("/").pop());var n=e===window.wrap(document);t(e,n),m(e),g.dom&&console.groupEnd()}function b(e){w(e,v)}var g=e.flags,y=e.forSubtree,w=e.forDocumentTree,_=window.MutationObserver._isPolyfilled&&g["throttle-attached"];e.hasPolyfillMutations=_,e.hasThrottledAttached=_;var E=!1,T=[],C=Array.prototype.forEach.call.bind(Array.prototype.forEach),M=Element.prototype.createShadowRoot;M&&(Element.prototype.createShadowRoot=function(){var e=M.call(this);return window.CustomElements.watchShadow(this),e}),e.watchShadow=h,e.upgradeDocumentTree=b,e.upgradeDocument=v,e.upgradeSubtree=r,e.upgradeAll=t,e.attached=a,e.takeRecords=f}),window.CustomElements.addModule(function(e){function t(t,r){if("template"===t.localName&&window.HTMLTemplateElement&&HTMLTemplateElement.decorate&&HTMLTemplateElement.decorate(t),!t.__upgraded__&&t.nodeType===Node.ELEMENT_NODE){var o=t.getAttribute("is"),i=e.getRegisteredDefinition(t.localName)||e.getRegisteredDefinition(o);if(i&&(o&&i.tag==t.localName||!o&&!i.extends))return n(t,i,r)}}function n(t,n,o){return a.upgrade&&console.group("upgrade:",t.localName),n.is&&t.setAttribute("is",n.is),r(t,n),t.__upgraded__=!0,i(t),o&&e.attached(t),e.upgradeSubtree(t,o),a.upgrade&&console.groupEnd(),t}function r(e,t){Object.__proto__?e.__proto__=t.prototype:(o(e,t.prototype,t.native),e.__proto__=t.prototype)}function o(e,t,n){for(var r={},o=t;o!==n&&o!==HTMLElement.prototype;){for(var i,a=Object.getOwnPropertyNames(o),s=0;i=a[s];s++)r[i]||(Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(o,i)),r[i]=1);o=Object.getPrototypeOf(o)}}function i(e){e.createdCallback&&e.createdCallback()}var a=e.flags;e.upgrade=t,e.upgradeWithDefinition=n,e.implementPrototype=r}),window.CustomElements.addModule(function(e){function t(t,r){var c=r||{};if(!t)throw Error("document.registerElement: first argument `name` must not be empty");if(0>t.indexOf("-"))throw Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '"+(t+"")+"'.");if(o(t))throw Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '"+(t+"")+"'. The type name is invalid.");if(u(t))throw Error("DuplicateDefinitionError: a type with name '"+(t+"")+"' is already registered");return c.prototype||(c.prototype=Object.create(HTMLElement.prototype)),c.__name=t.toLowerCase(),c.lifecycle=c.lifecycle||{},c.ancestry=i(c.extends),a(c),s(c),n(c.prototype),l(c.__name,c),c.ctor=d(c),c.ctor.prototype=c.prototype,c.prototype.constructor=c.ctor,e.ready&&b(document),c.ctor}function n(e){if(!e.setAttribute._polyfilled){var t=e.setAttribute;e.setAttribute=function(e,n){r.call(this,e,n,t)};var n=e.removeAttribute;e.removeAttribute=function(e){r.call(this,e,null,n)},e.setAttribute._polyfilled=!0}}function r(e,t,n){e=e.toLowerCase();var r=this.getAttribute(e);n.apply(this,arguments);var o=this.getAttribute(e);this.attributeChangedCallback&&o!==r&&this.attributeChangedCallback(e,r,o)}function o(e){for(var t=0;E.length>t;t++)if(e===E[t])return!0}function i(e){var t=u(e);return t?i(t.extends).concat([t]):[]}function a(e){for(var t,n=e.extends,r=0;t=e.ancestry[r];r++)n=t.is&&t.tag;e.tag=n||e.__name,n&&(e.is=e.__name)}function s(e){if(!Object.__proto__){var t=HTMLElement.prototype;if(e.is){var n=document.createElement(e.tag);t=Object.getPrototypeOf(n)}for(var r,o=e.prototype,i=!1;o;)o==t&&(i=!0),r=Object.getPrototypeOf(o),r&&(o.__proto__=r),o=r;i||console.warn(e.tag+" prototype not found in prototype chain for "+e.is),e.native=t}}function c(e){return y(M(e.tag),e)}function u(e){return e?T[e.toLowerCase()]:void 0}function l(e,t){T[e]=t}function d(e){return function(){return c(e)}}function h(e,t,n){return e===C?p(t,n):L(e,t)}function p(e,t){e&&(e=e.toLowerCase()),t&&(t=t.toLowerCase());var n=u(t||e);if(n){if(e==n.tag&&t==n.is)return new n.ctor;if(!t&&!n.is)return new n.ctor}var r;return t?(r=p(e),r.setAttribute("is",t),r):(r=M(e),e.indexOf("-")>=0&&w(r,HTMLElement),r)}function f(e,t){var n=e[t];e[t]=function(){var e=n.apply(this,arguments);return g(e),e}}var m,v=e.isIE,b=e.upgradeDocumentTree,g=e.upgradeAll,y=e.upgradeWithDefinition,w=e.implementPrototype,_=e.useNative,E=["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"],T={},C="http://www.w3.org/1999/xhtml",M=document.createElement.bind(document),L=document.createElementNS.bind(document);m=Object.__proto__||_?function(e,t){return e instanceof t}:function(e,t){if(e instanceof t)return!0;for(var n=e;n;){if(n===t.prototype)return!0;n=n.__proto__}return!1},f(Node.prototype,"cloneNode"),f(document,"importNode"),v&&function(){var e=document.importNode;document.importNode=function(){var t=e.apply(document,arguments);if(t.nodeType==t.DOCUMENT_FRAGMENT_NODE){var n=document.createDocumentFragment();return n.appendChild(t),n}return t}}(),document.registerElement=t,document.createElement=p,document.createElementNS=h,e.registry=T,e.instanceof=m,e.reservedTagList=E,e.getRegisteredDefinition=u,document.register=document.registerElement}),function(e){function t(){i(window.wrap(document)),window.CustomElements.ready=!0;var e=window.requestAnimationFrame||function(e){setTimeout(e,16)};e(function(){setTimeout(function(){window.CustomElements.readyTime=Date.now(),window.HTMLImports&&(window.CustomElements.elapsed=window.CustomElements.readyTime-window.HTMLImports.readyTime),document.dispatchEvent(new CustomEvent("WebComponentsReady",{bubbles:!0}))})})}var n=e.useNative,r=e.initializeModules;if(e.isIE,n){var o=function(){};e.watchShadow=o,e.upgrade=o,e.upgradeAll=o,e.upgradeDocumentTree=o,e.upgradeSubtree=o,e.takeRecords=o,e.instanceof=function(e,t){return e instanceof t}}else r();var i=e.upgradeDocumentTree,a=e.upgradeDocument;if(window.wrap||(window.ShadowDOMPolyfill?(window.wrap=window.ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=window.ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(e){return e}),window.HTMLImports&&(window.HTMLImports.__importsParsingHook=function(e){e.import&&a(wrap(e.import))}),"complete"===document.readyState||e.flags.eager)t();else if("interactive"!==document.readyState||window.attachEvent||window.HTMLImports&&!window.HTMLImports.ready){var s=window.HTMLImports&&!window.HTMLImports.ready?"HTMLImportsLoaded":"DOMContentLoaded";window.addEventListener(s,t)}else t()}(window.CustomElements),function(){var e=document.createElement("style");e.textContent="body {transition: opacity ease-in 0.2s; } \nbody[unresolved] {opacity: 0; display: block; overflow: hidden; position: relative; } \n";var t=document.querySelector("head");t.insertBefore(e,t.firstChild)}(window.WebComponents),function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.PointerEventsPolyfill=t()}(this,function(){"use strict";function e(e,t){t=t||Object.create(null);var n=document.createEvent("Event");n.initEvent(e,t.bubbles||!1,t.cancelable||!1);for(var r,o=2;l.length>o;o++)r=l[o],n[r]=t[r]||d[o];n.buttons=t.buttons||0;var i=0;return i=t.pressure?t.pressure:n.buttons?.5:0,n.x=n.clientX,n.y=n.clientY,n.pointerId=t.pointerId||0,n.width=t.width||0,n.height=t.height||0,n.pressure=i,n.tiltX=t.tiltX||0,n.tiltY=t.tiltY||0,n.pointerType=t.pointerType||"",n.hwTimestamp=t.hwTimestamp||0,n.isPrimary=t.isPrimary||!1,n}function t(){this.array=[],this.size=0}function n(e,t,n,r){this.addCallback=e.bind(r),this.removeCallback=t.bind(r),this.changedCallback=n.bind(r),O&&(this.observer=new O(this.mutationWatcher.bind(this)))}function r(e){return"body /shadow-deep/ "+o(e)}function o(e){return'[touch-action="'+e+'"]'}function i(e){return"{ -ms-touch-action: "+e+"; touch-action: "+e+"; touch-action-delay: none; }"}function a(){if(A){I.forEach(function(e){e+""===e?(k+=o(e)+i(e)+"\n",x&&(k+=r(e)+i(e)+"\n")):(k+=e.selectors.map(o)+i(e.rule)+"\n",x&&(k+=e.selectors.map(r)+i(e.rule)+"\n"))});var e=document.createElement("style");e.textContent=k,document.head.appendChild(e)}}function s(){if(!window.PointerEvent){if(window.PointerEvent=h,window.navigator.msPointerEnabled){var e=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:e,enumerable:!0}),_.registerSource("ms",ot)}else _.registerSource("mouse",U),void 0!==window.ontouchstart&&_.registerSource("touch",et);_.register(document)}}function c(e){if(!_.pointermap.has(e))throw Error("InvalidPointerId")}function u(){window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:J},releasePointerCapture:{value:Q}})}var l=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],d=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],h=e,p=window.Map&&window.Map.prototype.forEach,f=p?Map:t;t.prototype={set:function(e,t){return void 0===t?this.delete(e):(this.has(e)||this.size++,this.array[e]=t,void 0)},has:function(e){return void 0!==this.array[e]},"delete":function(e){this.has(e)&&(delete this.array[e],this.size--)},get:function(e){return this.array[e]},clear:function(){this.array.length=0,this.size=0},forEach:function(e,t){return this.array.forEach(function(n,r){e.call(t,n,r,this)},this)}};var m=f,v=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","buttons","pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary","type","target","currentTarget","which","pageX","pageY","timeStamp"],b=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0,0,0,0,0,0,"",0,!1,"",null,null,0,0,0,0],g={pointerover:1,pointerout:1,pointerenter:1,pointerleave:1},y="undefined"!=typeof SVGElementInstance,w={pointermap:new m,eventMap:Object.create(null),captureInfo:Object.create(null),eventSources:Object.create(null),eventSourceList:[],registerSource:function(e,t){var n=t,r=n.events;r&&(r.forEach(function(e){n[e]&&(this.eventMap[e]=n[e].bind(n))},this),this.eventSources[e]=n,this.eventSourceList.push(n))},register:function(e){for(var t,n=this.eventSourceList.length,r=0;n>r&&(t=this.eventSourceList[r]);r++)t.register.call(t,e)},unregister:function(e){for(var t,n=this.eventSourceList.length,r=0;n>r&&(t=this.eventSourceList[r]);r++)t.unregister.call(t,e)},contains:function(e,t){try{return e.contains(t)}catch(n){return!1}},down:function(e){e.bubbles=!0,this.fireEvent("pointerdown",e)},move:function(e){e.bubbles=!0,this.fireEvent("pointermove",e)},up:function(e){e.bubbles=!0,this.fireEvent("pointerup",e)},enter:function(e){e.bubbles=!1,this.fireEvent("pointerenter",e)},leave:function(e){e.bubbles=!1,this.fireEvent("pointerleave",e)},over:function(e){e.bubbles=!0,this.fireEvent("pointerover",e)},out:function(e){e.bubbles=!0,this.fireEvent("pointerout",e)},cancel:function(e){e.bubbles=!0,this.fireEvent("pointercancel",e)},leaveOut:function(e){this.out(e),this.contains(e.target,e.relatedTarget)||this.leave(e)},enterOver:function(e){this.over(e),this.contains(e.target,e.relatedTarget)||this.enter(e)},eventHandler:function(e){if(!e._handledByPE){var t=e.type,n=this.eventMap&&this.eventMap[t];n&&n(e),e._handledByPE=!0}},listen:function(e,t){t.forEach(function(t){this.addEvent(e,t)},this)},unlisten:function(e,t){t.forEach(function(t){this.removeEvent(e,t)},this)},addEvent:function(e,t){e.addEventListener(t,this.boundHandler)},removeEvent:function(e,t){e.removeEventListener(t,this.boundHandler)},makeEvent:function(e,t){this.captureInfo[t.pointerId]&&(t.relatedTarget=null);var n=new h(e,t);return t.preventDefault&&(n.preventDefault=t.preventDefault),n._target=n._target||t.target,n},fireEvent:function(e,t){var n=this.makeEvent(e,t);return this.dispatchEvent(n)},cloneEvent:function(e){for(var t,n=Object.create(null),r=0;v.length>r;r++)t=v[r],n[t]=e[t]||b[r],!y||"target"!==t&&"relatedTarget"!==t||n[t]instanceof SVGElementInstance&&(n[t]=n[t].correspondingUseElement);return e.preventDefault&&(n.preventDefault=function(){e.preventDefault()}),n},getTarget:function(e){var t=this.captureInfo[e.pointerId];return t?e._target!==t&&e.type in g?void 0:t:e._target},setCapture:function(e,t){this.captureInfo[e]&&this.releaseCapture(e),this.captureInfo[e]=t;var n=document.createEvent("Event");n.initEvent("gotpointercapture",!0,!1),n.pointerId=e,this.implicitRelease=this.releaseCapture.bind(this,e),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease),n._target=t,this.asyncDispatchEvent(n)},releaseCapture:function(e){var t=this.captureInfo[e];if(t){var n=document.createEvent("Event");n.initEvent("lostpointercapture",!0,!1),n.pointerId=e,this.captureInfo[e]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease),n._target=t,this.asyncDispatchEvent(n)}},dispatchEvent:function(e){var t=this.getTarget(e);return t?t.dispatchEvent(e):void 0},asyncDispatchEvent:function(e){requestAnimationFrame(this.dispatchEvent.bind(this,e))}};w.boundHandler=w.eventHandler.bind(w);var _=w,E={shadow:function(e){return e?e.shadowRoot||e.webkitShadowRoot:void 0},canTarget:function(e){return e&&Boolean(e.elementFromPoint)},targetingShadow:function(e){var t=this.shadow(e);return this.canTarget(t)?t:void 0},olderShadow:function(e){var t=e.olderShadowRoot;if(!t){var n=e.querySelector("shadow");n&&(t=n.olderShadowRoot)}return t},allShadows:function(e){for(var t=[],n=this.shadow(e);n;)t.push(n),n=this.olderShadow(n);return t},searchRoot:function(e,t,n){if(e){var r,o,i=e.elementFromPoint(t,n);for(o=this.targetingShadow(i);o;){if(r=o.elementFromPoint(t,n)){var a=this.targetingShadow(r);return this.searchRoot(a,t,n)||r}o=this.olderShadow(o)}return i}},owner:function(e){for(var t=e;t.parentNode;)t=t.parentNode;return t.nodeType!==Node.DOCUMENT_NODE&&t.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(t=document),t},findTarget:function(e){var t=e.clientX,n=e.clientY,r=this.owner(e.target);return r.elementFromPoint(t,n)||(r=document),this.searchRoot(r,t,n)}},T=Array.prototype.forEach.call.bind(Array.prototype.forEach),C=Array.prototype.map.call.bind(Array.prototype.map),M=Array.prototype.slice.call.bind(Array.prototype.slice),L=Array.prototype.filter.call.bind(Array.prototype.filter),O=window.MutationObserver||window.WebKitMutationObserver,S="[touch-action]",N={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};n.prototype={watchSubtree:function(e){this.observer&&E.canTarget(e)&&this.observer.observe(e,N)},enableOnSubtree:function(e){this.watchSubtree(e),e===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(e)},installNewSubtree:function(e){T(this.findElements(e),this.addElement,this)},findElements:function(e){return e.querySelectorAll?e.querySelectorAll(S):[]},removeElement:function(e){this.removeCallback(e)},addElement:function(e){this.addCallback(e)},elementChanged:function(e,t){this.changedCallback(e,t)},concatLists:function(e,t){return e.concat(M(t))},installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(e){return e.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(e){var t=C(e,this.findElements,this);return t.push(L(e,this.isElement)),t.reduce(this.concatLists,[])},mutationWatcher:function(e){e.forEach(this.mutationHandler,this)},mutationHandler:function(e){if("childList"===e.type){var t=this.flattenMutationTree(e.addedNodes);t.forEach(this.addElement,this);var n=this.flattenMutationTree(e.removedNodes);n.forEach(this.removeElement,this)}else"attributes"===e.type&&this.elementChanged(e.target,e.oldValue)}};var P=n,I=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],k="",A=window.PointerEvent||window.MSPointerEvent,x=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,D=_.pointermap,R=25,H=[1,4,2,8,16],j=!1;try{j=1===new MouseEvent("test",{buttons:1}).buttons}catch(F){}var q,Y={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(e){_.listen(e,this.events)},unregister:function(e){_.unlisten(e,this.events)},lastTouches:[],isEventSimulatedFromTouch:function(e){for(var t,n=this.lastTouches,r=e.clientX,o=e.clientY,i=0,a=n.length;a>i&&(t=n[i]);i++){var s=Math.abs(r-t.x),c=Math.abs(o-t.y);if(R>=s&&R>=c)return!0}},prepareEvent:function(e){var t=_.cloneEvent(e),n=t.preventDefault;return t.preventDefault=function(){e.preventDefault(),n()},t.pointerId=this.POINTER_ID,t.isPrimary=!0,t.pointerType=this.POINTER_TYPE,t},prepareButtonsForMove:function(e,t){var n=D.get(this.POINTER_ID);e.buttons=n?n.buttons:0,t.buttons=e.buttons},mousedown:function(e){if(!this.isEventSimulatedFromTouch(e)){var t=D.get(this.POINTER_ID),n=this.prepareEvent(e);j||(n.buttons=H[n.button],t&&(n.buttons|=t.buttons),e.buttons=n.buttons),D.set(this.POINTER_ID,e),t?_.move(n):_.down(n)}},mousemove:function(e){if(!this.isEventSimulatedFromTouch(e)){var t=this.prepareEvent(e);j||this.prepareButtonsForMove(t,e),_.move(t)}},mouseup:function(e){if(!this.isEventSimulatedFromTouch(e)){var t=D.get(this.POINTER_ID),n=this.prepareEvent(e);if(!j){var r=H[n.button];n.buttons=t?t.buttons&~r:0,e.buttons=n.buttons}D.set(this.POINTER_ID,e),0===n.buttons||n.buttons===H[n.button]?(this.cleanupMouse(),_.up(n)):_.move(n)}},mouseover:function(e){if(!this.isEventSimulatedFromTouch(e)){var t=this.prepareEvent(e);j||this.prepareButtonsForMove(t,e),_.enterOver(t)}},mouseout:function(e){if(!this.isEventSimulatedFromTouch(e)){var t=this.prepareEvent(e);j||this.prepareButtonsForMove(t,e),_.leaveOut(t)}},cancel:function(e){var t=this.prepareEvent(e);_.cancel(t),this.cleanupMouse()},cleanupMouse:function(){D.delete(this.POINTER_ID)}},U=Y,X=_.captureInfo,B=E.findTarget.bind(E),z=E.allShadows.bind(E),W=_.pointermap,V=2500,K=200,G="touch-action",$=!1,Z={events:["touchstart","touchmove","touchend","touchcancel"],register:function(e){$?_.listen(e,this.events):q.enableOnSubtree(e)},unregister:function(e){$&&_.unlisten(e,this.events)},elementAdded:function(e){var t=e.getAttribute(G),n=this.touchActionToScrollType(t);n&&(e._scrollType=n,_.listen(e,this.events),z(e).forEach(function(e){e._scrollType=n,_.listen(e,this.events)},this))},elementRemoved:function(e){e._scrollType=void 0,_.unlisten(e,this.events),z(e).forEach(function(e){e._scrollType=void 0,_.unlisten(e,this.events)},this)},elementChanged:function(e,t){var n=e.getAttribute(G),r=this.touchActionToScrollType(n),o=this.touchActionToScrollType(t);r&&o?(e._scrollType=r,z(e).forEach(function(e){e._scrollType=r},this)):o?this.elementRemoved(e):r&&this.elementAdded(e)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(e){var t=e,n=this.scrollTypes;return"none"===t?"none":t===n.XSCROLLER?"X":t===n.YSCROLLER?"Y":n.SCROLLER.exec(t)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(e){return this.firstTouch===e.identifier},setPrimaryTouch:function(e){(0===W.size||1===W.size&&W.has(1))&&(this.firstTouch=e.identifier,this.firstXY={X:e.clientX,Y:e.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(e){e.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var e=function(){this.clickCount=0,this.resetId=null}.bind(this);this.resetId=setTimeout(e,K)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(e){var t=0;return("touchstart"===e||"touchmove"===e)&&(t=1),t},touchToPointer:function(e){var t=this.currentTouchEvent,n=_.cloneEvent(e),r=n.pointerId=e.identifier+2;n.target=X[r]||B(n),n.bubbles=!0,n.cancelable=!0,n.detail=this.clickCount,n.button=0,n.buttons=this.typeToButtons(t.type),n.width=e.radiusX||e.webkitRadiusX||0,n.height=e.radiusY||e.webkitRadiusY||0,n.pressure=e.force||e.webkitForce||.5,n.isPrimary=this.isPrimaryTouch(e),n.pointerType=this.POINTER_TYPE;var o=this;return n.preventDefault=function(){o.scrolling=!1,o.firstXY=null,t.preventDefault()},n},processTouches:function(e,t){var n=e.changedTouches;this.currentTouchEvent=e;for(var r,o=0;n.length>o;o++)r=n[o],t.call(this,this.touchToPointer(r))},shouldScroll:function(e){if(this.firstXY){var t,n=e.currentTarget._scrollType;if("none"===n)t=!1;else if("XY"===n)t=!0;else{var r=e.changedTouches[0],o=n,i="Y"===n?"X":"Y",a=Math.abs(r["client"+o]-this.firstXY[o]),s=Math.abs(r["client"+i]-this.firstXY[i]);t=a>=s}return this.firstXY=null,t}},findTouch:function(e,t){for(var n,r=0,o=e.length;o>r&&(n=e[r]);r++)if(n.identifier===t)return!0},vacuumTouches:function(e){var t=e.touches;if(W.size>=t.length){var n=[];W.forEach(function(e,r){if(1!==r&&!this.findTouch(t,r-2)){var o=e.out;n.push(o)}},this),n.forEach(this.cancelOut,this)}},touchstart:function(e){this.vacuumTouches(e),this.setPrimaryTouch(e.changedTouches[0]),this.dedupSynthMouse(e),this.scrolling||(this.clickCount++,this.processTouches(e,this.overDown))},overDown:function(e){W.set(e.pointerId,{target:e.target,out:e,outTarget:e.target}),_.over(e),_.enter(e),_.down(e)},touchmove:function(e){this.scrolling||(this.shouldScroll(e)?(this.scrolling=!0,this.touchcancel(e)):(e.preventDefault(),this.processTouches(e,this.moveOverOut)))},moveOverOut:function(e){var t=e,n=W.get(t.pointerId);if(n){var r=n.out,o=n.outTarget;_.move(t),r&&o!==t.target&&(r.relatedTarget=t.target,t.relatedTarget=o,r.target=o,t.target?(_.leaveOut(r),_.enterOver(t)):(t.target=o,t.relatedTarget=null,this.cancelOut(t))),n.out=t,n.outTarget=t.target}},touchend:function(e){this.dedupSynthMouse(e),this.processTouches(e,this.upOut)},upOut:function(e){this.scrolling||(_.up(e),_.out(e),_.leave(e)),this.cleanUpPointer(e)},touchcancel:function(e){this.processTouches(e,this.cancelOut)},cancelOut:function(e){_.cancel(e),_.out(e),_.leave(e),this.cleanUpPointer(e)},cleanUpPointer:function(e){W.delete(e.pointerId),this.removePrimaryPointer(e)},dedupSynthMouse:function(e){var t=U.lastTouches,n=e.changedTouches[0];if(this.isPrimaryTouch(n)){var r={x:n.clientX,y:n.clientY};t.push(r);var o=function(e,t){var n=e.indexOf(t);n>-1&&e.splice(n,1)}.bind(null,t,r);setTimeout(o,V)}}};$||(q=new P(Z.elementAdded,Z.elementRemoved,Z.elementChanged,Z));var J,Q,et=Z,tt=_.pointermap,nt=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,rt={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(e){_.listen(e,this.events)},unregister:function(e){_.unlisten(e,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(e){var t=e;return nt&&(t=_.cloneEvent(e),t.pointerType=this.POINTER_TYPES[e.pointerType]),t},cleanup:function(e){tt.delete(e)},MSPointerDown:function(e){tt.set(e.pointerId,e);var t=this.prepareEvent(e);_.down(t)},MSPointerMove:function(e){var t=this.prepareEvent(e);_.move(t)},MSPointerUp:function(e){var t=this.prepareEvent(e);_.up(t),this.cleanup(e.pointerId)},MSPointerOut:function(e){var t=this.prepareEvent(e);_.leaveOut(t)},MSPointerOver:function(e){var t=this.prepareEvent(e);_.enterOver(t)},MSPointerCancel:function(e){var t=this.prepareEvent(e);_.cancel(t),this.cleanup(e.pointerId)},MSLostPointerCapture:function(e){var t=_.makeEvent("lostpointercapture",e);_.dispatchEvent(t)},MSGotPointerCapture:function(e){var t=_.makeEvent("gotpointercapture",e);_.dispatchEvent(t)}},ot=rt,it=window.navigator;it.msPointerEnabled?(J=function(e){c(e),this.msSetPointerCapture(e)},Q=function(e){c(e),this.msReleasePointerCapture(e)}):(J=function(e){c(e),_.setCapture(e,this)},Q=function(e){c(e),_.releaseCapture(e,this)}),a(),s(),u();var at={dispatcher:_,Installer:P,PointerEvent:h,PointerMap:m,targetFinding:E};return at}),function(){function e(e){var t=D.call(e);return x[t]||(x[t]=t.match(R)[1].toLowerCase())}function t(n,r){var o=t[r||e(n)];return o?o(n):n}function n(t){return H[e(t)]?[t]:Array.prototype.slice.call(t,0)}function r(e,t){return(t||j).length?n(e.querySelectorAll(t)):[]}function o(e){e()}function i(n,r,o){var i=e(o);return"object"==i&&"object"==e(n[r])?X.merge(n[r],o):n[r]=t(o,i),n}function a(e,t,n){var r,o={};for(var i in t)o[i.split(":")[0]]=i;for(i in n)r=o[i.split(":")[0]],"function"==typeof t[r]?(r.match(":mixins")||(t[r+":mixins"]=t[r],delete t[r],r+=":mixins"),t[r].__mixin__=X.applyPseudos(i+(i.match(":mixins")?"":":mixins"),n[i],e.pseudos,t[r].__mixin__)):(t[i]=n[i],delete t[r])}function s(e,t,n){for(var r in n)t[r+":__mixin__("+F++ +")"]=X.applyPseudos(r,n[r],e.pseudos)}function c(e,t){for(var n=e.length;n--;)t.unshift(e[n]),X.mixins[e[n]].mixins&&c(X.mixins[e[n]].mixins,t);return t}function u(e){return c(e.mixins,[]).forEach(function(t){var n=X.mixins[t];for(var r in n){var o=n[r],i=e[r];if(i)switch(r){case"mixins":break;case"events":s(e,i,o);break;case"accessors":case"prototype":for(var c in o)i[c]?a(e,i[c],o[c],t):i[c]=o[c];break;default:a(e,i,o,t)}else e[r]=o}}),e}function l(e,t){for(var n,r=t.target,o=t.currentTarget;!n&&r&&r!=o;)r.tagName&&A.call(r,e.value)&&(n=r),r=r.parentNode;return!n&&o.tagName&&A.call(o,e.value)&&(n=o),n?e.listener=e.listener.bind(n):null}function d(e){return 0===e.button}function h(e,t,n,r){r?t[e]=n[e]:Object.defineProperty(t,e,{writable:!0,enumerable:!0,value:n[e]})}function p(e,t){var n=Object.getOwnPropertyDescriptor(e,"target");for(var r in t)q[r]||h(r,e,t,n);e.baseEvent=t}function f(e,t,n,r,o){_[o].call(e,n,t&&t.boolean?"":r)}function m(e,t,n,r,o){if(t&&(t.property||t.selector))for(var i=t.property?[e.xtag[t.property]]:t.selector?X.query(e,t.selector):[],a=i.length;a--;)i[a][o](n,r)}function v(e,t,n,r,o,i){var a=n.split(":"),s=a[0];"get"==s?(a[0]=t,e.prototype[t].get=X.applyPseudos(a.join(":"),r[n],e.pseudos,r[n])):"set"==s?(a[0]=t,e.prototype[t].set=X.applyPseudos(a.join(":"),o?function(e){var t,a="setAttribute";o.boolean?(e=!!e,t=this.hasAttribute(i),e||(a="removeAttribute")):(e=o.validate?o.validate.call(this,e):e,t=this.getAttribute(i)),f(this,o,i,e,a),r[n].call(this,e,t),m(this,o,i,e,a)}:r[n]?function(e){r[n].call(this,e)}:null,e.pseudos,r[n]),o&&(o.setter=r[n])):e.prototype[t][n]=r[n]}function b(e,t){e.prototype[t]={};var n,r=e.accessors[t],o=r.attribute;o&&(n=o.name=(o?o.name||t.replace(O,"$1-$2"):t).toLowerCase(),o.key=t,e.attributes[n]=o);for(var i in r)v(e,t,i,r,o,n);if(o){if(!e.prototype[t].get){var a=(o.boolean?"has":"get")+"Attribute";e.prototype[t].get=function(){return this[a](n)}}e.prototype[t].set||(e.prototype[t].set=function(e){e=o.boolean?!!e:o.validate?o.validate.call(this,e):e;var t=o.boolean?e?"setAttribute":"removeAttribute":"setAttribute";f(this,o,n,e,t),m(this,o,n,e,t)})}}function g(e){return"function"==typeof e?U.exec(""+e)[1]:e}var y=window,w=document,_={setAttribute:Element.prototype.setAttribute,removeAttribute:Element.prototype.removeAttribute},E=Element.prototype.createShadowRoot,T=w.createElement("div"),C=function(){},M=function(){return!0},L=/,/g,O=/([a-z])([A-Z])/g,S=/\(|\)/g,N=/:(\w+)\u276A(.+?(?=\u276B))|:(\w+)/g,P=/(\d+)/g,I={action:function(e,t){return e.value.match(P).indexOf(t.keyCode+"")>-1==("keypass"==e.name)||null}},k=function(){var e=Object.keys(window).join(),t=(e.match(/,(ms)/)||e.match(/,(moz)/)||e.match(/,(O)/)||[null,"webkit"])[1].toLowerCase();return{dom:"ms"==t?"MS":t,lowercase:t,css:"-"+t+"-",js:"ms"==t?t:t.charAt(0).toUpperCase()+t.substring(1)}}(),A=Element.prototype.matches||Element.prototype.matchesSelector||Element.prototype[k.lowercase+"MatchesSelector"],x={},D=x.toString,R=/\s([a-zA-Z]+)/;t.object=function(e){var n={};for(var r in e)n[r]=t(e[r]);return n},t.array=function(e){for(var n=e.length,r=Array(n);n--;)r[n]=t(e[n]);return r};var H={undefined:1,"null":1,number:1,"boolean":1,string:1,"function":1},j="",F=0,q={};for(var Y in w.createEvent("CustomEvent"))q[Y]=1;var U=/\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//,X={tags:{},defaultOptions:{pseudos:[],mixins:[],events:{},methods:{},accessors:{},lifecycle:{},attributes:{},prototype:{xtag:{get:function(){return this.__xtag__?this.__xtag__:this.__xtag__={data:{}}}}}},register:function(e,t){var r;if("string"!=typeof e)throw"First argument must be a Custom Element string name";r=e.toLowerCase(),X.tags[r]=t||{};var o=t.prototype;delete t.prototype;var i=X.tags[r].compiled=u(X.merge({},X.defaultOptions,t)),a=i.prototype,s=i.lifecycle;for(var c in i.events)i.events[c]=X.parseEvent(c,i.events[c]);for(c in s)s[c.split(":")[0]]=X.applyPseudos(c,s[c],i.pseudos,s[c]);for(c in i.methods)a[c.split(":")[0]]={value:X.applyPseudos(c,i.methods[c],i.pseudos,i.methods[c]),enumerable:!0};for(c in i.accessors)b(i,c);i.shadow&&(i.shadow=i.shadow.nodeName?i.shadow:X.createFragment(i.shadow)),i.content&&(i.content=i.content.nodeName?i.content.innerHTML:g(i.content));var l=s.created,d=s.finalized;a.createdCallback={enumerable:!0,value:function(){var e=this;i.shadow&&E&&this.createShadowRoot().appendChild(i.shadow.cloneNode(!0)),i.content&&(this.appendChild(document.createElement("div")).outerHTML=i.content);var t=l?l.apply(this,arguments):null;X.addEvents(this,i.events);for(var n in i.attributes){var r=i.attributes[n],o=this.hasAttribute(n),a=void 0!==r.def;(o||r.boolean||a)&&(this[r.key]=r.boolean?o:!o&&a?r.def:this.getAttribute(n))}return i.pseudos.forEach(function(t){t.onAdd.call(e,t)}),this.xtagComponentReady=!0,d&&d.apply(this,arguments),t}};var h=s.inserted,p=s.removed;(h||p)&&(a.attachedCallback={value:function(){return p&&(this.xtag.__parentNode__=this.parentNode),h?h.apply(this,arguments):void 0},enumerable:!0}),p&&(a.detachedCallback={value:function(){var e=n(arguments);e.unshift(this.xtag.__parentNode__);var t=p.apply(this,e);return delete this.xtag.__parentNode__,t},enumerable:!0}),s.attributeChanged&&(a.attributeChangedCallback={value:s.attributeChanged,enumerable:!0}),a.setAttribute={writable:!0,enumerable:!0,value:function(e,t){var n,r=e.toLowerCase(),o=i.attributes[r];o&&(n=this.getAttribute(r),t=o.boolean?"":o.validate?o.validate.call(this,t):t),f(this,o,r,t,"setAttribute"),o&&(o.setter&&o.setter.call(this,o.boolean?!0:t,n),m(this,o,r,t,"setAttribute"))}},a.removeAttribute={writable:!0,enumerable:!0,value:function(e){var t=e.toLowerCase(),n=i.attributes[t],r=this.hasAttribute(t);f(this,n,t,"","removeAttribute"),n&&(n.setter&&n.setter.call(this,n.boolean?!1:void 0,r),m(this,n,t,"","removeAttribute"))}};var v={},_=o instanceof y.HTMLElement,T=i["extends"]&&(v["extends"]=i["extends"]);return o&&Object.getOwnPropertyNames(o).forEach(function(e){var t=a[e],n=_?Object.getOwnPropertyDescriptor(o,e):o[e];if(t)for(var r in n)t[r]="function"==typeof n[r]&&t[r]?X.wrap(n[r],t[r]):n[r];a[e]=t||n}),v.prototype=Object.create(T?Object.create(w.createElement(T).constructor).prototype:y.HTMLElement.prototype,a),w.registerElement(r,v)},mixins:{},prefix:k,captureEvents:{focus:1,blur:1,scroll:1,DOMMouseScroll:1},customEvents:{animationstart:{attach:[k.dom+"AnimationStart"]},animationend:{attach:[k.dom+"AnimationEnd"]},transitionend:{attach:[k.dom+"TransitionEnd"]},move:{attach:["pointermove"]},enter:{attach:["pointerenter"]},leave:{attach:["pointerleave"]},scrollwheel:{attach:["DOMMouseScroll","mousewheel"],condition:function(e){return e.delta=e.wheelDelta?e.wheelDelta/40:Math.round(-1*(e.detail/3.5)),!0 -}},tap:{attach:["pointerdown","pointerup"],condition:function(e,t){if("pointerdown"==e.type)t.startX=e.clientX,t.startY=e.clientY;else if(0===e.button&&10>Math.abs(t.startX-e.clientX)&&10>Math.abs(t.startY-e.clientY))return!0}},tapstart:{attach:["pointerdown"],condition:d},tapend:{attach:["pointerup"],condition:d},tapmove:{attach:["pointerdown"],condition:function(e,t){if("pointerdown"==e.type){var n=t.listener.bind(this);t.tapmoveListeners||(t.tapmoveListeners=X.addEvents(document,{pointermove:n,pointerup:n,pointercancel:n}))}else("pointerup"==e.type||"pointercancel"==e.type)&&(X.removeEvents(document,t.tapmoveListeners),t.tapmoveListeners=null);return!0}},taphold:{attach:["pointerdown","pointerup"],condition:function(e,t){if("pointerdown"==e.type)(t.pointers=t.pointers||{})[e.pointerId]=setTimeout(X.fireEvent.bind(null,this,"taphold"),t.duration||1e3);else{if("pointerup"!=e.type)return!0;t.pointers&&(clearTimeout(t.pointers[e.pointerId]),delete t.pointers[e.pointerId])}}}},pseudos:{__mixin__:{},mixins:{onCompiled:function(e,t){var n=t.source&&t.source.__mixin__||t.source;if(!n)return e;switch(t.value){case null:case"":case"before":return function(){return n.apply(this,arguments),e.apply(this,arguments)};case"after":return function(){var t=e.apply(this,arguments);return n.apply(this,arguments),t};case"none":return e}}},keypass:I,keyfail:I,delegate:{action:l},preventable:{action:function(e,t){return!t.defaultPrevented}},duration:{onAdd:function(e){e.source.duration=Number(e.value)}},capture:{onCompiled:function(e,t){t.source&&(t.source.capture=!0)}}},clone:t,typeOf:e,toArray:n,wrap:function(e,t){return function(){var n=e.apply(this,arguments);return t.apply(this,arguments),n}},merge:function(t,n,r){if("string"==e(n))return i(t,n,r);for(var o=1,a=arguments.length;a>o;o++){var s=arguments[o];for(var c in s)i(t,c,s[c])}return t},uid:function(){return Math.random().toString(36).substr(2,10)},query:r,skipTransition:function(e,t,n){var r=k.js+"TransitionProperty";e.style[r]=e.style.transitionProperty="none";var o=t?t.call(n||e):null;return X.skipFrame(function(){e.style[r]=e.style.transitionProperty="",o&&o.call(n||e)})},requestFrame:function(){var e=y.requestAnimationFrame||y[k.lowercase+"RequestAnimationFrame"]||function(e){return y.setTimeout(e,20)};return function(t){return e(t)}}(),cancelFrame:function(){var e=y.cancelAnimationFrame||y[k.lowercase+"CancelAnimationFrame"]||y.clearTimeout;return function(t){return e(t)}}(),skipFrame:function(e){var t=X.requestFrame(function(){t=X.requestFrame(e)});return t},matchSelector:function(e,t){return A.call(e,t)},set:function(e,t,n){e[t]=n,window.CustomElements&&CustomElements.upgradeAll(e)},innerHTML:function(e,t){X.set(e,"innerHTML",t)},hasClass:function(e,t){return e.className.split(" ").indexOf(t.trim())>-1},addClass:function(e,t){var n=e.className.trim().split(" ");return t.trim().split(" ").forEach(function(e){~n.indexOf(e)||n.push(e)}),e.className=n.join(" ").trim(),e},removeClass:function(e,t){var n=t.trim().split(" ");return e.className=e.className.trim().split(" ").filter(function(e){return e&&!~n.indexOf(e)}).join(" "),e},toggleClass:function(e,t){return X[X.hasClass(e,t)?"removeClass":"addClass"].call(null,e,t)},queryChildren:function(e,t){var r=e.id,o="#"+(e.id=r||"x_"+X.uid())+" > ",i=e.parentNode||!T.appendChild(e);t=o+(t+"").replace(L,","+o);var a=e.parentNode.querySelectorAll(t);return r||e.removeAttribute("id"),i||T.removeChild(e),n(a)},createFragment:function(e){var t=document.createElement("template");return e&&(e.nodeName?n(arguments).forEach(function(e){t.content.appendChild(e)}):t.innerHTML=g(e)),document.importNode(t.content,!0)},manipulate:function(e,t){var n=e.nextSibling,r=e.parentNode,o=t.call(e)||e;n?r.insertBefore(o,n):r.appendChild(o)},applyPseudos:function(e,t,r,i){var a=t,s={};if(e.match(":")){var c=[],u=0;e.replace(S,function(e){return"("==e?1==++u?"❪":"(":--u?")":"❫"}).replace(N,function(e,t,n,r){c.push([t||r,n])});for(var l=c.length;l--;)o(function(){var o=c[l][0],u=c[l][1];if(!X.pseudos[o])throw"pseudo not found: "+o+" "+u;u=""===u||u===void 0?null:u;var d=s[l]=Object.create(X.pseudos[o]);d.key=e,d.name=o,d.value=u,d.arguments=(u||"").split(","),d.action=d.action||M,d.source=i,d.onAdd=d.onAdd||C,d.onRemove=d.onRemove||C;var h=d.listener=a;a=function(){var e=d.action.apply(this,[d].concat(n(arguments)));return null===e||e===!1?e:(e=d.listener.apply(this,arguments),d.listener=h,e)},r?r.push(d):d.onAdd.call(t,d)})}for(var d in s)s[d].onCompiled&&(a=s[d].onCompiled(a,s[d])||a);return a},removePseudos:function(e,t){t.forEach(function(t){t.onRemove.call(e,t)})},parseEvent:function(e,t){var r=e.split(":"),o=r.shift(),i=X.customEvents[o],a=X.merge({type:o,stack:C,condition:M,capture:X.captureEvents[o],attach:[],_attach:[],pseudos:"",_pseudos:[],onAdd:C,onRemove:C},i||{});a.attach=n(a.base||a.attach),a.chain=o+(a.pseudos.length?":"+a.pseudos:"")+(r.length?":"+r.join(":"):"");var s=X.applyPseudos(a.chain,t,a._pseudos,a);return a.stack=function(e){e.currentTarget=e.currentTarget||this;var t=e.detail||{};return t.__stack__?t.__stack__==s?(e.stopPropagation(),e.cancelBubble=!0,s.apply(this,arguments)):void 0:s.apply(this,arguments)},a.listener=function(e){var t=n(arguments),r=a.condition.apply(this,t.concat([a]));return r?e.type!=o&&e.baseEvent&&e.type!=e.baseEvent.type?(X.fireEvent(e.target,o,{baseEvent:e,detail:r!==!0&&(r.__stack__=s)?r:{__stack__:s}}),void 0):a.stack.apply(this,t):r},a.attach.forEach(function(e){a._attach.push(X.parseEvent(e,a.listener))}),a},addEvent:function(e,t,n,r){var o="function"==typeof n?X.parseEvent(t,n):n;return o._pseudos.forEach(function(t){t.onAdd.call(e,t)}),o._attach.forEach(function(t){X.addEvent(e,t.type,t)}),o.onAdd.call(e,o,o.listener),e.addEventListener(o.type,o.stack,r||o.capture),o},addEvents:function(e,t){var n={};for(var r in t)n[r]=X.addEvent(e,r,t[r]);return n},removeEvent:function(e,t,n){n=n||t,n.onRemove.call(e,n,n.listener),X.removePseudos(e,n._pseudos),n._attach.forEach(function(t){X.removeEvent(e,t)}),e.removeEventListener(n.type,n.stack)},removeEvents:function(e,t){for(var n in t)X.removeEvent(e,t[n])},fireEvent:function(e,t,n){var r=w.createEvent("CustomEvent");n=n||{},r.initCustomEvent(t,n.bubbles!==!1,n.cancelable!==!1,n.detail),n.baseEvent&&p(r,n.baseEvent),e.dispatchEvent(r)}};"function"==typeof define&&define.amd?define(X):"undefined"!=typeof module&&module.exports?module.exports=X:y.xtag=X,w.addEventListener("WebComponentsReady",function(){X.fireEvent(w.body,"DOMComponentsLoaded")})}(); \ No newline at end of file diff --git a/dist/x-tag-no-polyfills.js b/dist/x-tag-no-polyfills.js deleted file mode 100644 index 38fe05e..0000000 --- a/dist/x-tag-no-polyfills.js +++ /dev/null @@ -1,866 +0,0 @@ -(function () { - -/*** Variables ***/ - - var win = window, - doc = document, - attrProto = { - setAttribute: Element.prototype.setAttribute, - removeAttribute: Element.prototype.removeAttribute - }, - hasShadow = Element.prototype.createShadowRoot, - container = doc.createElement('div'), - noop = function(){}, - trueop = function(){ return true; }, - regexReplaceCommas = /,/g, - regexCamelToDash = /([a-z])([A-Z])/g, - regexPseudoParens = /\(|\)/g, - regexPseudoCapture = /:(\w+)\u276A(.+?(?=\u276B))|:(\w+)/g, - regexDigits = /(\d+)/g, - keypseudo = { - action: function (pseudo, event) { - return pseudo.value.match(regexDigits).indexOf(String(event.keyCode)) > -1 == (pseudo.name == 'keypass') || null; - } - }, - /* - - The prefix object generated here is added to the xtag object as xtag.prefix later in the code - - Prefix provides a variety of prefix variations for the browser in which your code is running - - The 4 variations of prefix are as follows: - * prefix.dom: the correct prefix case and form when used on DOM elements/style properties - * prefix.lowercase: a lowercase version of the prefix for use in various user-code situations - * prefix.css: the lowercase, dashed version of the prefix - * prefix.js: addresses prefixed APIs present in global and non-Element contexts - */ - prefix = (function () { - var keys = Object.keys(window).join(); - var pre = ((keys.match(/,(ms)/) || keys.match(/,(moz)/) || keys.match(/,(O)/)) || [null, 'webkit'])[1].toLowerCase(); - return { - dom: pre == 'ms' ? 'MS' : pre, - lowercase: pre, - css: '-' + pre + '-', - js: pre == 'ms' ? pre : pre.charAt(0).toUpperCase() + pre.substring(1) - }; - })(), - matchSelector = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype[prefix.lowercase + 'MatchesSelector']; - -/*** Functions ***/ - -// Utilities - - /* - This is an enhanced typeof check for all types of objects. Where typeof would normaly return - 'object' for many common DOM objects (like NodeLists and HTMLCollections). - - For example: typeOf(document.children) will correctly return 'htmlcollection' - */ - var typeCache = {}, - typeString = typeCache.toString, - typeRegexp = /\s([a-zA-Z]+)/; - function typeOf(obj) { - var type = typeString.call(obj); - return typeCache[type] || (typeCache[type] = type.match(typeRegexp)[1].toLowerCase()); - } - - function clone(item, type){ - var fn = clone[type || typeOf(item)]; - return fn ? fn(item) : item; - } - clone.object = function(src){ - var obj = {}; - for (var key in src) obj[key] = clone(src[key]); - return obj; - }; - clone.array = function(src){ - var i = src.length, array = new Array(i); - while (i--) array[i] = clone(src[i]); - return array; - }; - - /* - The toArray() method allows for conversion of any object to a true array. For types that - cannot be converted to an array, the method returns a 1 item array containing the passed-in object. - */ - var unsliceable = { 'undefined': 1, 'null': 1, 'number': 1, 'boolean': 1, 'string': 1, 'function': 1 }; - function toArray(obj){ - return unsliceable[typeOf(obj)] ? [obj] : Array.prototype.slice.call(obj, 0); - } - -// DOM - - var str = ''; - function query(element, selector){ - return (selector || str).length ? toArray(element.querySelectorAll(selector)) : []; - } - -// Pseudos - - function parsePseudo(fn){fn();} - -// Mixins - - function mergeOne(source, key, current){ - var type = typeOf(current); - if (type == 'object' && typeOf(source[key]) == 'object') xtag.merge(source[key], current); - else source[key] = clone(current, type); - return source; - } - - function mergeMixin(tag, original, mixin, name) { - var key, keys = {}; - for (var z in original) keys[z.split(':')[0]] = z; - for (z in mixin) { - key = keys[z.split(':')[0]]; - if (typeof original[key] == 'function') { - if (!key.match(':mixins')) { - original[key + ':mixins'] = original[key]; - delete original[key]; - key = key + ':mixins'; - } - original[key].__mixin__ = xtag.applyPseudos(z + (z.match(':mixins') ? '' : ':mixins'), mixin[z], tag.pseudos, original[key].__mixin__); - } - else { - original[z] = mixin[z]; - delete original[key]; - } - } - } - - var uniqueMixinCount = 0; - function addMixin(tag, original, mixin){ - for (var z in mixin){ - original[z + ':__mixin__(' + (uniqueMixinCount++) + ')'] = xtag.applyPseudos(z, mixin[z], tag.pseudos); - } - } - - function resolveMixins(mixins, output){ - var index = mixins.length; - while (index--){ - output.unshift(mixins[index]); - if (xtag.mixins[mixins[index]].mixins) resolveMixins(xtag.mixins[mixins[index]].mixins, output); - } - return output; - } - - function applyMixins(tag) { - resolveMixins(tag.mixins, []).forEach(function(name){ - var mixin = xtag.mixins[name]; - for (var type in mixin) { - var item = mixin[type], - original = tag[type]; - if (!original) tag[type] = item; - else { - switch (type){ - case 'mixins': break; - case 'events': addMixin(tag, original, item); break; - case 'accessors': - case 'prototype': - for (var z in item) { - if (!original[z]) original[z] = item[z]; - else mergeMixin(tag, original[z], item[z], name); - } - break; - default: mergeMixin(tag, original, item, name); - } - } - } - }); - return tag; - } - -// Events - - function delegateAction(pseudo, event) { - var match, - target = event.target, - root = event.currentTarget; - while (!match && target && target != root) { - if (target.tagName && matchSelector.call(target, pseudo.value)) match = target; - target = target.parentNode; - } - if (!match && root.tagName && matchSelector.call(root, pseudo.value)) match = root; - return match ? pseudo.listener = pseudo.listener.bind(match) : null; - } - - function touchFilter(event){ - return event.button === 0; - } - - function writeProperty(key, event, base, desc){ - if (desc) event[key] = base[key]; - else Object.defineProperty(event, key, { - writable: true, - enumerable: true, - value: base[key] - }); - } - - var skipProps = {}; - for (var z in doc.createEvent('CustomEvent')) skipProps[z] = 1; - function inheritEvent(event, base){ - var desc = Object.getOwnPropertyDescriptor(event, 'target'); - for (var z in base) { - if (!skipProps[z]) writeProperty(z, event, base, desc); - } - event.baseEvent = base; - } - -// Accessors - - function modAttr(element, attr, name, value, method){ - attrProto[method].call(element, name, attr && attr.boolean ? '' : value); - } - - function syncAttr(element, attr, name, value, method){ - if (attr && (attr.property || attr.selector)) { - var nodes = attr.property ? [element.xtag[attr.property]] : attr.selector ? xtag.query(element, attr.selector) : [], - index = nodes.length; - while (index--) nodes[index][method](name, value); - } - } - - function attachProperties(tag, prop, z, accessor, attr, name){ - var key = z.split(':'), type = key[0]; - if (type == 'get') { - key[0] = prop; - tag.prototype[prop].get = xtag.applyPseudos(key.join(':'), accessor[z], tag.pseudos, accessor[z]); - } - else if (type == 'set') { - key[0] = prop; - var setter = tag.prototype[prop].set = xtag.applyPseudos(key.join(':'), attr ? function(value){ - var old, method = 'setAttribute'; - if (attr.boolean){ - value = !!value; - old = this.hasAttribute(name); - if (!value) method = 'removeAttribute'; - } - else { - value = attr.validate ? attr.validate.call(this, value) : value; - old = this.getAttribute(name); - } - modAttr(this, attr, name, value, method); - accessor[z].call(this, value, old); - syncAttr(this, attr, name, value, method); - } : accessor[z] ? function(value){ - accessor[z].call(this, value); - } : null, tag.pseudos, accessor[z]); - - if (attr) attr.setter = accessor[z]; - } - else tag.prototype[prop][z] = accessor[z]; - } - - function parseAccessor(tag, prop){ - tag.prototype[prop] = {}; - var accessor = tag.accessors[prop], - attr = accessor.attribute, - name; - - if (attr) { - name = attr.name = (attr ? (attr.name || prop.replace(regexCamelToDash, '$1-$2')) : prop).toLowerCase(); - attr.key = prop; - tag.attributes[name] = attr; - } - - for (var z in accessor) attachProperties(tag, prop, z, accessor, attr, name); - - if (attr) { - if (!tag.prototype[prop].get) { - var method = (attr.boolean ? 'has' : 'get') + 'Attribute'; - tag.prototype[prop].get = function(){ - return this[method](name); - }; - } - if (!tag.prototype[prop].set) tag.prototype[prop].set = function(value){ - value = attr.boolean ? !!value : attr.validate ? attr.validate.call(this, value) : value; - var method = attr.boolean ? (value ? 'setAttribute' : 'removeAttribute') : 'setAttribute'; - modAttr(this, attr, name, value, method); - syncAttr(this, attr, name, value, method); - }; - } - } - - var unwrapComment = /\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//; - function parseMultiline(fn){ - return typeof fn == 'function' ? unwrapComment.exec(fn.toString())[1] : fn; - } - -/*** X-Tag Object Definition ***/ - - var xtag = { - tags: {}, - defaultOptions: { - pseudos: [], - mixins: [], - events: {}, - methods: {}, - accessors: {}, - lifecycle: {}, - attributes: {}, - 'prototype': { - xtag: { - get: function(){ - return this.__xtag__ ? this.__xtag__ : (this.__xtag__ = { data: {} }); - } - } - } - }, - register: function (name, options) { - var _name; - if (typeof name == 'string') _name = name.toLowerCase(); - else throw 'First argument must be a Custom Element string name'; - xtag.tags[_name] = options || {}; - - var basePrototype = options.prototype; - delete options.prototype; - var tag = xtag.tags[_name].compiled = applyMixins(xtag.merge({}, xtag.defaultOptions, options)); - var proto = tag.prototype; - var lifecycle = tag.lifecycle; - - for (var z in tag.events) tag.events[z] = xtag.parseEvent(z, tag.events[z]); - for (z in lifecycle) lifecycle[z.split(':')[0]] = xtag.applyPseudos(z, lifecycle[z], tag.pseudos, lifecycle[z]); - for (z in tag.methods) proto[z.split(':')[0]] = { value: xtag.applyPseudos(z, tag.methods[z], tag.pseudos, tag.methods[z]), enumerable: true }; - for (z in tag.accessors) parseAccessor(tag, z); - - if (tag.shadow) tag.shadow = tag.shadow.nodeName ? tag.shadow : xtag.createFragment(tag.shadow); - if (tag.content) tag.content = tag.content.nodeName ? tag.content.innerHTML : parseMultiline(tag.content); - var created = lifecycle.created; - var finalized = lifecycle.finalized; - proto.createdCallback = { - enumerable: true, - value: function(){ - var element = this; - if (tag.shadow && hasShadow) this.createShadowRoot().appendChild(tag.shadow.cloneNode(true)); - if (tag.content) this.appendChild(document.createElement('div')).outerHTML = tag.content; - var output = created ? created.apply(this, arguments) : null; - xtag.addEvents(this, tag.events); - for (var name in tag.attributes) { - var attr = tag.attributes[name], - hasAttr = this.hasAttribute(name), - hasDefault = attr.def !== undefined; - if (hasAttr || attr.boolean || hasDefault) { - this[attr.key] = attr.boolean ? hasAttr : !hasAttr && hasDefault ? attr.def : this.getAttribute(name); - } - } - tag.pseudos.forEach(function(obj){ - obj.onAdd.call(element, obj); - }); - this.xtagComponentReady = true; - if (finalized) finalized.apply(this, arguments); - return output; - } - }; - - var inserted = lifecycle.inserted; - var removed = lifecycle.removed; - if (inserted || removed) { - proto.attachedCallback = { value: function(){ - if (removed) this.xtag.__parentNode__ = this.parentNode; - if (inserted) return inserted.apply(this, arguments); - }, enumerable: true }; - } - if (removed) { - proto.detachedCallback = { value: function(){ - var args = toArray(arguments); - args.unshift(this.xtag.__parentNode__); - var output = removed.apply(this, args); - delete this.xtag.__parentNode__; - return output; - }, enumerable: true }; - } - if (lifecycle.attributeChanged) proto.attributeChangedCallback = { value: lifecycle.attributeChanged, enumerable: true }; - - proto.setAttribute = { - writable: true, - enumerable: true, - value: function (name, value){ - var old; - var _name = name.toLowerCase(); - var attr = tag.attributes[_name]; - if (attr) { - old = this.getAttribute(_name); - value = attr.boolean ? '' : attr.validate ? attr.validate.call(this, value) : value; - } - modAttr(this, attr, _name, value, 'setAttribute'); - if (attr) { - if (attr.setter) attr.setter.call(this, attr.boolean ? true : value, old); - syncAttr(this, attr, _name, value, 'setAttribute'); - } - } - }; - - proto.removeAttribute = { - writable: true, - enumerable: true, - value: function (name){ - var _name = name.toLowerCase(); - var attr = tag.attributes[_name]; - var old = this.hasAttribute(_name); - modAttr(this, attr, _name, '', 'removeAttribute'); - if (attr) { - if (attr.setter) attr.setter.call(this, attr.boolean ? false : undefined, old); - syncAttr(this, attr, _name, '', 'removeAttribute'); - } - } - }; - - var definition = {}; - var instance = basePrototype instanceof win.HTMLElement; - var extended = tag['extends'] && (definition['extends'] = tag['extends']); - - if (basePrototype) Object.getOwnPropertyNames(basePrototype).forEach(function(z){ - var prop = proto[z]; - var desc = instance ? Object.getOwnPropertyDescriptor(basePrototype, z) : basePrototype[z]; - if (prop) { - for (var y in desc) { - if (typeof desc[y] == 'function' && prop[y]) prop[y] = xtag.wrap(desc[y], prop[y]); - else prop[y] = desc[y]; - } - } - proto[z] = prop || desc; - }); - - definition['prototype'] = Object.create( - extended ? Object.create(doc.createElement(extended).constructor).prototype : win.HTMLElement.prototype, - proto - ); - - return doc.registerElement(_name, definition); - }, - - /* Exposed Variables */ - - mixins: {}, - prefix: prefix, - captureEvents: { focus: 1, blur: 1, scroll: 1, DOMMouseScroll: 1 }, - customEvents: { - animationstart: { - attach: [prefix.dom + 'AnimationStart'] - }, - animationend: { - attach: [prefix.dom + 'AnimationEnd'] - }, - transitionend: { - attach: [prefix.dom + 'TransitionEnd'] - }, - move: { - attach: ['pointermove'] - }, - enter: { - attach: ['pointerenter'] - }, - leave: { - attach: ['pointerleave'] - }, - scrollwheel: { - attach: ['DOMMouseScroll', 'mousewheel'], - condition: function(event){ - event.delta = event.wheelDelta ? event.wheelDelta / 40 : Math.round(event.detail / 3.5 * -1); - return true; - } - }, - tap: { - attach: ['pointerdown', 'pointerup'], - condition: function(event, custom){ - if (event.type == 'pointerdown') { - custom.startX = event.clientX; - custom.startY = event.clientY; - } - else if (event.button === 0 && - Math.abs(custom.startX - event.clientX) < 10 && - Math.abs(custom.startY - event.clientY) < 10) return true; - } - }, - tapstart: { - attach: ['pointerdown'], - condition: touchFilter - }, - tapend: { - attach: ['pointerup'], - condition: touchFilter - }, - tapmove: { - attach: ['pointerdown'], - condition: function(event, custom){ - if (event.type == 'pointerdown') { - var listener = custom.listener.bind(this); - if (!custom.tapmoveListeners) custom.tapmoveListeners = xtag.addEvents(document, { - pointermove: listener, - pointerup: listener, - pointercancel: listener - }); - } - else if (event.type == 'pointerup' || event.type == 'pointercancel') { - xtag.removeEvents(document, custom.tapmoveListeners); - custom.tapmoveListeners = null; - } - return true; - } - }, - taphold: { - attach: ['pointerdown', 'pointerup'], - condition: function(event, custom){ - if (event.type == 'pointerdown') { - (custom.pointers = custom.pointers || {})[event.pointerId] = setTimeout( - xtag.fireEvent.bind(null, this, 'taphold'), - custom.duration || 1000 - ); - } - else if (event.type == 'pointerup') { - if (custom.pointers) { - clearTimeout(custom.pointers[event.pointerId]); - delete custom.pointers[event.pointerId]; - } - } - else return true; - } - } - }, - pseudos: { - __mixin__: {}, - mixins: { - onCompiled: function(fn, pseudo){ - var mixin = pseudo.source && pseudo.source.__mixin__ || pseudo.source; - if (mixin) switch (pseudo.value) { - case null: case '': case 'before': return function(){ - mixin.apply(this, arguments); - return fn.apply(this, arguments); - }; - case 'after': return function(){ - var returns = fn.apply(this, arguments); - mixin.apply(this, arguments); - return returns; - }; - case 'none': return fn; - } - else return fn; - } - }, - keypass: keypseudo, - keyfail: keypseudo, - delegate: { - action: delegateAction - }, - preventable: { - action: function (pseudo, event) { - return !event.defaultPrevented; - } - }, - duration: { - onAdd: function(pseudo){ - pseudo.source.duration = Number(pseudo.value); - } - }, - capture: { - onCompiled: function(fn, pseudo){ - if (pseudo.source) pseudo.source.capture = true; - } - } - }, - - /* UTILITIES */ - - clone: clone, - typeOf: typeOf, - toArray: toArray, - - wrap: function (original, fn) { - return function(){ - var output = original.apply(this, arguments); - fn.apply(this, arguments); - return output; - }; - }, - /* - Recursively merges one object with another. The first argument is the destination object, - all other objects passed in as arguments are merged from right to left, conflicts are overwritten - */ - merge: function(source, k, v){ - if (typeOf(k) == 'string') return mergeOne(source, k, v); - for (var i = 1, l = arguments.length; i < l; i++){ - var object = arguments[i]; - for (var key in object) mergeOne(source, key, object[key]); - } - return source; - }, - - /* - ----- This should be simplified! ----- - Generates a random ID string - */ - uid: function(){ - return Math.random().toString(36).substr(2,10); - }, - - /* DOM */ - - query: query, - - skipTransition: function(element, fn, bind){ - var prop = prefix.js + 'TransitionProperty'; - element.style[prop] = element.style.transitionProperty = 'none'; - var callback = fn ? fn.call(bind || element) : null; - return xtag.skipFrame(function(){ - element.style[prop] = element.style.transitionProperty = ''; - if (callback) callback.call(bind || element); - }); - }, - - requestFrame: (function(){ - var raf = win.requestAnimationFrame || - win[prefix.lowercase + 'RequestAnimationFrame'] || - function(fn){ return win.setTimeout(fn, 20); }; - return function(fn){ return raf(fn); }; - })(), - - cancelFrame: (function(){ - var cancel = win.cancelAnimationFrame || - win[prefix.lowercase + 'CancelAnimationFrame'] || - win.clearTimeout; - return function(id){ return cancel(id); }; - })(), - - skipFrame: function(fn){ - var id = xtag.requestFrame(function(){ id = xtag.requestFrame(fn); }); - return id; - }, - - matchSelector: function (element, selector) { - return matchSelector.call(element, selector); - }, - - set: function (element, method, value) { - element[method] = value; - if (window.CustomElements) CustomElements.upgradeAll(element); - }, - - innerHTML: function(el, html){ - xtag.set(el, 'innerHTML', html); - }, - - hasClass: function (element, klass) { - return element.className.split(' ').indexOf(klass.trim())>-1; - }, - - addClass: function (element, klass) { - var list = element.className.trim().split(' '); - klass.trim().split(' ').forEach(function (name) { - if (!~list.indexOf(name)) list.push(name); - }); - element.className = list.join(' ').trim(); - return element; - }, - - removeClass: function (element, klass) { - var classes = klass.trim().split(' '); - element.className = element.className.trim().split(' ').filter(function (name) { - return name && !~classes.indexOf(name); - }).join(' '); - return element; - }, - - toggleClass: function (element, klass) { - return xtag[xtag.hasClass(element, klass) ? 'removeClass' : 'addClass'].call(null, element, klass); - }, - - /* - Runs a query on only the children of an element - */ - queryChildren: function (element, selector) { - var id = element.id, - attr = '#' + (element.id = id || 'x_' + xtag.uid()) + ' > ', - parent = element.parentNode || !container.appendChild(element); - selector = attr + (selector + '').replace(regexReplaceCommas, ',' + attr); - var result = element.parentNode.querySelectorAll(selector); - if (!id) element.removeAttribute('id'); - if (!parent) container.removeChild(element); - return toArray(result); - }, - - /* - Creates a document fragment with the content passed in - content can be - a string of HTML, an element, or an array/collection of elements - */ - createFragment: function(content) { - var template = document.createElement('template'); - if (content) { - if (content.nodeName) toArray(arguments).forEach(function(e){ - template.content.appendChild(e); - }); - else template.innerHTML = parseMultiline(content); - } - return document.importNode(template.content, true); - }, - - /* - Removes an element from the DOM for more performant node manipulation. The element - is placed back into the DOM at the place it was taken from. - */ - manipulate: function(element, fn){ - var next = element.nextSibling, - parent = element.parentNode, - returned = fn.call(element) || element; - if (next) parent.insertBefore(returned, next); - else parent.appendChild(returned); - }, - - /* PSEUDOS */ - - applyPseudos: function(key, fn, target, source) { - var listener = fn, - pseudos = {}; - if (key.match(':')) { - var matches = [], - valueFlag = 0; - key.replace(regexPseudoParens, function(match){ - if (match == '(') return ++valueFlag == 1 ? '\u276A' : '('; - return !--valueFlag ? '\u276B' : ')'; - }).replace(regexPseudoCapture, function(z, name, value, solo){ - matches.push([name || solo, value]); - }); - var i = matches.length; - while (i--) parsePseudo(function(){ - var name = matches[i][0], - value = matches[i][1]; - if (!xtag.pseudos[name]) throw "pseudo not found: " + name + " " + value; - value = (value === '' || typeof value == 'undefined') ? null : value; - var pseudo = pseudos[i] = Object.create(xtag.pseudos[name]); - pseudo.key = key; - pseudo.name = name; - pseudo.value = value; - pseudo['arguments'] = (value || '').split(','); - pseudo.action = pseudo.action || trueop; - pseudo.source = source; - pseudo.onAdd = pseudo.onAdd || noop; - pseudo.onRemove = pseudo.onRemove || noop; - var original = pseudo.listener = listener; - listener = function(){ - var output = pseudo.action.apply(this, [pseudo].concat(toArray(arguments))); - if (output === null || output === false) return output; - output = pseudo.listener.apply(this, arguments); - pseudo.listener = original; - return output; - }; - if (!target) pseudo.onAdd.call(fn, pseudo); - else target.push(pseudo); - }); - } - for (var z in pseudos) { - if (pseudos[z].onCompiled) listener = pseudos[z].onCompiled(listener, pseudos[z]) || listener; - } - return listener; - }, - - removePseudos: function(target, pseudos){ - pseudos.forEach(function(obj){ - obj.onRemove.call(target, obj); - }); - }, - - /*** Events ***/ - - parseEvent: function(type, fn) { - var pseudos = type.split(':'), - key = pseudos.shift(), - custom = xtag.customEvents[key], - event = xtag.merge({ - type: key, - stack: noop, - condition: trueop, - capture: xtag.captureEvents[key], - attach: [], - _attach: [], - pseudos: '', - _pseudos: [], - onAdd: noop, - onRemove: noop - }, custom || {}); - event.attach = toArray(event.base || event.attach); - event.chain = key + (event.pseudos.length ? ':' + event.pseudos : '') + (pseudos.length ? ':' + pseudos.join(':') : ''); - var stack = xtag.applyPseudos(event.chain, fn, event._pseudos, event); - event.stack = function(e){ - e.currentTarget = e.currentTarget || this; - var detail = e.detail || {}; - if (!detail.__stack__) return stack.apply(this, arguments); - else if (detail.__stack__ == stack) { - e.stopPropagation(); - e.cancelBubble = true; - return stack.apply(this, arguments); - } - }; - event.listener = function(e){ - var args = toArray(arguments), - output = event.condition.apply(this, args.concat([event])); - if (!output) return output; - // The second condition in this IF is to address the following Blink regression: https://code.google.com/p/chromium/issues/detail?id=367537 - // Remove this when affected browser builds with this regression fall below 5% marketshare - if (e.type != key && (e.baseEvent && e.type != e.baseEvent.type)) { - xtag.fireEvent(e.target, key, { - baseEvent: e, - detail: output !== true && (output.__stack__ = stack) ? output : { __stack__: stack } - }); - } - else return event.stack.apply(this, args); - }; - event.attach.forEach(function(name) { - event._attach.push(xtag.parseEvent(name, event.listener)); - }); - return event; - }, - - addEvent: function (element, type, fn, capture) { - var event = typeof fn == 'function' ? xtag.parseEvent(type, fn) : fn; - event._pseudos.forEach(function(obj){ - obj.onAdd.call(element, obj); - }); - event._attach.forEach(function(obj) { - xtag.addEvent(element, obj.type, obj); - }); - event.onAdd.call(element, event, event.listener); - element.addEventListener(event.type, event.stack, capture || event.capture); - return event; - }, - - addEvents: function (element, obj) { - var events = {}; - for (var z in obj) { - events[z] = xtag.addEvent(element, z, obj[z]); - } - return events; - }, - - removeEvent: function (element, type, event) { - event = event || type; - event.onRemove.call(element, event, event.listener); - xtag.removePseudos(element, event._pseudos); - event._attach.forEach(function(obj) { - xtag.removeEvent(element, obj); - }); - element.removeEventListener(event.type, event.stack); - }, - - removeEvents: function(element, obj){ - for (var z in obj) xtag.removeEvent(element, obj[z]); - }, - - fireEvent: function(element, type, options){ - var event = doc.createEvent('CustomEvent'); - options = options || {}; - event.initCustomEvent(type, - options.bubbles !== false, - options.cancelable !== false, - options.detail - ); - if (options.baseEvent) inheritEvent(event, options.baseEvent); - element.dispatchEvent(event); - } - - }; - - if (typeof define === 'function' && define.amd) define(xtag); - else if (typeof module !== 'undefined' && module.exports) module.exports = xtag; - else win.xtag = xtag; - - doc.addEventListener('WebComponentsReady', function(){ - xtag.fireEvent(doc.body, 'DOMComponentsLoaded'); - }); - -})(); diff --git a/dist/x-tag-no-polyfills.min.js b/dist/x-tag-no-polyfills.min.js deleted file mode 100644 index 8fd82ad..0000000 --- a/dist/x-tag-no-polyfills.min.js +++ /dev/null @@ -1 +0,0 @@ -(function(){function t(t){var e=F.call(t);return S[e]||(S[e]=e.match(q)[1].toLowerCase())}function e(n,r){var a=e[r||t(n)];return a?a(n):n}function n(e){return R[t(e)]?[e]:Array.prototype.slice.call(e,0)}function r(t,e){return(e||D).length?n(t.querySelectorAll(e)):[]}function a(t){t()}function o(n,r,a){var o=t(a);return"object"==o&&"object"==t(n[r])?B.merge(n[r],a):n[r]=e(a,o),n}function i(t,e,n){var r,a={};for(var o in e)a[o.split(":")[0]]=o;for(o in n)r=a[o.split(":")[0]],"function"==typeof e[r]?(r.match(":mixins")||(e[r+":mixins"]=e[r],delete e[r],r+=":mixins"),e[r].__mixin__=B.applyPseudos(o+(o.match(":mixins")?"":":mixins"),n[o],t.pseudos,e[r].__mixin__)):(e[o]=n[o],delete e[r])}function s(t,e,n){for(var r in n)e[r+":__mixin__("+H++ +")"]=B.applyPseudos(r,n[r],t.pseudos)}function u(t,e){for(var n=t.length;n--;)e.unshift(t[n]),B.mixins[t[n]].mixins&&u(B.mixins[t[n]].mixins,e);return e}function c(t){return u(t.mixins,[]).forEach(function(e){var n=B.mixins[e];for(var r in n){var a=n[r],o=t[r];if(o)switch(r){case"mixins":break;case"events":s(t,o,a);break;case"accessors":case"prototype":for(var u in a)o[u]?i(t,o[u],a[u],e):o[u]=a[u];break;default:i(t,o,a,e)}else t[r]=a}}),t}function l(t,e){for(var n,r=e.target,a=e.currentTarget;!n&&r&&r!=a;)r.tagName&&T.call(r,t.value)&&(n=r),r=r.parentNode;return!n&&a.tagName&&T.call(a,t.value)&&(n=a),n?t.listener=t.listener.bind(n):null}function p(t){return 0===t.button}function d(t,e,n,r){r?e[t]=n[t]:Object.defineProperty(e,t,{writable:!0,enumerable:!0,value:n[t]})}function m(t,e){var n=Object.getOwnPropertyDescriptor(t,"target");for(var r in e)z[r]||d(r,t,e,n);t.baseEvent=e}function f(t,e,n,r,a){E[a].call(t,n,e&&e.boolean?"":r)}function v(t,e,n,r,a){if(e&&(e.property||e.selector))for(var o=e.property?[t.xtag[e.property]]:e.selector?B.query(t,e.selector):[],i=o.length;i--;)o[i][a](n,r)}function h(t,e,n,r,a,o){var i=n.split(":"),s=i[0];"get"==s?(i[0]=e,t.prototype[e].get=B.applyPseudos(i.join(":"),r[n],t.pseudos,r[n])):"set"==s?(i[0]=e,t.prototype[e].set=B.applyPseudos(i.join(":"),a?function(t){var e,i="setAttribute";a.boolean?(t=!!t,e=this.hasAttribute(o),t||(i="removeAttribute")):(t=a.validate?a.validate.call(this,t):t,e=this.getAttribute(o)),f(this,a,o,t,i),r[n].call(this,t,e),v(this,a,o,t,i)}:r[n]?function(t){r[n].call(this,t)}:null,t.pseudos,r[n]),a&&(a.setter=r[n])):t.prototype[e][n]=r[n]}function b(t,e){t.prototype[e]={};var n,r=t.accessors[e],a=r.attribute;a&&(n=a.name=(a?a.name||e.replace(N,"$1-$2"):e).toLowerCase(),a.key=e,t.attributes[n]=a);for(var o in r)h(t,e,o,r,a,n);if(a){if(!t.prototype[e].get){var i=(a.boolean?"has":"get")+"Attribute";t.prototype[e].get=function(){return this[i](n)}}t.prototype[e].set||(t.prototype[e].set=function(t){t=a.boolean?!!t:a.validate?a.validate.call(this,t):t;var e=a.boolean?t?"setAttribute":"removeAttribute":"setAttribute";f(this,a,n,t,e),v(this,a,n,t,e)})}}function y(t){return"function"==typeof t?Y.exec(""+t)[1]:t}var g=window,_=document,E={setAttribute:Element.prototype.setAttribute,removeAttribute:Element.prototype.removeAttribute},w=Element.prototype.createShadowRoot,A=_.createElement("div"),x=function(){},C=function(){return!0},k=/,/g,N=/([a-z])([A-Z])/g,O=/\(|\)/g,L=/:(\w+)\u276A(.+?(?=\u276B))|:(\w+)/g,j=/(\d+)/g,P={action:function(t,e){return t.value.match(j).indexOf(e.keyCode+"")>-1==("keypass"==t.name)||null}},M=function(){var t=Object.keys(window).join(),e=(t.match(/,(ms)/)||t.match(/,(moz)/)||t.match(/,(O)/)||[null,"webkit"])[1].toLowerCase();return{dom:"ms"==e?"MS":e,lowercase:e,css:"-"+e+"-",js:"ms"==e?e:e.charAt(0).toUpperCase()+e.substring(1)}}(),T=Element.prototype.matches||Element.prototype.matchesSelector||Element.prototype[M.lowercase+"MatchesSelector"],S={},F=S.toString,q=/\s([a-zA-Z]+)/;e.object=function(t){var n={};for(var r in t)n[r]=e(t[r]);return n},e.array=function(t){for(var n=t.length,r=Array(n);n--;)r[n]=e(t[n]);return r};var R={undefined:1,"null":1,number:1,"boolean":1,string:1,"function":1},D="",H=0,z={};for(var X in _.createEvent("CustomEvent"))z[X]=1;var Y=/\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//,B={tags:{},defaultOptions:{pseudos:[],mixins:[],events:{},methods:{},accessors:{},lifecycle:{},attributes:{},prototype:{xtag:{get:function(){return this.__xtag__?this.__xtag__:this.__xtag__={data:{}}}}}},register:function(t,e){var r;if("string"!=typeof t)throw"First argument must be a Custom Element string name";r=t.toLowerCase(),B.tags[r]=e||{};var a=e.prototype;delete e.prototype;var o=B.tags[r].compiled=c(B.merge({},B.defaultOptions,e)),i=o.prototype,s=o.lifecycle;for(var u in o.events)o.events[u]=B.parseEvent(u,o.events[u]);for(u in s)s[u.split(":")[0]]=B.applyPseudos(u,s[u],o.pseudos,s[u]);for(u in o.methods)i[u.split(":")[0]]={value:B.applyPseudos(u,o.methods[u],o.pseudos,o.methods[u]),enumerable:!0};for(u in o.accessors)b(o,u);o.shadow&&(o.shadow=o.shadow.nodeName?o.shadow:B.createFragment(o.shadow)),o.content&&(o.content=o.content.nodeName?o.content.innerHTML:y(o.content));var l=s.created,p=s.finalized;i.createdCallback={enumerable:!0,value:function(){var t=this;o.shadow&&w&&this.createShadowRoot().appendChild(o.shadow.cloneNode(!0)),o.content&&(this.appendChild(document.createElement("div")).outerHTML=o.content);var e=l?l.apply(this,arguments):null;B.addEvents(this,o.events);for(var n in o.attributes){var r=o.attributes[n],a=this.hasAttribute(n),i=void 0!==r.def;(a||r.boolean||i)&&(this[r.key]=r.boolean?a:!a&&i?r.def:this.getAttribute(n))}return o.pseudos.forEach(function(e){e.onAdd.call(t,e)}),this.xtagComponentReady=!0,p&&p.apply(this,arguments),e}};var d=s.inserted,m=s.removed;(d||m)&&(i.attachedCallback={value:function(){return m&&(this.xtag.__parentNode__=this.parentNode),d?d.apply(this,arguments):void 0},enumerable:!0}),m&&(i.detachedCallback={value:function(){var t=n(arguments);t.unshift(this.xtag.__parentNode__);var e=m.apply(this,t);return delete this.xtag.__parentNode__,e},enumerable:!0}),s.attributeChanged&&(i.attributeChangedCallback={value:s.attributeChanged,enumerable:!0}),i.setAttribute={writable:!0,enumerable:!0,value:function(t,e){var n,r=t.toLowerCase(),a=o.attributes[r];a&&(n=this.getAttribute(r),e=a.boolean?"":a.validate?a.validate.call(this,e):e),f(this,a,r,e,"setAttribute"),a&&(a.setter&&a.setter.call(this,a.boolean?!0:e,n),v(this,a,r,e,"setAttribute"))}},i.removeAttribute={writable:!0,enumerable:!0,value:function(t){var e=t.toLowerCase(),n=o.attributes[e],r=this.hasAttribute(e);f(this,n,e,"","removeAttribute"),n&&(n.setter&&n.setter.call(this,n.boolean?!1:void 0,r),v(this,n,e,"","removeAttribute"))}};var h={},E=a instanceof g.HTMLElement,A=o["extends"]&&(h["extends"]=o["extends"]);return a&&Object.getOwnPropertyNames(a).forEach(function(t){var e=i[t],n=E?Object.getOwnPropertyDescriptor(a,t):a[t];if(e)for(var r in n)e[r]="function"==typeof n[r]&&e[r]?B.wrap(n[r],e[r]):n[r];i[t]=e||n}),h.prototype=Object.create(A?Object.create(_.createElement(A).constructor).prototype:g.HTMLElement.prototype,i),_.registerElement(r,h)},mixins:{},prefix:M,captureEvents:{focus:1,blur:1,scroll:1,DOMMouseScroll:1},customEvents:{animationstart:{attach:[M.dom+"AnimationStart"]},animationend:{attach:[M.dom+"AnimationEnd"]},transitionend:{attach:[M.dom+"TransitionEnd"]},move:{attach:["pointermove"]},enter:{attach:["pointerenter"]},leave:{attach:["pointerleave"]},scrollwheel:{attach:["DOMMouseScroll","mousewheel"],condition:function(t){return t.delta=t.wheelDelta?t.wheelDelta/40:Math.round(-1*(t.detail/3.5)),!0}},tap:{attach:["pointerdown","pointerup"],condition:function(t,e){if("pointerdown"==t.type)e.startX=t.clientX,e.startY=t.clientY;else if(0===t.button&&10>Math.abs(e.startX-t.clientX)&&10>Math.abs(e.startY-t.clientY))return!0}},tapstart:{attach:["pointerdown"],condition:p},tapend:{attach:["pointerup"],condition:p},tapmove:{attach:["pointerdown"],condition:function(t,e){if("pointerdown"==t.type){var n=e.listener.bind(this);e.tapmoveListeners||(e.tapmoveListeners=B.addEvents(document,{pointermove:n,pointerup:n,pointercancel:n}))}else("pointerup"==t.type||"pointercancel"==t.type)&&(B.removeEvents(document,e.tapmoveListeners),e.tapmoveListeners=null);return!0}},taphold:{attach:["pointerdown","pointerup"],condition:function(t,e){if("pointerdown"==t.type)(e.pointers=e.pointers||{})[t.pointerId]=setTimeout(B.fireEvent.bind(null,this,"taphold"),e.duration||1e3);else{if("pointerup"!=t.type)return!0;e.pointers&&(clearTimeout(e.pointers[t.pointerId]),delete e.pointers[t.pointerId])}}}},pseudos:{__mixin__:{},mixins:{onCompiled:function(t,e){var n=e.source&&e.source.__mixin__||e.source;if(!n)return t;switch(e.value){case null:case"":case"before":return function(){return n.apply(this,arguments),t.apply(this,arguments)};case"after":return function(){var e=t.apply(this,arguments);return n.apply(this,arguments),e};case"none":return t}}},keypass:P,keyfail:P,delegate:{action:l},preventable:{action:function(t,e){return!e.defaultPrevented}},duration:{onAdd:function(t){t.source.duration=Number(t.value)}},capture:{onCompiled:function(t,e){e.source&&(e.source.capture=!0)}}},clone:e,typeOf:t,toArray:n,wrap:function(t,e){return function(){var n=t.apply(this,arguments);return e.apply(this,arguments),n}},merge:function(e,n,r){if("string"==t(n))return o(e,n,r);for(var a=1,i=arguments.length;i>a;a++){var s=arguments[a];for(var u in s)o(e,u,s[u])}return e},uid:function(){return Math.random().toString(36).substr(2,10)},query:r,skipTransition:function(t,e,n){var r=M.js+"TransitionProperty";t.style[r]=t.style.transitionProperty="none";var a=e?e.call(n||t):null;return B.skipFrame(function(){t.style[r]=t.style.transitionProperty="",a&&a.call(n||t)})},requestFrame:function(){var t=g.requestAnimationFrame||g[M.lowercase+"RequestAnimationFrame"]||function(t){return g.setTimeout(t,20)};return function(e){return t(e)}}(),cancelFrame:function(){var t=g.cancelAnimationFrame||g[M.lowercase+"CancelAnimationFrame"]||g.clearTimeout;return function(e){return t(e)}}(),skipFrame:function(t){var e=B.requestFrame(function(){e=B.requestFrame(t)});return e},matchSelector:function(t,e){return T.call(t,e)},set:function(t,e,n){t[e]=n,window.CustomElements&&CustomElements.upgradeAll(t)},innerHTML:function(t,e){B.set(t,"innerHTML",e)},hasClass:function(t,e){return t.className.split(" ").indexOf(e.trim())>-1},addClass:function(t,e){var n=t.className.trim().split(" ");return e.trim().split(" ").forEach(function(t){~n.indexOf(t)||n.push(t)}),t.className=n.join(" ").trim(),t},removeClass:function(t,e){var n=e.trim().split(" ");return t.className=t.className.trim().split(" ").filter(function(t){return t&&!~n.indexOf(t)}).join(" "),t},toggleClass:function(t,e){return B[B.hasClass(t,e)?"removeClass":"addClass"].call(null,t,e)},queryChildren:function(t,e){var r=t.id,a="#"+(t.id=r||"x_"+B.uid())+" > ",o=t.parentNode||!A.appendChild(t);e=a+(e+"").replace(k,","+a);var i=t.parentNode.querySelectorAll(e);return r||t.removeAttribute("id"),o||A.removeChild(t),n(i)},createFragment:function(t){var e=document.createElement("template");return t&&(t.nodeName?n(arguments).forEach(function(t){e.content.appendChild(t)}):e.innerHTML=y(t)),document.importNode(e.content,!0)},manipulate:function(t,e){var n=t.nextSibling,r=t.parentNode,a=e.call(t)||t;n?r.insertBefore(a,n):r.appendChild(a)},applyPseudos:function(t,e,r,o){var i=e,s={};if(t.match(":")){var u=[],c=0;t.replace(O,function(t){return"("==t?1==++c?"❪":"(":--c?")":"❫"}).replace(L,function(t,e,n,r){u.push([e||r,n])});for(var l=u.length;l--;)a(function(){var a=u[l][0],c=u[l][1];if(!B.pseudos[a])throw"pseudo not found: "+a+" "+c;c=""===c||c===void 0?null:c;var p=s[l]=Object.create(B.pseudos[a]);p.key=t,p.name=a,p.value=c,p.arguments=(c||"").split(","),p.action=p.action||C,p.source=o,p.onAdd=p.onAdd||x,p.onRemove=p.onRemove||x;var d=p.listener=i;i=function(){var t=p.action.apply(this,[p].concat(n(arguments)));return null===t||t===!1?t:(t=p.listener.apply(this,arguments),p.listener=d,t)},r?r.push(p):p.onAdd.call(e,p)})}for(var p in s)s[p].onCompiled&&(i=s[p].onCompiled(i,s[p])||i);return i},removePseudos:function(t,e){e.forEach(function(e){e.onRemove.call(t,e)})},parseEvent:function(t,e){var r=t.split(":"),a=r.shift(),o=B.customEvents[a],i=B.merge({type:a,stack:x,condition:C,capture:B.captureEvents[a],attach:[],_attach:[],pseudos:"",_pseudos:[],onAdd:x,onRemove:x},o||{});i.attach=n(i.base||i.attach),i.chain=a+(i.pseudos.length?":"+i.pseudos:"")+(r.length?":"+r.join(":"):"");var s=B.applyPseudos(i.chain,e,i._pseudos,i);return i.stack=function(t){t.currentTarget=t.currentTarget||this;var e=t.detail||{};return e.__stack__?e.__stack__==s?(t.stopPropagation(),t.cancelBubble=!0,s.apply(this,arguments)):void 0:s.apply(this,arguments)},i.listener=function(t){var e=n(arguments),r=i.condition.apply(this,e.concat([i]));return r?t.type!=a&&t.baseEvent&&t.type!=t.baseEvent.type?(B.fireEvent(t.target,a,{baseEvent:t,detail:r!==!0&&(r.__stack__=s)?r:{__stack__:s}}),void 0):i.stack.apply(this,e):r},i.attach.forEach(function(t){i._attach.push(B.parseEvent(t,i.listener))}),i},addEvent:function(t,e,n,r){var a="function"==typeof n?B.parseEvent(e,n):n;return a._pseudos.forEach(function(e){e.onAdd.call(t,e)}),a._attach.forEach(function(e){B.addEvent(t,e.type,e)}),a.onAdd.call(t,a,a.listener),t.addEventListener(a.type,a.stack,r||a.capture),a},addEvents:function(t,e){var n={};for(var r in e)n[r]=B.addEvent(t,r,e[r]);return n},removeEvent:function(t,e,n){n=n||e,n.onRemove.call(t,n,n.listener),B.removePseudos(t,n._pseudos),n._attach.forEach(function(e){B.removeEvent(t,e)}),t.removeEventListener(n.type,n.stack)},removeEvents:function(t,e){for(var n in e)B.removeEvent(t,e[n])},fireEvent:function(t,e,n){var r=_.createEvent("CustomEvent");n=n||{},r.initCustomEvent(e,n.bubbles!==!1,n.cancelable!==!1,n.detail),n.baseEvent&&m(r,n.baseEvent),t.dispatchEvent(r)}};"function"==typeof define&&define.amd?define(B):"undefined"!=typeof module&&module.exports?module.exports=B:g.xtag=B,_.addEventListener("WebComponentsReady",function(){B.fireEvent(_.body,"DOMComponentsLoaded")})})(); \ No newline at end of file diff --git a/dist/x-tag-polyfilled.js b/dist/x-tag-polyfilled.js new file mode 100644 index 0000000..f58c356 --- /dev/null +++ b/dist/x-tag-polyfilled.js @@ -0,0 +1,462 @@ +(function(){ + 'use strict';var h=new function(){};var aa=new Set("annotation-xml color-profile font-face font-face-src font-face-uri font-face-format font-face-name missing-glyph".split(" "));function k(b){var a=aa.has(b);b=/^[a-z][.0-9_a-z]*-[\-.0-9_a-z]*$/.test(b);return!a&&b}function l(b){var a=b.isConnected;if(void 0!==a)return a;for(;b&&!(b.__CE_isImportDocument||b instanceof Document);)b=b.parentNode||(window.ShadowRoot&&b instanceof ShadowRoot?b.host:void 0);return!(!b||!(b.__CE_isImportDocument||b instanceof Document))} + function m(b,a){for(;a&&a!==b&&!a.nextSibling;)a=a.parentNode;return a&&a!==b?a.nextSibling:null} + function n(b,a,e){e=e?e:new Set;for(var c=b;c;){if(c.nodeType===Node.ELEMENT_NODE){var d=c;a(d);var f=d.localName;if("link"===f&&"import"===d.getAttribute("rel")){c=d.import;if(c instanceof Node&&!e.has(c))for(e.add(c),c=c.firstChild;c;c=c.nextSibling)n(c,a,e);c=m(b,d);continue}else if("template"===f){c=m(b,d);continue}if(d=d.__CE_shadowRoot)for(d=d.firstChild;d;d=d.nextSibling)n(d,a,e)}c=c.firstChild?c.firstChild:m(b,c)}}function q(b,a,e){b[a]=e};function r(){this.a=new Map;this.m=new Map;this.f=[];this.b=!1}function ba(b,a,e){b.a.set(a,e);b.m.set(e.constructor,e)}function t(b,a){b.b=!0;b.f.push(a)}function v(b,a){b.b&&n(a,function(a){return w(b,a)})}function w(b,a){if(b.b&&!a.__CE_patched){a.__CE_patched=!0;for(var e=0;e "-" + c.toLowerCase(); + + function delegateAction(node, pseudo, event) { + var match, + target = event.target, + root = event.currentTarget; + while (!match && target && target != root) { + if (target.tagName && target.matches(pseudo.args)) match = target; + target = target.parentNode; + } + if (!match && root.tagName && root.matches(pseudo.args)) match = root; + if (match) pseudo.fn = pseudo.fn.bind(match); + else return null; + } + + var xtag = { + events: {}, + pseudos: { + delegate: { + onInvoke: delegateAction + } + }, + extensions: { + rxn: { + onParse (klass, prop, args, descriptor, key){ + delete klass.prototype[key]; + return false; + }, + onConstruct (node, property, args, descriptor){ + node.rxn(property, descriptor.value, !!args[1]); + } + }, + attr: { + mixin: (base) => class extends base { + attributeChangedCallback(attr, last, current){ + var desc = this.constructor.getOptions('attributes')[attr]; + if (desc && desc.set && !desc._skip) { + desc.set.call(this, current); + desc._skip = null; + } + } + }, + types: { + boolean: { + set: function(prop, val){ + val || val === '' ? this.setAttribute(prop, '') : this.removeAttribute(prop); + }, + get: function(prop){ + return this.hasAttribute(prop); + } + } + }, + onParse (klass, prop, args, descriptor, key){ + if (descriptor.value) throw 'Attribute accessor "'+ prop +'" was declared as a value, but must be declared as get or set'; + var _prop = prop.replace(regexCamel, dashLower); + klass.getOptions('attributes')[_prop] = descriptor; + var type = this.types[args[0]] || {}; + let descSet = descriptor.set; + let typeSet = type.set || HTMLElement.prototype.setAttribute; + descriptor.set = function(val){ + if (!descriptor._skip){ + descriptor._skip = true; + var output; + if (descSet) output = descSet.call(this, val); + typeSet.call(this, _prop, typeof output == 'undefined' ? val : output); + descriptor._skip = null; + } + } + let descGet = descriptor.get; + let typeGet = type.get || HTMLElement.prototype.getAttribute; + descriptor.get = function(){ + var output; + var val = typeGet.call(this, _prop); + if (descGet) output = descGet.call(this, val); + return typeof output == 'undefined' ? val : output; + } + delete klass.prototype[key]; + }, + onCompiled (klass){ + klass.observedAttributes = Object.keys(klass.getOptions('attributes')).concat(klass.observedAttributes || []) + } + }, + event: { + onParse (klass, property, args, descriptor, key){ + delete klass.prototype[key]; + return false; + }, + onConstruct (node, property, args, descriptor){ + xtag.addEvent(node, property, descriptor.value); + } + }, + template: { + throttle: { + frame: function (node, template, queued){ + queued.cancel = cancelAnimationFrame.bind(window, requestAnimationFrame(() => { + node._render(template, queued); + })) + }, + debounce: function (node, template, queued, options){ + queued.cancel = clearTimeout.bind(window, setTimeout(() => { + node_.render(template, queued); + }, options.throttle)) + } + }, + mixin: (base) => class extends base { + set 'template::attr' (name){ + this.render(name); + } + get templates (){ + return this.constructor.getOptions('templates'); + } + _render (template, queued){ + this.innerHTML = template.call(this); + this._XTagRender = null; + if (queued.resolve) queued.resolve(this); + } + render (name, options = {}){ + var _name = name || 'default'; + var template = this.templates[_name]; + if (!template) { + throw new ReferenceError('Template "' + _name + '" undefined for ' + this.nodeName); + } + var queued = this._XTagRender; + if (queued) { + if (queued.name === _name) return queued.promise; + else if (queued.cancel) queued.cancel(); + } + if (this.getAttribute('template') != _name) this.setAttribute('template', _name); + queued = this._XTagRender = { name: _name }; + var ext = xtag.extensions.template.throttle; + var throttle = (options.throttle ? ext[options.throttle] || ext.debounce : false); + if (throttle) { + return queued.promise = new Promise(resolve => { + queued.resolve = resolve; + throttle(this, template, queued, options); + }); + } + else { + this._render(template, queued); + return Promise.resolve(this); + } + } + }, + onParse (klass, property, args, descriptor){ + klass.getOptions('templates')[property || 'default'] = descriptor.value; + return false; + }, + onReady (node, resolve, property, args){ + if (args[0]) { + if (args[0] === 'ready') node.render(property); + else node.rxn('firstpaint', () => node.render(property)); + } + resolve(); + } + } + }, + create (name, klass){ + var c = klass || name; + c.options = Object.assign({}, c.options); + onParse(c); + if (klass && name) customElements.define(name, c); + return c; + }, + register (name, klass) { + customElements.define(name, klass); + }, + addEvents (node, events){ + let refs = {}; + for (let z in events) refs[z] = xtag.addEvent(node, z, events[z]); + return refs; + }, + addEvent (node, key, fn, options){ + var type; + var stack = fn; + var ref = options || {}; + ref.data = {}; + key.replace(regexParseExt, (match, name, dots, pseudo, args) => { + if (name) type = name; + else if (dots == ':'){ + var pseudo = xtag.pseudos[pseudo]; + var _args = args ? args.split(regexCommaArgs) : []; + stack = pseudoWrap(pseudo, _args, stack, ref); + if (pseudo.onParse) pseudo.onParse(node, type, _args, stack, ref); + } + }); + node.addEventListener(type, stack, ref); + ref.type = type; + ref.listener = stack; + var event = xtag.events[type]; + if (event) { + var listener = function(e){ + new Promise(resolve => { + event.onFilter ? event.onFilter(this, e, ref, resolve) : resolve(); + }).then(() => { + let fired = '_' + type + 'EventFired'; + if (!e[fired]) { + e[fired] = true; + xtag.fireEvent(e.target || this, type); + } + }) + } + ref.attached = event.attach.map(key => { + return xtag.addEvent(node, key, listener, {capture: true}); + }); + if (event.onAdd) event.onAdd(node, ref); + } + return ref; + }, + removeEvents (node, refs) { + for (let z in refs) xtag.removeEvent(node, refs[z]); + }, + removeEvent (node, ref){ + node.removeEventListener(ref.type, ref.listener, ref.capture); + var event = xtag.events[ref.type]; + if (event && event.onRemove) event.onRemove(node, ref); + if (ref.attached) ref.attached.forEach(attached => { xtag.removeEvent(node, ref) }) + }, + fireEvent (node, name, obj = {}){ + let options = Object.assign({ + bubbles: true, + cancelable: true + }, obj); + node.dispatchEvent(new CustomEvent(name, options)); + } + } + + var rxnID = 0; + function processRxns(node, type){ + var rxn = node.rxns[type]; + var queue = rxn.queue; + for (let z in queue) { + queue[z].fn.call(node); + if (rxn.singleton || !queue[z].recurring) delete queue[z]; + } + rxn.fired = true; + } + + function createClass(options = {}){ + var klass; + klass = class extends (options.native ? Object.getPrototypeOf(document.createElement(options.native)).constructor : HTMLElement) { + constructor () { + super(); + if (!this.rxns) this.rxns = { + ready: { queue: {}, singleton: true }, + firstpaint: { queue: {}, singleton: true }, + render: { queue: {} } + }; + onConstruct(this); + new Promise(resolve => onReady(this, resolve)).then(() => { + processRxns(this, 'ready') + if (this.readyCallback) this.readyCallback(); + }); + } + + connectedCallback () { + onConnect(this); + if (!this.rxns.firstpaint.frame) { + this.rxns.firstpaint.frame = requestAnimationFrame(() => processRxns(this, 'firstpaint')); + } + } + + rxn (type, fn, recurring){ + var rxn = this.rxns[type]; + if (rxn.singleton && rxn.fired) fn.call(this); + else { + rxn.queue[rxnID++] = { fn: fn, recurring: recurring }; + return rxnID; + } + } + + cancelRxn (type, id){ + delete this.rxns[type].queue[id]; + } + }; + + klass.options = { + extensions: {}, + pseudos: {} + }; + + klass.getOptions = function(name){ + return this.options[name] || (this.options[name] = Object.assign({}, Object.getPrototypeOf(this).options ? Object.getPrototypeOf(this).options[name] : {})); + } + + klass.extensions = function extensions(...extensions){ + var exts = this.getOptions('extensions'); + return extensions.reduce((current, extension) => { + var mixin; + var extended = current; + if (!exts[extension.name]) { + if (typeof extension == 'string') { + mixin = xtag.extensions[extension].mixin; + } + else { + mixin = extension.mixin; + exts[extension.name] = extension; + } + if (mixin) { + extended = mixin(current); + onParse(extended); + } + } + return extended; + }, this); + } + + klass.as = function(tag){ + return createClass({ + native: tag + }); + } + + return klass.extensions('attr', 'event', 'template'); + } + + XTagElement = createClass(); + + function pseudoWrap(pseudo, args, fn, detail){ + return function(){ + var _pseudo = { fn: fn, args: args, detail: detail }; + var output = pseudo.onInvoke(this, _pseudo, ...arguments); + if (output === null || output === false) return output; + return _pseudo.fn.apply(this, output instanceof Array ? output : arguments); + }; + } + + function onParse(target){ + var processedProps = {}; + var descriptors = getDescriptors(target); + var extensions = target.getOptions('extensions'); + var processed = target._processedExtensions = new Map(); + for (let z in descriptors) { + let matches = []; + let property; + let extension; + let extensionArgs = []; + let descriptor = descriptors[z]; + let pseudos = target._pseudos || xtag.pseudos; + z.replace(regexParseExt, function(){ matches.unshift(arguments); }); + matches.forEach(a => function(match, prop, dots, name, args){ + property = prop || property; + if (args) var _args = args.split(regexCommaArgs); + if (dots == '::') { + extensionArgs = _args || []; + extension = extensions[name] || xtag.extensions[name]; + if (!processed.get(extension)) processed.set(extension, []); + } + else if (!prop){ + let pseudo = pseudos[name]; + if (pseudo) { + for (let y in descriptor) { + let fn = descriptor[y]; + if (typeof fn == 'function' && pseudo.onInvoke) { + fn = descriptor[y] = pseudoWrap(pseudo, _args, fn); + if (pseudo.onParse) pseudo.onParse(target, property, _args, fn); + } + } + } + } + }.apply(null, a)); + let attachProperty; + if (extension) { + processed.get(extension).push([property, extensionArgs, descriptor]); + if (extension.onParse) attachProperty = extension.onParse(target, property, extensionArgs, descriptor, z); + } + if (!property) delete target.prototype[z]; + else if (attachProperty !== false) { + let prop = processedProps[property] || (processedProps[property] = {}); + for (let y in descriptor) prop[y] = descriptor[y]; + } + } + for (let ext of processed.keys()) { + if (ext.onCompiled) ext.onCompiled(target, processedProps); + } + Object.defineProperties(target.prototype, processedProps); + } + + function onConstruct (target){ + var processed = target.constructor._processedExtensions; + for (let [ext, items] of processed) { + if (ext.onConstruct) items.forEach(item => ext.onConstruct(target, ...item)) + } + } + + function onReady (target, resolve){ + var processed = target.constructor._processedExtensions; + for (let [ext, items] of processed) { + if (ext.onReady) Promise.all(items.map(item => { + return new Promise(resolve => ext.onReady(target, resolve, ...item)) + })).then(resolve) + } + } + + function onConnect (target){ + var processed = target.constructor._processedExtensions; + for (let [ext, items] of processed) { + if (ext.onConnect) items.forEach(item => ext.onConnect(target, ...item)) + } + } + + function getDescriptors(target){ + var descriptors = {}; + var proto = target.prototype; + Object.getOwnPropertyNames(proto).forEach(key => { + descriptors[key] = Object.getOwnPropertyDescriptor(proto, key); + }); + return descriptors; + } + + if (typeof define === 'function' && define.amd) { + define(xtag); + define(XTagElement); + } + else if (typeof module !== 'undefined' && module.exports) { + module.exports = { xtag: xtag, XTagElement: XTagElement }; + } + else { + window.xtag = xtag; + window.XTagElement = XTagElement; + } + +})(); \ No newline at end of file diff --git a/dist/x-tag-polyfilled.min.js b/dist/x-tag-polyfilled.min.js new file mode 100644 index 0000000..5dfb4a1 --- /dev/null +++ b/dist/x-tag-polyfilled.min.js @@ -0,0 +1,2 @@ +(function(){"use strict";var t=new function(){},e=new Set("annotation-xml color-profile font-face font-face-src font-face-uri font-face-format font-face-name missing-glyph".split(" "));function n(t){var n=e.has(t);return t=/^[a-z][.0-9_a-z]*-[\-.0-9_a-z]*$/.test(t),!n&&t}function o(t){var e=t.isConnected;if(void 0!==e)return e;for(;t&&!(t.__CE_isImportDocument||t instanceof Document);)t=t.parentNode||(window.ShadowRoot&&t instanceof ShadowRoot?t.host:void 0);return!(!t||!(t.__CE_isImportDocument||t instanceof Document))}function i(t,e){for(;e&&e!==t&&!e.nextSibling;)e=e.parentNode;return e&&e!==t?e.nextSibling:null}function r(t,e,n){n=n||new Set;for(var o=t;o;){if(o.nodeType===Node.ELEMENT_NODE){var a=o;e(a);var l=a.localName;if("link"===l&&"import"===a.getAttribute("rel")){if((o=a.import)instanceof Node&&!n.has(o))for(n.add(o),o=o.firstChild;o;o=o.nextSibling)r(o,e,n);o=i(t,a);continue}if("template"===l){o=i(t,a);continue}if(a=a.__CE_shadowRoot)for(a=a.firstChild;a;a=a.nextSibling)r(a,e,n)}o=o.firstChild?o.firstChild:i(t,o)}}function a(t,e,n){t[e]=n}function l(){this.a=new Map,this.m=new Map,this.f=[],this.b=!1}function c(t,e){t.b=!0,t.f.push(e)}function s(t,e){t.b&&r(e,function(e){return f(t,e)})}function f(t,e){if(t.b&&!e.__CE_patched){e.__CE_patched=!0;for(var n=0;n"-"+e.toLowerCase();var o={events:{},pseudos:{delegate:{onInvoke:function(e,t,n){for(var r,s=n.target,o=n.currentTarget;!r&&s&&s!=o;)s.tagName&&s.matches(t.args)&&(r=s),s=s.parentNode;if(!r&&o.tagName&&o.matches(t.args)&&(r=o),!r)return null;t.fn=t.fn.bind(r)}}},extensions:{rxn:{onParse:(e,t,n,r,s)=>(delete e.prototype[s],!1),onConstruct(e,t,n,r){e.rxn(t,r.value,!!n[1])}},attr:{mixin:e=>(class extends e{attributeChangedCallback(e,t,n){var r=this.constructor.getOptions("attributes")[e];r&&r.set&&!r._skip&&(r.set.call(this,n),r._skip=null)}}),types:{boolean:{set:function(e,t){t||""===t?this.setAttribute(e,""):this.removeAttribute(e)},get:function(e){return this.hasAttribute(e)}}},onParse(e,t,n,o,i){if(o.value)throw'Attribute accessor "'+t+'" was declared as a value, but must be declared as get or set';var a=t.replace(r,s);e.getOptions("attributes")[a]=o;var l=this.types[n[0]]||{};let c=o.set,u=l.set||HTMLElement.prototype.setAttribute;o.set=function(e){var t;o._skip||(o._skip=!0,c&&(t=c.call(this,e)),u.call(this,a,void 0===t?e:t),o._skip=null)};let d=o.get,p=l.get||HTMLElement.prototype.getAttribute;o.get=function(){var e,t=p.call(this,a);return d&&(e=d.call(this,t)),void 0===e?t:e},delete e.prototype[i]},onCompiled(e){e.observedAttributes=Object.keys(e.getOptions("attributes")).concat(e.observedAttributes||[])}},event:{onParse:(e,t,n,r,s)=>(delete e.prototype[s],!1),onConstruct(e,t,n,r){o.addEvent(e,t,r.value)}},template:{throttle:{frame:function(e,t,n){n.cancel=cancelAnimationFrame.bind(window,requestAnimationFrame(()=>{e._render(t,n)}))},debounce:function(e,t,n,r){n.cancel=clearTimeout.bind(window,setTimeout(()=>{node_.render(t,n)},r.throttle))}},mixin:e=>(class extends e{set"template::attr"(e){this.render(e)}get templates(){return this.constructor.getOptions("templates")}_render(e,t){this.innerHTML=e.call(this),this._XTagRender=null,t.resolve&&t.resolve(this)}render(e,t={}){var n=e||"default",r=this.templates[n];if(!r)throw new ReferenceError('Template "'+n+'" undefined for '+this.nodeName);var s=this._XTagRender;if(s){if(s.name===n)return s.promise;s.cancel&&s.cancel()}this.getAttribute("template")!=n&&this.setAttribute("template",n),s=this._XTagRender={name:n};var i=o.extensions.template.throttle,a=!!t.throttle&&(i[t.throttle]||i.debounce);return a?s.promise=new Promise(e=>{s.resolve=e,a(this,r,s,t)}):(this._render(r,s),Promise.resolve(this))}}),onParse:(e,t,n,r)=>(e.getOptions("templates")[t||"default"]=r.value,!1),onReady(e,t,n,r){r[0]&&("ready"===r[0]?e.render(n):e.rxn("firstpaint",()=>e.render(n))),t()}}},create(e,t){var n=t||e;return n.options=Object.assign({},n.options),c(n),t&&e&&customElements.define(e,n),n},register(e,t){customElements.define(e,t)},addEvents(e,t){let n={};for(let r in t)n[r]=o.addEvent(e,r,t[r]);return n},addEvent(e,r,s,i){var a,c=s,u=i||{};u.data={},r.replace(t,(t,r,s,i,d)=>{if(r)a=r;else if(":"==s){i=o.pseudos[i];var p=d?d.split(n):[];c=l(i,p,c,u),i.onParse&&i.onParse(e,a,p,c,u)}}),e.addEventListener(a,c,u),u.type=a,u.listener=c;var d=o.events[a];if(d){var p=function(e){new Promise(t=>{d.onFilter?d.onFilter(this,e,u,t):t()}).then(()=>{let t="_"+a+"EventFired";e[t]||(e[t]=!0,o.fireEvent(e.target||this,a))})};u.attached=d.attach.map(t=>o.addEvent(e,t,p,{capture:!0})),d.onAdd&&d.onAdd(e,u)}return u},removeEvents(e,t){for(let n in t)o.removeEvent(e,t[n])},removeEvent(e,t){e.removeEventListener(t.type,t.listener,t.capture);var n=o.events[t.type];n&&n.onRemove&&n.onRemove(e,t),t.attached&&t.attached.forEach(n=>{o.removeEvent(e,t)})},fireEvent(e,t,n={}){let r=Object.assign({bubbles:!0,cancelable:!0},n);e.dispatchEvent(new CustomEvent(t,r))}},i=0;function a(e,t){var n=e.rxns[t],r=n.queue;for(let t in r)r[t].fn.call(e),!n.singleton&&r[t].recurring||delete r[t];n.fired=!0}function l(e,t,n,r){return function(){var s={fn:n,args:t,detail:r},o=e.onInvoke(this,s,...arguments);return null===o||!1===o?o:s.fn.apply(this,o instanceof Array?o:arguments)}}function c(e){var r={},s=function(e){var t={},n=e.prototype;return Object.getOwnPropertyNames(n).forEach(e=>{t[e]=Object.getOwnPropertyDescriptor(n,e)}),t}(e),i=e.getOptions("extensions"),a=e._processedExtensions=new Map;for(let c in s){let u,d,p,f=[],m=[],h=s[c],v=e._pseudos||o.pseudos;if(c.replace(t,function(){f.unshift(arguments)}),f.forEach(t=>(function(t,r,s,c,p){if(u=r||u,p)var f=p.split(n);if("::"==s)m=f||[],d=i[c]||o.extensions[c],a.get(d)||a.set(d,[]);else if(!r){let t=v[c];if(t)for(let n in h){let r=h[n];"function"==typeof r&&t.onInvoke&&(r=h[n]=l(t,f,r),t.onParse&&t.onParse(e,u,f,r))}}}).apply(null,t)),d&&(a.get(d).push([u,m,h]),d.onParse&&(p=d.onParse(e,u,m,h,c))),u){if(!1!==p){let e=r[u]||(r[u]={});for(let t in h)e[t]=h[t]}}else delete e.prototype[c]}for(let t of a.keys())t.onCompiled&&t.onCompiled(e,r);Object.defineProperties(e.prototype,r)}XTagElement=function e(t={}){var n;return(n=class extends(t.native?Object.getPrototypeOf(document.createElement(t.native)).constructor:HTMLElement){constructor(){super(),this.rxns||(this.rxns={ready:{queue:{},singleton:!0},firstpaint:{queue:{},singleton:!0},render:{queue:{}}}),function(e){var t=e.constructor._processedExtensions;for(let[n,r]of t)n.onConstruct&&r.forEach(t=>n.onConstruct(e,...t))}(this),new Promise(e=>(function(e,t){var n=e.constructor._processedExtensions;for(let[r,s]of n)r.onReady&&Promise.all(s.map(t=>new Promise(n=>r.onReady(e,n,...t)))).then(t)})(this,e)).then(()=>{a(this,"ready"),this.readyCallback&&this.readyCallback()})}connectedCallback(){!function(e){var t=e.constructor._processedExtensions;for(let[n,r]of t)n.onConnect&&r.forEach(t=>n.onConnect(e,...t))}(this),this.rxns.firstpaint.frame||(this.rxns.firstpaint.frame=requestAnimationFrame(()=>a(this,"firstpaint")))}rxn(e,t,n){var r=this.rxns[e];if(!r.singleton||!r.fired)return r.queue[i++]={fn:t,recurring:n},i;t.call(this)}cancelRxn(e,t){delete this.rxns[e].queue[t]}}).options={extensions:{},pseudos:{}},n.getOptions=function(e){return this.options[e]||(this.options[e]=Object.assign({},Object.getPrototypeOf(this).options?Object.getPrototypeOf(this).options[e]:{}))},n.extensions=function(...e){var t=this.getOptions("extensions");return e.reduce((e,n)=>{var r,s=e;return t[n.name]||("string"==typeof n?r=o.extensions[n].mixin:(r=n.mixin,t[n.name]=n),r&&c(s=r(e))),s},this)},n.as=function(t){return e({native:t})},n.extensions("attr","event","template")}(),"function"==typeof define&&define.amd?(define(o),define(XTagElement)):"undefined"!=typeof module&&module.exports?module.exports={xtag:o,XTagElement:XTagElement}:(window.xtag=o,window.XTagElement=XTagElement)}(); \ No newline at end of file diff --git a/dist/x-tag-raw.js b/dist/x-tag-raw.js new file mode 100644 index 0000000..5682d97 --- /dev/null +++ b/dist/x-tag-raw.js @@ -0,0 +1,432 @@ +(function(){ + + var docElement = document.documentElement; + (Element.prototype.matches || (Element.prototype.matches = docElement.webkitMatchesSelector || + docElement.msMatchesSelector || + docElement.oMatchesSelector)) + + var regexParseExt = /([\w\-]+)|(::|:)(\w+)(?:\((.+?(?=\)))\))?/g; + var regexCommaArgs = /,\s*/; + var regexCamel = /[A-Z]/g; + var dashLower = c => "-" + c.toLowerCase(); + + function delegateAction(node, pseudo, event) { + var match, + target = event.target, + root = event.currentTarget; + while (!match && target && target != root) { + if (target.tagName && target.matches(pseudo.args)) match = target; + target = target.parentNode; + } + if (!match && root.tagName && root.matches(pseudo.args)) match = root; + if (match) pseudo.fn = pseudo.fn.bind(match); + else return null; + } + + var xtag = { + events: {}, + pseudos: { + delegate: { + onInvoke: delegateAction + } + }, + extensions: { + rxn: { + onParse (klass, prop, args, descriptor, key){ + delete klass.prototype[key]; + return false; + }, + onConstruct (node, property, args, descriptor){ + node.rxn(property, descriptor.value, !!args[1]); + } + }, + attr: { + mixin: (base) => class extends base { + attributeChangedCallback(attr, last, current){ + var desc = this.constructor.getOptions('attributes')[attr]; + if (desc && desc.set && !desc._skip) { + desc.set.call(this, current); + desc._skip = null; + } + } + }, + types: { + boolean: { + set: function(prop, val){ + val || val === '' ? this.setAttribute(prop, '') : this.removeAttribute(prop); + }, + get: function(prop){ + return this.hasAttribute(prop); + } + } + }, + onParse (klass, prop, args, descriptor, key){ + if (descriptor.value) throw 'Attribute accessor "'+ prop +'" was declared as a value, but must be declared as get or set'; + var _prop = prop.replace(regexCamel, dashLower); + klass.getOptions('attributes')[_prop] = descriptor; + var type = this.types[args[0]] || {}; + let descSet = descriptor.set; + let typeSet = type.set || HTMLElement.prototype.setAttribute; + descriptor.set = function(val){ + if (!descriptor._skip){ + descriptor._skip = true; + var output; + if (descSet) output = descSet.call(this, val); + typeSet.call(this, _prop, typeof output == 'undefined' ? val : output); + descriptor._skip = null; + } + } + let descGet = descriptor.get; + let typeGet = type.get || HTMLElement.prototype.getAttribute; + descriptor.get = function(){ + var output; + var val = typeGet.call(this, _prop); + if (descGet) output = descGet.call(this, val); + return typeof output == 'undefined' ? val : output; + } + delete klass.prototype[key]; + }, + onCompiled (klass){ + klass.observedAttributes = Object.keys(klass.getOptions('attributes')).concat(klass.observedAttributes || []) + } + }, + event: { + onParse (klass, property, args, descriptor, key){ + delete klass.prototype[key]; + return false; + }, + onConstruct (node, property, args, descriptor){ + xtag.addEvent(node, property, descriptor.value); + } + }, + template: { + throttle: { + frame: function (node, template, queued){ + queued.cancel = cancelAnimationFrame.bind(window, requestAnimationFrame(() => { + node._render(template, queued); + })) + }, + debounce: function (node, template, queued, options){ + queued.cancel = clearTimeout.bind(window, setTimeout(() => { + node_.render(template, queued); + }, options.throttle)) + } + }, + mixin: (base) => class extends base { + set 'template::attr' (name){ + this.render(name); + } + get templates (){ + return this.constructor.getOptions('templates'); + } + _render (template, queued){ + this.innerHTML = template.call(this); + this._XTagRender = null; + if (queued.resolve) queued.resolve(this); + } + render (name, options = {}){ + var _name = name || 'default'; + var template = this.templates[_name]; + if (!template) { + throw new ReferenceError('Template "' + _name + '" undefined for ' + this.nodeName); + } + var queued = this._XTagRender; + if (queued) { + if (queued.name === _name) return queued.promise; + else if (queued.cancel) queued.cancel(); + } + if (this.getAttribute('template') != _name) this.setAttribute('template', _name); + queued = this._XTagRender = { name: _name }; + var ext = xtag.extensions.template.throttle; + var throttle = (options.throttle ? ext[options.throttle] || ext.debounce : false); + if (throttle) { + return queued.promise = new Promise(resolve => { + queued.resolve = resolve; + throttle(this, template, queued, options); + }); + } + else { + this._render(template, queued); + return Promise.resolve(this); + } + } + }, + onParse (klass, property, args, descriptor){ + klass.getOptions('templates')[property || 'default'] = descriptor.value; + return false; + }, + onReady (node, resolve, property, args){ + if (args[0]) { + if (args[0] === 'ready') node.render(property); + else node.rxn('firstpaint', () => node.render(property)); + } + resolve(); + } + } + }, + create (name, klass){ + var c = klass || name; + c.options = Object.assign({}, c.options); + onParse(c); + if (klass && name) customElements.define(name, c); + return c; + }, + register (name, klass) { + customElements.define(name, klass); + }, + addEvents (node, events){ + let refs = {}; + for (let z in events) refs[z] = xtag.addEvent(node, z, events[z]); + return refs; + }, + addEvent (node, key, fn, options){ + var type; + var stack = fn; + var ref = options || {}; + ref.data = {}; + key.replace(regexParseExt, (match, name, dots, pseudo, args) => { + if (name) type = name; + else if (dots == ':'){ + var pseudo = xtag.pseudos[pseudo]; + var _args = args ? args.split(regexCommaArgs) : []; + stack = pseudoWrap(pseudo, _args, stack, ref); + if (pseudo.onParse) pseudo.onParse(node, type, _args, stack, ref); + } + }); + node.addEventListener(type, stack, ref); + ref.type = type; + ref.listener = stack; + var event = xtag.events[type]; + if (event) { + var listener = function(e){ + new Promise(resolve => { + event.onFilter ? event.onFilter(this, e, ref, resolve) : resolve(); + }).then(() => { + let fired = '_' + type + 'EventFired'; + if (!e[fired]) { + e[fired] = true; + xtag.fireEvent(e.target || this, type); + } + }) + } + ref.attached = event.attach.map(key => { + return xtag.addEvent(node, key, listener, {capture: true}); + }); + if (event.onAdd) event.onAdd(node, ref); + } + return ref; + }, + removeEvents (node, refs) { + for (let z in refs) xtag.removeEvent(node, refs[z]); + }, + removeEvent (node, ref){ + node.removeEventListener(ref.type, ref.listener, ref.capture); + var event = xtag.events[ref.type]; + if (event && event.onRemove) event.onRemove(node, ref); + if (ref.attached) ref.attached.forEach(attached => { xtag.removeEvent(node, ref) }) + }, + fireEvent (node, name, obj = {}){ + let options = Object.assign({ + bubbles: true, + cancelable: true + }, obj); + node.dispatchEvent(new CustomEvent(name, options)); + } + } + + var rxnID = 0; + function processRxns(node, type){ + var rxn = node.rxns[type]; + var queue = rxn.queue; + for (let z in queue) { + queue[z].fn.call(node); + if (rxn.singleton || !queue[z].recurring) delete queue[z]; + } + rxn.fired = true; + } + + function createClass(options = {}){ + var klass; + klass = class extends (options.native ? Object.getPrototypeOf(document.createElement(options.native)).constructor : HTMLElement) { + constructor () { + super(); + if (!this.rxns) this.rxns = { + ready: { queue: {}, singleton: true }, + firstpaint: { queue: {}, singleton: true }, + render: { queue: {} } + }; + onConstruct(this); + new Promise(resolve => onReady(this, resolve)).then(() => { + processRxns(this, 'ready') + if (this.readyCallback) this.readyCallback(); + }); + } + + connectedCallback () { + onConnect(this); + if (!this.rxns.firstpaint.frame) { + this.rxns.firstpaint.frame = requestAnimationFrame(() => processRxns(this, 'firstpaint')); + } + } + + rxn (type, fn, recurring){ + var rxn = this.rxns[type]; + if (rxn.singleton && rxn.fired) fn.call(this); + else { + rxn.queue[rxnID++] = { fn: fn, recurring: recurring }; + return rxnID; + } + } + + cancelRxn (type, id){ + delete this.rxns[type].queue[id]; + } + }; + + klass.options = { + extensions: {}, + pseudos: {} + }; + + klass.getOptions = function(name){ + return this.options[name] || (this.options[name] = Object.assign({}, Object.getPrototypeOf(this).options ? Object.getPrototypeOf(this).options[name] : {})); + } + + klass.extensions = function extensions(...extensions){ + var exts = this.getOptions('extensions'); + return extensions.reduce((current, extension) => { + var mixin; + var extended = current; + if (!exts[extension.name]) { + if (typeof extension == 'string') { + mixin = xtag.extensions[extension].mixin; + } + else { + mixin = extension.mixin; + exts[extension.name] = extension; + } + if (mixin) { + extended = mixin(current); + onParse(extended); + } + } + return extended; + }, this); + } + + klass.as = function(tag){ + return createClass({ + native: tag + }); + } + + return klass.extensions('attr', 'event', 'template'); + } + + XTagElement = createClass(); + + function pseudoWrap(pseudo, args, fn, detail){ + return function(){ + var _pseudo = { fn: fn, args: args, detail: detail }; + var output = pseudo.onInvoke(this, _pseudo, ...arguments); + if (output === null || output === false) return output; + return _pseudo.fn.apply(this, output instanceof Array ? output : arguments); + }; + } + + function onParse(target){ + var processedProps = {}; + var descriptors = getDescriptors(target); + var extensions = target.getOptions('extensions'); + var processed = target._processedExtensions = new Map(); + for (let z in descriptors) { + let matches = []; + let property; + let extension; + let extensionArgs = []; + let descriptor = descriptors[z]; + let pseudos = target._pseudos || xtag.pseudos; + z.replace(regexParseExt, function(){ matches.unshift(arguments); }); + matches.forEach(a => function(match, prop, dots, name, args){ + property = prop || property; + if (args) var _args = args.split(regexCommaArgs); + if (dots == '::') { + extensionArgs = _args || []; + extension = extensions[name] || xtag.extensions[name]; + if (!processed.get(extension)) processed.set(extension, []); + } + else if (!prop){ + let pseudo = pseudos[name]; + if (pseudo) { + for (let y in descriptor) { + let fn = descriptor[y]; + if (typeof fn == 'function' && pseudo.onInvoke) { + fn = descriptor[y] = pseudoWrap(pseudo, _args, fn); + if (pseudo.onParse) pseudo.onParse(target, property, _args, fn); + } + } + } + } + }.apply(null, a)); + let attachProperty; + if (extension) { + processed.get(extension).push([property, extensionArgs, descriptor]); + if (extension.onParse) attachProperty = extension.onParse(target, property, extensionArgs, descriptor, z); + } + if (!property) delete target.prototype[z]; + else if (attachProperty !== false) { + let prop = processedProps[property] || (processedProps[property] = {}); + for (let y in descriptor) prop[y] = descriptor[y]; + } + } + for (let ext of processed.keys()) { + if (ext.onCompiled) ext.onCompiled(target, processedProps); + } + Object.defineProperties(target.prototype, processedProps); + } + + function onConstruct (target){ + var processed = target.constructor._processedExtensions; + for (let [ext, items] of processed) { + if (ext.onConstruct) items.forEach(item => ext.onConstruct(target, ...item)) + } + } + + function onReady (target, resolve){ + var processed = target.constructor._processedExtensions; + for (let [ext, items] of processed) { + if (ext.onReady) Promise.all(items.map(item => { + return new Promise(resolve => ext.onReady(target, resolve, ...item)) + })).then(resolve) + } + } + + function onConnect (target){ + var processed = target.constructor._processedExtensions; + for (let [ext, items] of processed) { + if (ext.onConnect) items.forEach(item => ext.onConnect(target, ...item)) + } + } + + function getDescriptors(target){ + var descriptors = {}; + var proto = target.prototype; + Object.getOwnPropertyNames(proto).forEach(key => { + descriptors[key] = Object.getOwnPropertyDescriptor(proto, key); + }); + return descriptors; + } + + if (typeof define === 'function' && define.amd) { + define(xtag); + define(XTagElement); + } + else if (typeof module !== 'undefined' && module.exports) { + module.exports = { xtag: xtag, XTagElement: XTagElement }; + } + else { + window.xtag = xtag; + window.XTagElement = XTagElement; + } + +})(); \ No newline at end of file diff --git a/dist/x-tag-raw.min.js b/dist/x-tag-raw.min.js new file mode 100644 index 0000000..6a52f2b --- /dev/null +++ b/dist/x-tag-raw.min.js @@ -0,0 +1 @@ +!function(){var e=document.documentElement;Element.prototype.matches||(Element.prototype.matches=e.webkitMatchesSelector||e.msMatchesSelector||e.oMatchesSelector);var t=/([\w\-]+)|(::|:)(\w+)(?:\((.+?(?=\)))\))?/g,n=/,\s*/,r=/[A-Z]/g,s=e=>"-"+e.toLowerCase();var o={events:{},pseudos:{delegate:{onInvoke:function(e,t,n){for(var r,s=n.target,o=n.currentTarget;!r&&s&&s!=o;)s.tagName&&s.matches(t.args)&&(r=s),s=s.parentNode;if(!r&&o.tagName&&o.matches(t.args)&&(r=o),!r)return null;t.fn=t.fn.bind(r)}}},extensions:{rxn:{onParse:(e,t,n,r,s)=>(delete e.prototype[s],!1),onConstruct(e,t,n,r){e.rxn(t,r.value,!!n[1])}},attr:{mixin:e=>(class extends e{attributeChangedCallback(e,t,n){var r=this.constructor.getOptions("attributes")[e];r&&r.set&&!r._skip&&(r.set.call(this,n),r._skip=null)}}),types:{boolean:{set:function(e,t){t||""===t?this.setAttribute(e,""):this.removeAttribute(e)},get:function(e){return this.hasAttribute(e)}}},onParse(e,t,n,o,i){if(o.value)throw'Attribute accessor "'+t+'" was declared as a value, but must be declared as get or set';var a=t.replace(r,s);e.getOptions("attributes")[a]=o;var l=this.types[n[0]]||{};let c=o.set,u=l.set||HTMLElement.prototype.setAttribute;o.set=function(e){var t;o._skip||(o._skip=!0,c&&(t=c.call(this,e)),u.call(this,a,void 0===t?e:t),o._skip=null)};let d=o.get,p=l.get||HTMLElement.prototype.getAttribute;o.get=function(){var e,t=p.call(this,a);return d&&(e=d.call(this,t)),void 0===e?t:e},delete e.prototype[i]},onCompiled(e){e.observedAttributes=Object.keys(e.getOptions("attributes")).concat(e.observedAttributes||[])}},event:{onParse:(e,t,n,r,s)=>(delete e.prototype[s],!1),onConstruct(e,t,n,r){o.addEvent(e,t,r.value)}},template:{throttle:{frame:function(e,t,n){n.cancel=cancelAnimationFrame.bind(window,requestAnimationFrame(()=>{e._render(t,n)}))},debounce:function(e,t,n,r){n.cancel=clearTimeout.bind(window,setTimeout(()=>{node_.render(t,n)},r.throttle))}},mixin:e=>(class extends e{set"template::attr"(e){this.render(e)}get templates(){return this.constructor.getOptions("templates")}_render(e,t){this.innerHTML=e.call(this),this._XTagRender=null,t.resolve&&t.resolve(this)}render(e,t={}){var n=e||"default",r=this.templates[n];if(!r)throw new ReferenceError('Template "'+n+'" undefined for '+this.nodeName);var s=this._XTagRender;if(s){if(s.name===n)return s.promise;s.cancel&&s.cancel()}this.getAttribute("template")!=n&&this.setAttribute("template",n),s=this._XTagRender={name:n};var i=o.extensions.template.throttle,a=!!t.throttle&&(i[t.throttle]||i.debounce);return a?s.promise=new Promise(e=>{s.resolve=e,a(this,r,s,t)}):(this._render(r,s),Promise.resolve(this))}}),onParse:(e,t,n,r)=>(e.getOptions("templates")[t||"default"]=r.value,!1),onReady(e,t,n,r){r[0]&&("ready"===r[0]?e.render(n):e.rxn("firstpaint",()=>e.render(n))),t()}}},create(e,t){var n=t||e;return n.options=Object.assign({},n.options),c(n),t&&e&&customElements.define(e,n),n},register(e,t){customElements.define(e,t)},addEvents(e,t){let n={};for(let r in t)n[r]=o.addEvent(e,r,t[r]);return n},addEvent(e,r,s,i){var a,c=s,u=i||{};u.data={},r.replace(t,(t,r,s,i,d)=>{if(r)a=r;else if(":"==s){i=o.pseudos[i];var p=d?d.split(n):[];c=l(i,p,c,u),i.onParse&&i.onParse(e,a,p,c,u)}}),e.addEventListener(a,c,u),u.type=a,u.listener=c;var d=o.events[a];if(d){var p=function(e){new Promise(t=>{d.onFilter?d.onFilter(this,e,u,t):t()}).then(()=>{let t="_"+a+"EventFired";e[t]||(e[t]=!0,o.fireEvent(e.target||this,a))})};u.attached=d.attach.map(t=>o.addEvent(e,t,p,{capture:!0})),d.onAdd&&d.onAdd(e,u)}return u},removeEvents(e,t){for(let n in t)o.removeEvent(e,t[n])},removeEvent(e,t){e.removeEventListener(t.type,t.listener,t.capture);var n=o.events[t.type];n&&n.onRemove&&n.onRemove(e,t),t.attached&&t.attached.forEach(n=>{o.removeEvent(e,t)})},fireEvent(e,t,n={}){let r=Object.assign({bubbles:!0,cancelable:!0},n);e.dispatchEvent(new CustomEvent(t,r))}},i=0;function a(e,t){var n=e.rxns[t],r=n.queue;for(let t in r)r[t].fn.call(e),!n.singleton&&r[t].recurring||delete r[t];n.fired=!0}function l(e,t,n,r){return function(){var s={fn:n,args:t,detail:r},o=e.onInvoke(this,s,...arguments);return null===o||!1===o?o:s.fn.apply(this,o instanceof Array?o:arguments)}}function c(e){var r={},s=function(e){var t={},n=e.prototype;return Object.getOwnPropertyNames(n).forEach(e=>{t[e]=Object.getOwnPropertyDescriptor(n,e)}),t}(e),i=e.getOptions("extensions"),a=e._processedExtensions=new Map;for(let c in s){let u,d,p,f=[],m=[],h=s[c],v=e._pseudos||o.pseudos;if(c.replace(t,function(){f.unshift(arguments)}),f.forEach(t=>(function(t,r,s,c,p){if(u=r||u,p)var f=p.split(n);if("::"==s)m=f||[],d=i[c]||o.extensions[c],a.get(d)||a.set(d,[]);else if(!r){let t=v[c];if(t)for(let n in h){let r=h[n];"function"==typeof r&&t.onInvoke&&(r=h[n]=l(t,f,r),t.onParse&&t.onParse(e,u,f,r))}}}).apply(null,t)),d&&(a.get(d).push([u,m,h]),d.onParse&&(p=d.onParse(e,u,m,h,c))),u){if(!1!==p){let e=r[u]||(r[u]={});for(let t in h)e[t]=h[t]}}else delete e.prototype[c]}for(let t of a.keys())t.onCompiled&&t.onCompiled(e,r);Object.defineProperties(e.prototype,r)}XTagElement=function e(t={}){var n;return(n=class extends(t.native?Object.getPrototypeOf(document.createElement(t.native)).constructor:HTMLElement){constructor(){super(),this.rxns||(this.rxns={ready:{queue:{},singleton:!0},firstpaint:{queue:{},singleton:!0},render:{queue:{}}}),function(e){var t=e.constructor._processedExtensions;for(let[n,r]of t)n.onConstruct&&r.forEach(t=>n.onConstruct(e,...t))}(this),new Promise(e=>(function(e,t){var n=e.constructor._processedExtensions;for(let[r,s]of n)r.onReady&&Promise.all(s.map(t=>new Promise(n=>r.onReady(e,n,...t)))).then(t)})(this,e)).then(()=>{a(this,"ready"),this.readyCallback&&this.readyCallback()})}connectedCallback(){!function(e){var t=e.constructor._processedExtensions;for(let[n,r]of t)n.onConnect&&r.forEach(t=>n.onConnect(e,...t))}(this),this.rxns.firstpaint.frame||(this.rxns.firstpaint.frame=requestAnimationFrame(()=>a(this,"firstpaint")))}rxn(e,t,n){var r=this.rxns[e];if(!r.singleton||!r.fired)return r.queue[i++]={fn:t,recurring:n},i;t.call(this)}cancelRxn(e,t){delete this.rxns[e].queue[t]}}).options={extensions:{},pseudos:{}},n.getOptions=function(e){return this.options[e]||(this.options[e]=Object.assign({},Object.getPrototypeOf(this).options?Object.getPrototypeOf(this).options[e]:{}))},n.extensions=function(...e){var t=this.getOptions("extensions");return e.reduce((e,n)=>{var r,s=e;return t[n.name]||("string"==typeof n?r=o.extensions[n].mixin:(r=n.mixin,t[n.name]=n),r&&c(s=r(e))),s},this)},n.as=function(t){return e({native:t})},n.extensions("attr","event","template")}(),"function"==typeof define&&define.amd?(define(o),define(XTagElement)):"undefined"!=typeof module&&module.exports?module.exports={xtag:o,XTagElement:XTagElement}:(window.xtag=o,window.XTagElement=XTagElement)}(); \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..a3230dc --- /dev/null +++ b/gulpfile.js @@ -0,0 +1,64 @@ +var gulp = require('gulp'); +var concat = require('gulp-concat'); +var uglify = require('gulp-uglify-es').default; + +var paths = { + core: 'src/core.js', + polyfill: 'polyfills/custom-elements.min.js', + plugins: { + attributes: { + src: ['plugins/attributes/src/main.js'] + }, + events: { + tap: ['plugins/events/tap/pep.min.js', 'plugins/events/tap/main.js'] + }, + rendering: { + hyperHTML: ['plugins/rendering/hyperHTML/hyperHTML.min.js', 'plugins/rendering/hyperHTML/main.js'] + } + } +}; + +gulp.task('raw', function() { + return gulp.src(paths.core) + .pipe(concat('x-tag-raw.js')) + .pipe(gulp.dest('dist/')); +}); + +gulp.task('raw.min', function() { + return gulp.src(paths.core) + .pipe(uglify()) + .pipe(concat('x-tag-raw.min.js')) + .pipe(gulp.dest('dist/')); +}); + +gulp.task('polyfilled', function() { + return gulp.src([paths.polyfill, paths.core]) + .pipe(concat('x-tag-polyfilled.js')) + .pipe(gulp.dest('dist/')); +}); + +gulp.task('polyfilled.min', function() { + return gulp.src([paths.polyfill, paths.core]) + .pipe(uglify()) + .pipe(concat('x-tag-polyfilled.min.js')) + .pipe(gulp.dest('dist/')); +}); + +Object.keys(paths.plugins).forEach(type => { + var tasks = []; + var plugins = paths.plugins[type]; + for (let z in plugins) { + tasks.push(type + ':' + z); + gulp.task(type + ':' + z, function() { + return gulp.src(plugins[z]) + .pipe(uglify()) + .pipe(concat(z + '.js')) + .pipe(gulp.dest('dist/plugins/' + type)); + }); + } + gulp.task(type, tasks); +}); + +gulp.task('default', ['raw', 'polyfilled', 'raw.min', 'polyfilled.min']); +gulp.task('plugins', Object.keys(paths.plugins)); +gulp.task('all', ['default', 'plugins']); \ No newline at end of file diff --git a/lib/DOMTokenList.js b/lib/DOMTokenList.js deleted file mode 100644 index b66f5d2..0000000 --- a/lib/DOMTokenList.js +++ /dev/null @@ -1,83 +0,0 @@ -// DOMTokenList polyfill for IE9 -(function () { - -if (typeof window.Element === "undefined" || "classList" in document.documentElement) return; - -var prototype = Array.prototype, - indexOf = prototype.indexOf, - slice = prototype.slice, - push = prototype.push, - splice = prototype.splice, - join = prototype.join; - -function DOMTokenList(el) { - this._element = el; - if (el.className != this._classCache) { - this._classCache = el.className; - - if (!this._classCache) return; - - // The className needs to be trimmed and split on whitespace - // to retrieve a list of classes. - var classes = this._classCache.replace(/^\s+|\s+$/g,'').split(/\s+/), - i; - for (i = 0; i < classes.length; i++) { - push.call(this, classes[i]); - } - } -}; - -function setToClassName(el, classes) { - el.className = classes.join(' '); -} - -DOMTokenList.prototype = { - add: function(token) { - if(this.contains(token)) return; - push.call(this, token); - setToClassName(this._element, slice.call(this, 0)); - }, - contains: function(token) { - return indexOf.call(this, token) !== -1; - }, - item: function(index) { - return this[index] || null; - }, - remove: function(token) { - var i = indexOf.call(this, token); - if (i === -1) { - return; - } - splice.call(this, i, 1); - setToClassName(this._element, slice.call(this, 0)); - }, - toString: function() { - return join.call(this, ' '); - }, - toggle: function(token) { - if (indexOf.call(this, token) === -1) { - this.add(token); - } else { - this.remove(token); - } - } -}; - -window.DOMTokenList = DOMTokenList; - -function defineElementGetter (obj, prop, getter) { - if (Object.defineProperty) { - Object.defineProperty(obj, prop,{ - get : getter - }) - } else { - obj.__defineGetter__(prop, getter); - } -} - -defineElementGetter(Element.prototype, 'classList', function () { - return new DOMTokenList(this); -}); - -})(); - diff --git a/lib/custom-elements.min.js b/lib/custom-elements.min.js deleted file mode 100644 index e93a91a..0000000 --- a/lib/custom-elements.min.js +++ /dev/null @@ -1,38 +0,0 @@ -(function(){ -'use strict';var g=new function(){};var aa=new Set("annotation-xml color-profile font-face font-face-src font-face-uri font-face-format font-face-name missing-glyph".split(" "));function k(b){var a=aa.has(b);b=/^[a-z][.0-9_a-z]*-[\-.0-9_a-z]*$/.test(b);return!a&&b}function l(b){var a=b.isConnected;if(void 0!==a)return a;for(;b&&!(b.__CE_isImportDocument||b instanceof Document);)b=b.parentNode||(window.ShadowRoot&&b instanceof ShadowRoot?b.host:void 0);return!(!b||!(b.__CE_isImportDocument||b instanceof Document))} -function m(b,a){for(;a&&a!==b&&!a.nextSibling;)a=a.parentNode;return a&&a!==b?a.nextSibling:null} -function n(b,a,e){e=e?e:new Set;for(var c=b;c;){if(c.nodeType===Node.ELEMENT_NODE){var d=c;a(d);var h=d.localName;if("link"===h&&"import"===d.getAttribute("rel")){c=d.import;if(c instanceof Node&&!e.has(c))for(e.add(c),c=c.firstChild;c;c=c.nextSibling)n(c,a,e);c=m(b,d);continue}else if("template"===h){c=m(b,d);continue}if(d=d.__CE_shadowRoot)for(d=d.firstChild;d;d=d.nextSibling)n(d,a,e)}c=c.firstChild?c.firstChild:m(b,c)}}function q(b,a,e){b[a]=e};function r(){this.a=new Map;this.f=new Map;this.c=[];this.b=!1}function ba(b,a,e){b.a.set(a,e);b.f.set(e.constructor,e)}function t(b,a){b.b=!0;b.c.push(a)}function v(b,a){b.b&&n(a,function(a){return w(b,a)})}function w(b,a){if(b.b&&!a.__CE_patched){a.__CE_patched=!0;for(var e=0;e element that is represented by the instance for Safari, Chrome, IE. - // This is the behavior implemented by Firefox. - if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) { - if (eventCopy[p] instanceof SVGElementInstance) { - eventCopy[p] = eventCopy[p].correspondingUseElement; - } - } - } - - // keep the semantics of preventDefault - if (inEvent.preventDefault) { - eventCopy.preventDefault = function() { - inEvent.preventDefault(); - }; - } - return eventCopy; - }, - getTarget: function(inEvent) { - var capture = this.captureInfo[inEvent.pointerId]; - if (!capture) { - return inEvent._target; - } - if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) { - return capture; - } - }, - setCapture: function(inPointerId, inTarget) { - if (this.captureInfo[inPointerId]) { - this.releaseCapture(inPointerId); - } - this.captureInfo[inPointerId] = inTarget; - var e = document.createEvent('Event'); - e.initEvent('gotpointercapture', true, false); - e.pointerId = inPointerId; - this.implicitRelease = this.releaseCapture.bind(this, inPointerId); - document.addEventListener('pointerup', this.implicitRelease); - document.addEventListener('pointercancel', this.implicitRelease); - e._target = inTarget; - this.asyncDispatchEvent(e); - }, - releaseCapture: function(inPointerId) { - var t = this.captureInfo[inPointerId]; - if (t) { - var e = document.createEvent('Event'); - e.initEvent('lostpointercapture', true, false); - e.pointerId = inPointerId; - this.captureInfo[inPointerId] = undefined; - document.removeEventListener('pointerup', this.implicitRelease); - document.removeEventListener('pointercancel', this.implicitRelease); - e._target = t; - this.asyncDispatchEvent(e); - } - }, - /** - * Dispatches the event to its target. - * - * @param {Event} inEvent The event to be dispatched. - * @return {Boolean} True if an event handler returns true, false otherwise. - */ - dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) { - var t = this.getTarget(inEvent); - if (t) { - return t.dispatchEvent(inEvent); - } - }, - asyncDispatchEvent: function(inEvent) { - requestAnimationFrame(this.dispatchEvent.bind(this, inEvent)); - } - }; - dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher); - - var _dispatcher = dispatcher; - - var targeting = { - shadow: function(inEl) { - if (inEl) { - return inEl.shadowRoot || inEl.webkitShadowRoot; - } - }, - canTarget: function(shadow) { - return shadow && Boolean(shadow.elementFromPoint); - }, - targetingShadow: function(inEl) { - var s = this.shadow(inEl); - if (this.canTarget(s)) { - return s; - } - }, - olderShadow: function(shadow) { - var os = shadow.olderShadowRoot; - if (!os) { - var se = shadow.querySelector('shadow'); - if (se) { - os = se.olderShadowRoot; - } - } - return os; - }, - allShadows: function(element) { - var shadows = []; - var s = this.shadow(element); - while (s) { - shadows.push(s); - s = this.olderShadow(s); - } - return shadows; - }, - searchRoot: function(inRoot, x, y) { - if (inRoot) { - var t = inRoot.elementFromPoint(x, y); - var st, sr; - - // is element a shadow host? - sr = this.targetingShadow(t); - while (sr) { - - // find the the element inside the shadow root - st = sr.elementFromPoint(x, y); - if (!st) { - - // check for older shadows - sr = this.olderShadow(sr); - } else { - - // shadowed element may contain a shadow root - var ssr = this.targetingShadow(st); - return this.searchRoot(ssr, x, y) || st; - } - } - - // light dom element is the target - return t; - } - }, - owner: function(element) { - var s = element; - - // walk up until you hit the shadow root or document - while (s.parentNode) { - s = s.parentNode; - } - - // the owner element is expected to be a Document or ShadowRoot - if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) { - s = document; - } - return s; - }, - findTarget: function(inEvent) { - var x = inEvent.clientX; - var y = inEvent.clientY; - - // if the listener is in the shadow root, it is much faster to start there - var s = this.owner(inEvent.target); - - // if x, y is not in this root, fall back to document search - if (!s.elementFromPoint(x, y)) { - s = document; - } - return this.searchRoot(s, x, y); - } - }; - - /** - * This module uses Mutation Observers to dynamically adjust which nodes will - * generate Pointer Events. - * - * All nodes that wish to generate Pointer Events must have the attribute - * `touch-action` set to `none`. - */ - var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); - var map = Array.prototype.map.call.bind(Array.prototype.map); - var toArray = Array.prototype.slice.call.bind(Array.prototype.slice); - var filter = Array.prototype.filter.call.bind(Array.prototype.filter); - var MO = window.MutationObserver || window.WebKitMutationObserver; - var SELECTOR = '[touch-action]'; - var OBSERVER_INIT = { - subtree: true, - childList: true, - attributes: true, - attributeOldValue: true, - attributeFilter: ['touch-action'] - }; - - function Installer(add, remove, changed, binder) { - this.addCallback = add.bind(binder); - this.removeCallback = remove.bind(binder); - this.changedCallback = changed.bind(binder); - if (MO) { - this.observer = new MO(this.mutationWatcher.bind(this)); - } - } - - Installer.prototype = { - watchSubtree: function(target) { - - // Only watch scopes that can target find, as these are top-level. - // Otherwise we can see duplicate additions and removals that add noise. - // - // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see - // a removal without an insertion when a node is redistributed among - // shadows. Since it all ends up correct in the document, watching only - // the document will yield the correct mutations to watch. - if (this.observer && targeting.canTarget(target)) { - this.observer.observe(target, OBSERVER_INIT); - } - }, - enableOnSubtree: function(target) { - this.watchSubtree(target); - if (target === document && document.readyState !== 'complete') { - this.installOnLoad(); - } else { - this.installNewSubtree(target); - } - }, - installNewSubtree: function(target) { - forEach(this.findElements(target), this.addElement, this); - }, - findElements: function(target) { - if (target.querySelectorAll) { - return target.querySelectorAll(SELECTOR); - } - return []; - }, - removeElement: function(el) { - this.removeCallback(el); - }, - addElement: function(el) { - this.addCallback(el); - }, - elementChanged: function(el, oldValue) { - this.changedCallback(el, oldValue); - }, - concatLists: function(accum, list) { - return accum.concat(toArray(list)); - }, - - // register all touch-action = none nodes on document load - installOnLoad: function() { - document.addEventListener('readystatechange', function() { - if (document.readyState === 'complete') { - this.installNewSubtree(document); - } - }.bind(this)); - }, - isElement: function(n) { - return n.nodeType === Node.ELEMENT_NODE; - }, - flattenMutationTree: function(inNodes) { - - // find children with touch-action - var tree = map(inNodes, this.findElements, this); - - // make sure the added nodes are accounted for - tree.push(filter(inNodes, this.isElement)); - - // flatten the list - return tree.reduce(this.concatLists, []); - }, - mutationWatcher: function(mutations) { - mutations.forEach(this.mutationHandler, this); - }, - mutationHandler: function(m) { - if (m.type === 'childList') { - var added = this.flattenMutationTree(m.addedNodes); - added.forEach(this.addElement, this); - var removed = this.flattenMutationTree(m.removedNodes); - removed.forEach(this.removeElement, this); - } else if (m.type === 'attributes') { - this.elementChanged(m.target, m.oldValue); - } - } - }; - - var installer = Installer; - - function shadowSelector(v) { - return 'body /shadow-deep/ ' + selector(v); - } - function selector(v) { - return '[touch-action="' + v + '"]'; - } - function rule(v) { - return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; touch-action-delay: none; }'; - } - var attrib2css = [ - 'none', - 'auto', - 'pan-x', - 'pan-y', - { - rule: 'pan-x pan-y', - selectors: [ - 'pan-x pan-y', - 'pan-y pan-x' - ] - } - ]; - var styles = ''; - - // only install stylesheet if the browser has touch action support - var hasNativePE = window.PointerEvent || window.MSPointerEvent; - - // only add shadow selectors if shadowdom is supported - var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot; - - function applyAttributeStyles() { - if (hasNativePE) { - attrib2css.forEach(function(r) { - if (String(r) === r) { - styles += selector(r) + rule(r) + '\n'; - if (hasShadowRoot) { - styles += shadowSelector(r) + rule(r) + '\n'; - } - } else { - styles += r.selectors.map(selector) + rule(r.rule) + '\n'; - if (hasShadowRoot) { - styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n'; - } - } - }); - - var el = document.createElement('style'); - el.textContent = styles; - document.head.appendChild(el); - } - } - - var mouse__pointermap = _dispatcher.pointermap; - - // radius around touchend that swallows mouse events - var DEDUP_DIST = 25; - - // left, middle, right, back, forward - var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16]; - - var HAS_BUTTONS = false; - try { - HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1; - } catch (e) {} - - // handler block for native mouse events - var mouseEvents = { - POINTER_ID: 1, - POINTER_TYPE: 'mouse', - events: [ - 'mousedown', - 'mousemove', - 'mouseup', - 'mouseover', - 'mouseout' - ], - register: function(target) { - _dispatcher.listen(target, this.events); - }, - unregister: function(target) { - _dispatcher.unlisten(target, this.events); - }, - lastTouches: [], - - // collide with the global mouse listener - isEventSimulatedFromTouch: function(inEvent) { - var lts = this.lastTouches; - var x = inEvent.clientX; - var y = inEvent.clientY; - for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) { - - // simulated mouse events will be swallowed near a primary touchend - var dx = Math.abs(x - t.x); - var dy = Math.abs(y - t.y); - if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) { - return true; - } - } - }, - prepareEvent: function(inEvent) { - var e = _dispatcher.cloneEvent(inEvent); - - // forward mouse preventDefault - var pd = e.preventDefault; - e.preventDefault = function() { - inEvent.preventDefault(); - pd(); - }; - e.pointerId = this.POINTER_ID; - e.isPrimary = true; - e.pointerType = this.POINTER_TYPE; - return e; - }, - prepareButtonsForMove: function(e, inEvent) { - var p = mouse__pointermap.get(this.POINTER_ID); - e.buttons = p ? p.buttons : 0; - inEvent.buttons = e.buttons; - }, - mousedown: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var p = mouse__pointermap.get(this.POINTER_ID); - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { - e.buttons = BUTTON_TO_BUTTONS[e.button]; - if (p) { e.buttons |= p.buttons; } - inEvent.buttons = e.buttons; - } - mouse__pointermap.set(this.POINTER_ID, inEvent); - if (!p) { - _dispatcher.down(e); - } else { - _dispatcher.move(e); - } - } - }, - mousemove: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); } - _dispatcher.move(e); - } - }, - mouseup: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var p = mouse__pointermap.get(this.POINTER_ID); - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { - var up = BUTTON_TO_BUTTONS[e.button]; - - // Produces wrong state of buttons in Browsers without `buttons` support - // when a mouse button that was pressed outside the document is released - // inside and other buttons are still pressed down. - e.buttons = p ? p.buttons & ~up : 0; - inEvent.buttons = e.buttons; - } - mouse__pointermap.set(this.POINTER_ID, inEvent); - - // Support: Firefox <=44 only - // FF Ubuntu includes the lifted button in the `buttons` property on - // mouseup. - // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366 - if (e.buttons === 0 || e.buttons === BUTTON_TO_BUTTONS[e.button]) { - this.cleanupMouse(); - _dispatcher.up(e); - } else { - _dispatcher.move(e); - } - } - }, - mouseover: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); } - _dispatcher.enterOver(e); - } - }, - mouseout: function(inEvent) { - if (!this.isEventSimulatedFromTouch(inEvent)) { - var e = this.prepareEvent(inEvent); - if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); } - _dispatcher.leaveOut(e); - } - }, - cancel: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.cancel(e); - this.cleanupMouse(); - }, - cleanupMouse: function() { - mouse__pointermap.delete(this.POINTER_ID); - } - }; - - var mouse = mouseEvents; - - var captureInfo = _dispatcher.captureInfo; - var findTarget = targeting.findTarget.bind(targeting); - var allShadows = targeting.allShadows.bind(targeting); - var touch__pointermap = _dispatcher.pointermap; - - // This should be long enough to ignore compat mouse events made by touch - var DEDUP_TIMEOUT = 2500; - var CLICK_COUNT_TIMEOUT = 200; - var ATTRIB = 'touch-action'; - var INSTALLER; - - // The presence of touch event handlers blocks scrolling, and so we must be careful to - // avoid adding handlers unnecessarily. Chrome plans to add a touch-action-delay property - // (crbug.com/329559) to address this, and once we have that we can opt-in to a simpler - // handler registration mechanism. Rather than try to predict how exactly to opt-in to - // that we'll just leave this disabled until there is a build of Chrome to test. - var HAS_TOUCH_ACTION_DELAY = false; - - // handler block for native touch events - var touchEvents = { - events: [ - 'touchstart', - 'touchmove', - 'touchend', - 'touchcancel' - ], - register: function(target) { - if (HAS_TOUCH_ACTION_DELAY) { - _dispatcher.listen(target, this.events); - } else { - INSTALLER.enableOnSubtree(target); - } - }, - unregister: function(target) { - if (HAS_TOUCH_ACTION_DELAY) { - _dispatcher.unlisten(target, this.events); - } else { - - // TODO(dfreedman): is it worth it to disconnect the MO? - } - }, - elementAdded: function(el) { - var a = el.getAttribute(ATTRIB); - var st = this.touchActionToScrollType(a); - if (st) { - el._scrollType = st; - _dispatcher.listen(el, this.events); - - // set touch-action on shadows as well - allShadows(el).forEach(function(s) { - s._scrollType = st; - _dispatcher.listen(s, this.events); - }, this); - } - }, - elementRemoved: function(el) { - el._scrollType = undefined; - _dispatcher.unlisten(el, this.events); - - // remove touch-action from shadow - allShadows(el).forEach(function(s) { - s._scrollType = undefined; - _dispatcher.unlisten(s, this.events); - }, this); - }, - elementChanged: function(el, oldValue) { - var a = el.getAttribute(ATTRIB); - var st = this.touchActionToScrollType(a); - var oldSt = this.touchActionToScrollType(oldValue); - - // simply update scrollType if listeners are already established - if (st && oldSt) { - el._scrollType = st; - allShadows(el).forEach(function(s) { - s._scrollType = st; - }, this); - } else if (oldSt) { - this.elementRemoved(el); - } else if (st) { - this.elementAdded(el); - } - }, - scrollTypes: { - EMITTER: 'none', - XSCROLLER: 'pan-x', - YSCROLLER: 'pan-y', - SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/ - }, - touchActionToScrollType: function(touchAction) { - var t = touchAction; - var st = this.scrollTypes; - if (t === 'none') { - return 'none'; - } else if (t === st.XSCROLLER) { - return 'X'; - } else if (t === st.YSCROLLER) { - return 'Y'; - } else if (st.SCROLLER.exec(t)) { - return 'XY'; - } - }, - POINTER_TYPE: 'touch', - firstTouch: null, - isPrimaryTouch: function(inTouch) { - return this.firstTouch === inTouch.identifier; - }, - setPrimaryTouch: function(inTouch) { - - // set primary touch if there no pointers, or the only pointer is the mouse - if (touch__pointermap.size === 0 || (touch__pointermap.size === 1 && touch__pointermap.has(1))) { - this.firstTouch = inTouch.identifier; - this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY }; - this.scrolling = false; - this.cancelResetClickCount(); - } - }, - removePrimaryPointer: function(inPointer) { - if (inPointer.isPrimary) { - this.firstTouch = null; - this.firstXY = null; - this.resetClickCount(); - } - }, - clickCount: 0, - resetId: null, - resetClickCount: function() { - var fn = function() { - this.clickCount = 0; - this.resetId = null; - }.bind(this); - this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT); - }, - cancelResetClickCount: function() { - if (this.resetId) { - clearTimeout(this.resetId); - } - }, - typeToButtons: function(type) { - var ret = 0; - if (type === 'touchstart' || type === 'touchmove') { - ret = 1; - } - return ret; - }, - touchToPointer: function(inTouch) { - var cte = this.currentTouchEvent; - var e = _dispatcher.cloneEvent(inTouch); - - // We reserve pointerId 1 for Mouse. - // Touch identifiers can start at 0. - // Add 2 to the touch identifier for compatibility. - var id = e.pointerId = inTouch.identifier + 2; - e.target = captureInfo[id] || findTarget(e); - e.bubbles = true; - e.cancelable = true; - e.detail = this.clickCount; - e.button = 0; - e.buttons = this.typeToButtons(cte.type); - e.width = inTouch.radiusX || inTouch.webkitRadiusX || 0; - e.height = inTouch.radiusY || inTouch.webkitRadiusY || 0; - e.pressure = inTouch.force || inTouch.webkitForce || 0.5; - e.isPrimary = this.isPrimaryTouch(inTouch); - e.pointerType = this.POINTER_TYPE; - - // forward touch preventDefaults - var self = this; - e.preventDefault = function() { - self.scrolling = false; - self.firstXY = null; - cte.preventDefault(); - }; - return e; - }, - processTouches: function(inEvent, inFunction) { - var tl = inEvent.changedTouches; - this.currentTouchEvent = inEvent; - for (var i = 0, t; i < tl.length; i++) { - t = tl[i]; - inFunction.call(this, this.touchToPointer(t)); - } - }, - - // For single axis scrollers, determines whether the element should emit - // pointer events or behave as a scroller - shouldScroll: function(inEvent) { - if (this.firstXY) { - var ret; - var scrollAxis = inEvent.currentTarget._scrollType; - if (scrollAxis === 'none') { - - // this element is a touch-action: none, should never scroll - ret = false; - } else if (scrollAxis === 'XY') { - - // this element should always scroll - ret = true; - } else { - var t = inEvent.changedTouches[0]; - - // check the intended scroll axis, and other axis - var a = scrollAxis; - var oa = scrollAxis === 'Y' ? 'X' : 'Y'; - var da = Math.abs(t['client' + a] - this.firstXY[a]); - var doa = Math.abs(t['client' + oa] - this.firstXY[oa]); - - // if delta in the scroll axis > delta other axis, scroll instead of - // making events - ret = da >= doa; - } - this.firstXY = null; - return ret; - } - }, - findTouch: function(inTL, inId) { - for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) { - if (t.identifier === inId) { - return true; - } - } - }, - - // In some instances, a touchstart can happen without a touchend. This - // leaves the pointermap in a broken state. - // Therefore, on every touchstart, we remove the touches that did not fire a - // touchend event. - // To keep state globally consistent, we fire a - // pointercancel for this "abandoned" touch - vacuumTouches: function(inEvent) { - var tl = inEvent.touches; - - // pointermap.size should be < tl.length here, as the touchstart has not - // been processed yet. - if (touch__pointermap.size >= tl.length) { - var d = []; - touch__pointermap.forEach(function(value, key) { - - // Never remove pointerId == 1, which is mouse. - // Touch identifiers are 2 smaller than their pointerId, which is the - // index in pointermap. - if (key !== 1 && !this.findTouch(tl, key - 2)) { - var p = value.out; - d.push(p); - } - }, this); - d.forEach(this.cancelOut, this); - } - }, - touchstart: function(inEvent) { - this.vacuumTouches(inEvent); - this.setPrimaryTouch(inEvent.changedTouches[0]); - this.dedupSynthMouse(inEvent); - if (!this.scrolling) { - this.clickCount++; - this.processTouches(inEvent, this.overDown); - } - }, - overDown: function(inPointer) { - touch__pointermap.set(inPointer.pointerId, { - target: inPointer.target, - out: inPointer, - outTarget: inPointer.target - }); - _dispatcher.over(inPointer); - _dispatcher.enter(inPointer); - _dispatcher.down(inPointer); - }, - touchmove: function(inEvent) { - if (!this.scrolling) { - if (this.shouldScroll(inEvent)) { - this.scrolling = true; - this.touchcancel(inEvent); - } else { - inEvent.preventDefault(); - this.processTouches(inEvent, this.moveOverOut); - } - } - }, - moveOverOut: function(inPointer) { - var event = inPointer; - var pointer = touch__pointermap.get(event.pointerId); - - // a finger drifted off the screen, ignore it - if (!pointer) { - return; - } - var outEvent = pointer.out; - var outTarget = pointer.outTarget; - _dispatcher.move(event); - if (outEvent && outTarget !== event.target) { - outEvent.relatedTarget = event.target; - event.relatedTarget = outTarget; - - // recover from retargeting by shadow - outEvent.target = outTarget; - if (event.target) { - _dispatcher.leaveOut(outEvent); - _dispatcher.enterOver(event); - } else { - - // clean up case when finger leaves the screen - event.target = outTarget; - event.relatedTarget = null; - this.cancelOut(event); - } - } - pointer.out = event; - pointer.outTarget = event.target; - }, - touchend: function(inEvent) { - this.dedupSynthMouse(inEvent); - this.processTouches(inEvent, this.upOut); - }, - upOut: function(inPointer) { - if (!this.scrolling) { - _dispatcher.up(inPointer); - _dispatcher.out(inPointer); - _dispatcher.leave(inPointer); - } - this.cleanUpPointer(inPointer); - }, - touchcancel: function(inEvent) { - this.processTouches(inEvent, this.cancelOut); - }, - cancelOut: function(inPointer) { - _dispatcher.cancel(inPointer); - _dispatcher.out(inPointer); - _dispatcher.leave(inPointer); - this.cleanUpPointer(inPointer); - }, - cleanUpPointer: function(inPointer) { - touch__pointermap.delete(inPointer.pointerId); - this.removePrimaryPointer(inPointer); - }, - - // prevent synth mouse events from creating pointer events - dedupSynthMouse: function(inEvent) { - var lts = mouse.lastTouches; - var t = inEvent.changedTouches[0]; - - // only the primary finger will synth mouse events - if (this.isPrimaryTouch(t)) { - - // remember x/y of last touch - var lt = { x: t.clientX, y: t.clientY }; - lts.push(lt); - var fn = (function(lts, lt) { - var i = lts.indexOf(lt); - if (i > -1) { - lts.splice(i, 1); - } - }).bind(null, lts, lt); - setTimeout(fn, DEDUP_TIMEOUT); - } - } - }; - - if (!HAS_TOUCH_ACTION_DELAY) { - INSTALLER = new installer(touchEvents.elementAdded, touchEvents.elementRemoved, - touchEvents.elementChanged, touchEvents); - } - - var touch = touchEvents; - - var ms__pointermap = _dispatcher.pointermap; - var HAS_BITMAP_TYPE = window.MSPointerEvent && - typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number'; - var msEvents = { - events: [ - 'MSPointerDown', - 'MSPointerMove', - 'MSPointerUp', - 'MSPointerOut', - 'MSPointerOver', - 'MSPointerCancel', - 'MSGotPointerCapture', - 'MSLostPointerCapture' - ], - register: function(target) { - _dispatcher.listen(target, this.events); - }, - unregister: function(target) { - _dispatcher.unlisten(target, this.events); - }, - POINTER_TYPES: [ - '', - 'unavailable', - 'touch', - 'pen', - 'mouse' - ], - prepareEvent: function(inEvent) { - var e = inEvent; - if (HAS_BITMAP_TYPE) { - e = _dispatcher.cloneEvent(inEvent); - e.pointerType = this.POINTER_TYPES[inEvent.pointerType]; - } - return e; - }, - cleanup: function(id) { - ms__pointermap.delete(id); - }, - MSPointerDown: function(inEvent) { - ms__pointermap.set(inEvent.pointerId, inEvent); - var e = this.prepareEvent(inEvent); - _dispatcher.down(e); - }, - MSPointerMove: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.move(e); - }, - MSPointerUp: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.up(e); - this.cleanup(inEvent.pointerId); - }, - MSPointerOut: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.leaveOut(e); - }, - MSPointerOver: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.enterOver(e); - }, - MSPointerCancel: function(inEvent) { - var e = this.prepareEvent(inEvent); - _dispatcher.cancel(e); - this.cleanup(inEvent.pointerId); - }, - MSLostPointerCapture: function(inEvent) { - var e = _dispatcher.makeEvent('lostpointercapture', inEvent); - _dispatcher.dispatchEvent(e); - }, - MSGotPointerCapture: function(inEvent) { - var e = _dispatcher.makeEvent('gotpointercapture', inEvent); - _dispatcher.dispatchEvent(e); - } - }; - - var ms = msEvents; - - function platform_events__applyPolyfill() { - - // only activate if this platform does not have pointer events - if (!window.PointerEvent) { - window.PointerEvent = _PointerEvent; - - if (window.navigator.msPointerEnabled) { - var tp = window.navigator.msMaxTouchPoints; - Object.defineProperty(window.navigator, 'maxTouchPoints', { - value: tp, - enumerable: true - }); - _dispatcher.registerSource('ms', ms); - } else { - _dispatcher.registerSource('mouse', mouse); - if (window.ontouchstart !== undefined) { - _dispatcher.registerSource('touch', touch); - } - } - - _dispatcher.register(document); - } - } - - var n = window.navigator; - var s, r; - function assertDown(id) { - if (!_dispatcher.pointermap.has(id)) { - throw new Error('InvalidPointerId'); - } - } - if (n.msPointerEnabled) { - s = function(pointerId) { - assertDown(pointerId); - this.msSetPointerCapture(pointerId); - }; - r = function(pointerId) { - assertDown(pointerId); - this.msReleasePointerCapture(pointerId); - }; - } else { - s = function setPointerCapture(pointerId) { - assertDown(pointerId); - _dispatcher.setCapture(pointerId, this); - }; - r = function releasePointerCapture(pointerId) { - assertDown(pointerId); - _dispatcher.releaseCapture(pointerId, this); - }; - } - - function _capture__applyPolyfill() { - if (window.Element && !Element.prototype.setPointerCapture) { - Object.defineProperties(Element.prototype, { - 'setPointerCapture': { - value: s - }, - 'releasePointerCapture': { - value: r - } - }); - } - } - - applyAttributeStyles(); - platform_events__applyPolyfill(); - _capture__applyPolyfill(); - - var pointerevents = { - dispatcher: _dispatcher, - Installer: installer, - PointerEvent: _PointerEvent, - PointerMap: _pointermap, - targetFinding: targeting - }; - - return pointerevents; - -})); diff --git a/lib/webcomponents-hi-ce-es5.js b/lib/webcomponents-hi-ce-es5.js deleted file mode 100644 index 1c96eb7..0000000 --- a/lib/webcomponents-hi-ce-es5.js +++ /dev/null @@ -1,16 +0,0 @@ -(function () { -'use strict'; - -(()=>{'use strict';if(!window.customElements)return;const a=window.HTMLElement,b=window.customElements.define,c=window.customElements.get,d=new Map,e=new Map;let f=!1,g=!1;window.HTMLElement=function(){if(!f){const h=d.get(this.constructor),i=c.call(window.customElements,h);g=!0;const j=new i;return j}f=!1;},window.HTMLElement.prototype=a.prototype,window.customElements.define=(h,i)=>{const j=i.prototype,k=class extends a{constructor(){super(),Object.setPrototypeOf(this,j),g||(f=!0,i.call(this)),g=!1;}},l=k.prototype;k.observedAttributes=i.observedAttributes,l.connectedCallback=j.connectedCallback,l.disconnectedCallback=j.disconnectedCallback,l.attributeChangedCallback=j.attributeChangedCallback,l.adoptedCallback=j.adoptedCallback,d.set(i,h),e.set(h,i),b.call(window.customElements,h,k);},window.customElements.get=(h)=>e.get(h);})(); - -((a)=>{const b=!!('import'in document.createElement('link'));let c=null;!1=='currentScript'in document&&Object.defineProperty(document,'currentScript',{get(){return c||('complete'===document.readyState?null:document.scripts[document.scripts.length-1])},configurable:!0});const d=/(^\/)|(^#)|(^[\w-\d]*:)/,f=/(url\()([^)]*)(\))/g,g=/(@import[\s]+(?!url\())([^;]*)(;)/g,h=/(]*)(rel=['|"]?stylesheet['|"]?[^>]*>)/g,k={fixUrls(J,K){if(J.href&&J.setAttribute('href',k.replaceAttrUrl(J.getAttribute('href'),K)),J.src&&J.setAttribute('src',k.replaceAttrUrl(J.getAttribute('src'),K)),'style'===J.localName){const L=k.replaceUrls(J.textContent,K,f);J.textContent=k.replaceUrls(L,K,g);}},replaceUrls(J,K,L){return J.replace(L,(M,N,O,P)=>{let Q=O.replace(/["']/g,'');return K&&(Q=k.resolveUrl(Q,K)),N+'\''+Q+'\''+P})},replaceAttrUrl(J,K){return J&&d.test(J)?J:k.resolveUrl(J,K)},resolveUrl(J,K){if(void 0===k.__workingURL){k.__workingURL=!1;try{const M=new URL('b','http://a');M.pathname='c%20d',k.__workingURL='http://a/c%20d'===M.href;}catch(M){}}if(k.__workingURL)return new URL(J,K).href;let L=k.__tempDoc;return L||(L=document.implementation.createHTMLDocument('temp'),k.__tempDoc=L,L.__base=L.createElement('base'),L.head.appendChild(L.__base),L.__anchor=L.createElement('a')),L.__base.href=K,L.__anchor.href=J,L.__anchor.href||J}},o={async:!0,load(J,K,L){if(!J)L('error: href must be specified');else if(J.match(/^data:/)){const M=J.split(','),N=M[0];let O=M[1];O=-1{let N=M.getResponseHeader('Location');if(N&&0===N.indexOf('/')){const P=location.origin||location.protocol+'//'+location.host;N=P+N;}const O=M.response||M.responseText;304===M.status||0===M.status||200<=M.status&&300>M.status?K(O,N):L(O);},M.send();}}},p=/Trident/.test(navigator.userAgent)||/Edge\/\d./i.test(navigator.userAgent),q='link[rel=import]',t='import-disable',v=`link[rel=stylesheet][href][type=${t}]`,w=`${q}, ${v}, - style:not([type]), link[rel=stylesheet][href]:not([type]), - script:not([type]), script[type="application/javascript"], - script[type="text/javascript"]`,x='import-dependency',y=`${q}:not(${x})`,z=`script[${x}]`,A=`style[${x}], - link[rel=stylesheet][${x}]`;const C=(J)=>{return J.nodeType===Node.ELEMENT_NODE&&'link'===J.localName&&'import'===J.rel},D=(J,K)=>{if(J.__loaded)K&&K();else if(C(J)&&!b&&null===J.import||J.import&&'complete'===J.import.readyState)J.__loaded=!0,K&&K();else if('script'===J.localName&&!J.src)J.__loaded=!0,K&&K();else{const L=(M)=>{J.removeEventListener(M.type,L),J.__loaded=!0,K&&K();};J.addEventListener('load',L),p&&'style'===J.localName||J.addEventListener('error',L);}},E=(J)=>{F(()=>G(()=>J&&J()));},F=(J)=>{if('loading'!==document.readyState)J();else{const K=()=>{'loading'!==document.readyState&&(document.removeEventListener('readystatechange',K),J());};document.addEventListener('readystatechange',K);}},G=(J)=>{let K=document.querySelectorAll(y),L=K.length;if(!L)return void J();for(let O,M=0,N=K.length;M{0==--L&&J();});},H=(J)=>{if(b)return J.ownerDocument===document?null:J.ownerDocument;let K=J.__importDoc;if(!K&&J.parentNode){if(K=J.parentNode,'function'==typeof K.closest)K=K.closest(q);else for(;!C(K)&&(K=K.parentNode););J.__importDoc=K;}return K},I=(J,K)=>{if('function'==typeof window.CustomEvent)return new CustomEvent(J,K);const L=document.createEvent('CustomEvent');return L.initCustomEvent(J,!!K.bubbles,!!K.cancelable,K.detail),L};if(b){const J=document.querySelectorAll(q);for(let N,L=0,M=J.length;L{const M=L.target;C(M)&&(M.__loaded=!0);};document.addEventListener('load',K,!0),document.addEventListener('error',K,!0);}else new class{constructor(){this.documents={},this.inflight=0,this.dynamicImportsMO=new MutationObserver((J)=>this.handleMutations(J)),F(()=>{this.dynamicImportsMO.observe(document.head,{childList:!0,subtree:!0}),this.loadImports(document);});}loadImports(J){const K=J.querySelectorAll(q);for(let L=0,M=K.length;L{const N=this.makeDocument(L,M||K);this.documents[K]=N,this.inflight--,this.loadImports(N),this.processImportsIfLoadingDone();},()=>{this.documents[K]=null,this.inflight--,this.processImportsIfLoadingDone();});}makeDocument(J,K){if(!J)return document.createDocumentFragment();p&&(J=J.replace(h,(Q,R,S)=>{return-1===Q.indexOf('type=')?`${R} type=${t} ${S}`:Q}));let L;const M=document.createElement('template');if(M.innerHTML=J,M.content)L=M.content;else for(L=document.createDocumentFragment();M.firstChild;)L.appendChild(M.firstChild);const N=L.querySelector('base');N&&(K=k.replaceAttrUrl(N.getAttribute('href'),K),N.removeAttribute('href'));const O=L.querySelectorAll(w);let P=0;for(let S,Q=0,R=O.length;Q{K&&J&&(this.dynamicImportsMO.observe(document.head,{childList:!0,subtree:!0}),this.fireEvents());};this.waitForStyles(()=>{K=!0,L();}),this.runScripts(()=>{J=!0,L();});}flatten(J){const K=J.querySelectorAll(q);for(let N,L=0,M=K.length;LN.href,configurable:!0,enumerable:!0}),this.flatten(O),N.appendChild(O));}}runScripts(J){const K=document.querySelectorAll(z),L=K.length,M=(N)=>{if(N{c=null,M(N+1);});}else J();};M(0);}waitForStyles(J){const K=document.querySelectorAll(A);let L=K.length;if(!L)return void J();const M=p&&!!document.querySelector(v);for(let P,N=0,O=K.length;N{P.removeAttribute(x),0==--L&&J();}),M&&P.parentNode!==document.head){const Q=document.createElement(P.localName);Q.__appliedElement=P,Q.setAttribute('type','import-placeholder'),P.parentNode.insertBefore(Q,P.nextSibling);let R=H(P);for(;R&&H(R);)R=H(R);R.parentNode!==document.head&&(R=null),document.head.insertBefore(P,R),P.removeAttribute('type');}}fireEvents(){const J=document.querySelectorAll(q);for(let L,K=J.length-1;0<=K&&(L=J[K]);K--)this.fireEventIfNeeded(L);}fireEventIfNeeded(J){if(!J.__loaded){J.__loaded=!0,J.import&&(J.import.readyState='complete');const K=J.import?'load':'error';J.dispatchEvent(I(K,{bubbles:!1,cancelable:!1,detail:void 0}));}}handleMutations(J){for(let K=0;Kdocument.dispatchEvent(I('HTMLImportsLoaded',{cancelable:!0,bubbles:!0,detail:void 0}))),a.useNative=b,a.whenReady=E,a.importForElement=H;})(window.HTMLImports=window.HTMLImports||{}); - -(function(){'use strict';var a=window.customElements,b=window.HTMLImports;if(a&&a.polyfillWrapFlushCallback){var c,d=function(){if(c){var g=c;return c=null,g(),!0}},e=b.whenReady;a.polyfillWrapFlushCallback(function(f){c=f,e(d);}),b.whenReady=function(f){e(function(){d()?b.whenReady(f):f();});};}b.whenReady(function(){requestAnimationFrame(function(){window.dispatchEvent(new CustomEvent('WebComponentsReady'));});});})(); - -(function(){'use strict';var a=document.createElement('style');a.textContent='body {transition: opacity ease-in 0.2s; } \\nbody[unresolved] {opacity: 0; display: block; overflow: hidden; position: relative; } \\n';var b=document.querySelector('head');b.insertBefore(a,b.firstChild);})(); - -}()); diff --git a/lib/webcomponents-lite.js b/lib/webcomponents-lite.js deleted file mode 100644 index 3a133a1..0000000 --- a/lib/webcomponents-lite.js +++ /dev/null @@ -1,2430 +0,0 @@ -/** - * @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.20 -(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 && " " != 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 (" " == 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 (" " == 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 (" " != 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 (" " == 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 (" " != c && "\n" != c && "\r" != c) { - buffer += percentEscape(c); - } - break; - - case "query": - if (!stateOverride && "#" == c) { - this._fragment = "#"; - state = "fragment"; - } else if (EOF != c && " " != c && "\n" != c && "\r" != c) { - this._query += percentEscapeQuery(c); - } - break; - - case "fragment": - if (EOF != c && " " != 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); - -if (typeof HTMLTemplateElement === "undefined") { - (function() { - var TEMPLATE_TAG = "template"; - var contentDoc = document.implementation.createHTMLDocument("template"); - var canDecorate = true; - HTMLTemplateElement = function() {}; - HTMLTemplateElement.prototype = Object.create(HTMLElement.prototype); - HTMLTemplateElement.decorate = function(template) { - if (template.content) { - return; - } - template.content = contentDoc.createDocumentFragment(); - var child; - while (child = template.firstChild) { - template.content.appendChild(child); - } - 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; - HTMLTemplateElement.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; - } - } - HTMLTemplateElement.bootstrap(template.content); - }; - HTMLTemplateElement.bootstrap = function(doc) { - var templates = doc.querySelectorAll(TEMPLATE_TAG); - for (var i = 0, l = templates.length, t; i < l && (t = templates[i]); i++) { - HTMLTemplateElement.decorate(t); - } - }; - document.addEventListener("DOMContentLoaded", function() { - HTMLTemplateElement.bootstrap(document); - }); - var createElement = document.createElement; - document.createElement = function() { - "use strict"; - var el = createElement.apply(document, arguments); - if (el.localName == "template") { - HTMLTemplateElement.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); - } - })(); -} - -(function(scope) { - "use strict"; - if (!window.performance) { - 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.HTMLImports.__importsParsingHook) { - window.HTMLImports.__importsParsingHook(elt); - } - if (elt.import) { - elt.import.__importParsed = true; - } - this.markParsingComplete(elt); - if (elt.__resource && !elt.__error) { - elt.dispatchEvent(new CustomEvent("load", { - bubbles: false - })); - } else { - elt.dispatchEvent(new CustomEvent("error", { - bubbles: false - })); - } - if (elt.__pending) { - var fn; - while (elt.__pending.length) { - fn = elt.__pending.shift(); - if (fn) { - fn({ - target: elt - }); - } - } - } - this.parseNext(); - }, - parseLink: function(linkElt) { - if (nodeIsImport(linkElt)) { - this.parseImport(linkElt); - } else { - linkElt.href = linkElt.href; - this.parseGeneric(linkElt); - } - }, - parseStyle: function(elt) { - var src = elt; - elt = cloneStyle(elt); - src.__appliedElement = elt; - elt.__importElement = src; - this.parseGeneric(elt); - }, - parseGeneric: function(elt) { - this.trackElement(elt); - this.addElementToDocument(elt); - }, - rootImportForElement: function(elt) { - var n = elt; - while (n.ownerDocument.__importLink) { - n = n.ownerDocument.__importLink; - } - return n; - }, - addElementToDocument: function(elt) { - var port = this.rootImportForElement(elt.__importElement || elt); - port.parentNode.insertBefore(elt, port); - }, - trackElement: function(elt, callback) { - var self = this; - var done = function(e) { - elt.removeEventListener("load", done); - elt.removeEventListener("error", done); - if (callback) { - callback(e); - } - self.markParsingComplete(elt); - self.parseNext(); - }; - elt.addEventListener("load", done); - elt.addEventListener("error", done); - if (isIE && elt.localName === "style") { - var fakeLoad = false; - if (elt.textContent.indexOf("@import") == -1) { - fakeLoad = true; - } else if (elt.sheet) { - fakeLoad = true; - var csr = elt.sheet.cssRules; - var len = csr ? csr.length : 0; - for (var i = 0, r; i < len && (r = csr[i]); i++) { - if (r.type === CSSRule.IMPORT_RULE) { - fakeLoad = fakeLoad && Boolean(r.styleSheet); - } - } - } - if (fakeLoad) { - setTimeout(function() { - elt.dispatchEvent(new CustomEvent("load", { - bubbles: false - })); - }); - } - } - }, - parseScript: function(scriptElt) { - var script = document.createElement("script"); - script.__importElement = scriptElt; - script.src = scriptElt.src ? scriptElt.src : generateScriptDataUrl(scriptElt); - scope.currentScript = scriptElt; - this.trackElement(script, function(e) { - if (script.parentNode) { - script.parentNode.removeChild(script); - } - scope.currentScript = null; - }); - this.addElementToDocument(script); - }, - nextToParse: function() { - this._mayParse = []; - return !this.parsingElement && (this.nextToParseInDoc(rootDocument) || this.nextToParseDynamic()); - }, - nextToParseInDoc: function(doc, link) { - if (doc && this._mayParse.indexOf(doc) < 0) { - this._mayParse.push(doc); - var nodes = doc.querySelectorAll(this.parseSelectorsForNode(doc)); - for (var i = 0, l = nodes.length, p = 0, n; i < l && (n = nodes[i]); i++) { - if (!this.isParsed(n)) { - if (this.hasResource(n)) { - return nodeIsImport(n) ? this.nextToParseInDoc(n.__doc, n) : n; - } else { - return; - } - } - } - } - return link; - }, - nextToParseDynamic: function() { - return this.dynamicElements[0]; - }, - parseSelectorsForNode: function(node) { - var doc = node.ownerDocument || node; - return doc === rootDocument ? this.documentSelectors : this.importsSelectors; - }, - isParsed: function(node) { - return node.__importParsed; - }, - needsDynamicParsing: function(elt) { - return this.dynamicElements.indexOf(elt) >= 0; - }, - hasResource: function(node) { - if (nodeIsImport(node) && node.__doc === undefined) { - return false; - } - return true; - } - }; - function nodeIsImport(elt) { - return elt.localName === "link" && elt.rel === IMPORT_LINK_TYPE; - } - function generateScriptDataUrl(script) { - var scriptContent = generateScriptContent(script); - return "data:text/javascript;charset=utf-8," + encodeURIComponent(scriptContent); - } - function generateScriptContent(script) { - return script.textContent + generateSourceMapHint(script); - } - function generateSourceMapHint(script) { - var owner = script.ownerDocument; - owner.__importedScripts = owner.__importedScripts || 0; - var moniker = script.ownerDocument.baseURI; - var num = owner.__importedScripts ? "-" + owner.__importedScripts : ""; - owner.__importedScripts++; - return "\n//# sourceURL=" + moniker + num + ".js\n"; - } - function cloneStyle(style) { - var clone = style.ownerDocument.createElement("style"); - clone.textContent = style.textContent; - path.resolveUrlsInStyle(clone); - return clone; - } - scope.parser = importParser; - scope.IMPORT_SELECTOR = IMPORT_SELECTOR; -}); - -window.HTMLImports.addModule(function(scope) { - var flags = scope.flags; - var IMPORT_LINK_TYPE = scope.IMPORT_LINK_TYPE; - var IMPORT_SELECTOR = scope.IMPORT_SELECTOR; - var rootDocument = scope.rootDocument; - var Loader = scope.Loader; - var Observer = scope.Observer; - var parser = scope.parser; - var importer = { - documents: {}, - documentPreloadSelectors: IMPORT_SELECTOR, - importsPreloadSelectors: [ IMPORT_SELECTOR ].join(","), - loadNode: function(node) { - importLoader.addNode(node); - }, - loadSubtree: function(parent) { - var nodes = this.marshalNodes(parent); - importLoader.addNodes(nodes); - }, - marshalNodes: function(parent) { - return parent.querySelectorAll(this.loadSelectorsForNode(parent)); - }, - loadSelectorsForNode: function(node) { - var doc = node.ownerDocument || node; - return doc === rootDocument ? this.documentPreloadSelectors : this.importsPreloadSelectors; - }, - loaded: function(url, elt, resource, err, redirectedUrl) { - flags.load && console.log("loaded", url, elt); - elt.__resource = resource; - elt.__error = err; - if (isImportLink(elt)) { - var doc = this.documents[url]; - if (doc === undefined) { - doc = err ? null : makeDocument(resource, redirectedUrl || url); - if (doc) { - doc.__importLink = elt; - this.bootDocument(doc); - } - this.documents[url] = doc; - } - elt.__doc = doc; - } - parser.parseNext(); - }, - bootDocument: function(doc) { - this.loadSubtree(doc); - this.observer.observe(doc); - parser.parseNext(); - }, - loadedAll: function() { - parser.parseNext(); - } - }; - var importLoader = new Loader(importer.loaded.bind(importer), importer.loadedAll.bind(importer)); - importer.observer = new Observer(); - function isImportLink(elt) { - return isLinkRel(elt, IMPORT_LINK_TYPE); - } - function isLinkRel(elt, rel) { - return elt.localName === "link" && elt.getAttribute("rel") === rel; - } - function hasBaseURIAccessor(doc) { - return !!Object.getOwnPropertyDescriptor(doc, "baseURI"); - } - function makeDocument(resource, url) { - var doc = document.implementation.createHTMLDocument(IMPORT_LINK_TYPE); - doc._URL = url; - var base = doc.createElement("base"); - base.setAttribute("href", url); - if (!doc.baseURI && !hasBaseURIAccessor(doc)) { - Object.defineProperty(doc, "baseURI", { - value: url - }); - } - var meta = doc.createElement("meta"); - meta.setAttribute("charset", "utf-8"); - doc.head.appendChild(meta); - doc.head.appendChild(base); - doc.body.innerHTML = resource; - if (window.HTMLTemplateElement && HTMLTemplateElement.bootstrap) { - HTMLTemplateElement.bootstrap(doc); - } - return doc; - } - if (!document.baseURI) { - var baseURIDescriptor = { - get: function() { - var base = document.querySelector("base"); - return base ? base.href : window.location.href; - }, - configurable: true - }; - Object.defineProperty(document, "baseURI", baseURIDescriptor); - Object.defineProperty(rootDocument, "baseURI", baseURIDescriptor); - } - scope.importer = importer; - scope.importLoader = importLoader; -}); - -window.HTMLImports.addModule(function(scope) { - var parser = scope.parser; - var importer = scope.importer; - var dynamic = { - added: function(nodes) { - var owner, parsed, loading; - for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) { - if (!owner) { - owner = n.ownerDocument; - parsed = parser.isParsed(owner); - } - loading = this.shouldLoadNode(n); - if (loading) { - importer.loadNode(n); - } - if (this.shouldParseNode(n) && parsed) { - parser.parseDynamic(n, loading); - } - } - }, - shouldLoadNode: function(node) { - return node.nodeType === 1 && matches.call(node, importer.loadSelectorsForNode(node)); - }, - shouldParseNode: function(node) { - return node.nodeType === 1 && matches.call(node, parser.parseSelectorsForNode(node)); - } - }; - importer.observer.addCallback = dynamic.added.bind(dynamic); - var matches = HTMLElement.prototype.matches || HTMLElement.prototype.matchesSelector || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector || HTMLElement.prototype.msMatchesSelector; -}); - -(function(scope) { - var initializeModules = scope.initializeModules; - var isIE = scope.isIE; - if (scope.useNative) { - return; - } - initializeModules(); - var rootDocument = scope.rootDocument; - function bootstrap() { - window.HTMLImports.importer.bootDocument(rootDocument); - } - if (document.readyState === "complete" || document.readyState === "interactive" && !window.attachEvent) { - bootstrap(); - } else { - document.addEventListener("DOMContentLoaded", bootstrap); - } -})(window.HTMLImports); - -window.CustomElements = window.CustomElements || { - flags: {} -}; - -(function(scope) { - var flags = scope.flags; - var modules = []; - var addModule = function(module) { - modules.push(module); - }; - var initializeModules = function() { - modules.forEach(function(module) { - module(scope); - }); - }; - scope.addModule = addModule; - scope.initializeModules = initializeModules; - scope.hasNative = Boolean(document.registerElement); - scope.isIE = /Trident/.test(navigator.userAgent); - scope.useNative = !flags.register && scope.hasNative && !window.ShadowDOMPolyfill && (!window.HTMLImports || window.HTMLImports.useNative); -})(window.CustomElements); - -window.CustomElements.addModule(function(scope) { - var IMPORT_LINK_TYPE = window.HTMLImports ? window.HTMLImports.IMPORT_LINK_TYPE : "none"; - function forSubtree(node, cb) { - findAllElements(node, function(e) { - if (cb(e)) { - return true; - } - forRoots(e, cb); - }); - forRoots(node, cb); - } - function findAllElements(node, find, data) { - var e = node.firstElementChild; - if (!e) { - e = node.firstChild; - while (e && e.nodeType !== Node.ELEMENT_NODE) { - e = e.nextSibling; - } - } - while (e) { - if (find(e, data) !== true) { - findAllElements(e, find, data); - } - e = e.nextElementSibling; - } - return null; - } - function forRoots(node, cb) { - var root = node.shadowRoot; - while (root) { - forSubtree(root, cb); - root = root.olderShadowRoot; - } - } - function forDocumentTree(doc, cb) { - _forDocumentTree(doc, cb, []); - } - function _forDocumentTree(doc, cb, processingDocuments) { - doc = window.wrap(doc); - if (processingDocuments.indexOf(doc) >= 0) { - return; - } - processingDocuments.push(doc); - var imports = doc.querySelectorAll("link[rel=" + IMPORT_LINK_TYPE + "]"); - for (var i = 0, l = imports.length, n; i < l && (n = imports[i]); i++) { - if (n.import) { - _forDocumentTree(n.import, cb, processingDocuments); - } - } - cb(doc); - } - scope.forDocumentTree = forDocumentTree; - scope.forSubtree = forSubtree; -}); - -window.CustomElements.addModule(function(scope) { - var flags = scope.flags; - var forSubtree = scope.forSubtree; - var forDocumentTree = scope.forDocumentTree; - function addedNode(node, isAttached) { - return added(node, isAttached) || addedSubtree(node, isAttached); - } - function added(node, isAttached) { - if (scope.upgrade(node, isAttached)) { - return true; - } - if (isAttached) { - attached(node); - } - } - function addedSubtree(node, isAttached) { - forSubtree(node, function(e) { - if (added(e, isAttached)) { - return true; - } - }); - } - var hasThrottledAttached = window.MutationObserver._isPolyfilled && flags["throttle-attached"]; - scope.hasPolyfillMutations = hasThrottledAttached; - scope.hasThrottledAttached = hasThrottledAttached; - var isPendingMutations = false; - var pendingMutations = []; - function deferMutation(fn) { - pendingMutations.push(fn); - if (!isPendingMutations) { - isPendingMutations = true; - setTimeout(takeMutations); - } - } - function takeMutations() { - isPendingMutations = false; - var $p = pendingMutations; - for (var i = 0, l = $p.length, p; i < l && (p = $p[i]); i++) { - p(); - } - pendingMutations = []; - } - function attached(element) { - if (hasThrottledAttached) { - deferMutation(function() { - _attached(element); - }); - } else { - _attached(element); - } - } - function _attached(element) { - if (element.__upgraded__ && !element.__attached) { - element.__attached = true; - if (element.attachedCallback) { - element.attachedCallback(); - } - } - } - function detachedNode(node) { - detached(node); - forSubtree(node, function(e) { - detached(e); - }); - } - function detached(element) { - if (hasThrottledAttached) { - deferMutation(function() { - _detached(element); - }); - } else { - _detached(element); - } - } - function _detached(element) { - if (element.__upgraded__ && element.__attached) { - element.__attached = false; - if (element.detachedCallback) { - element.detachedCallback(); - } - } - } - function inDocument(element) { - var p = element; - var doc = window.wrap(document); - while (p) { - if (p == doc) { - return true; - } - p = p.parentNode || p.nodeType === Node.DOCUMENT_FRAGMENT_NODE && p.host; - } - } - function watchShadow(node) { - if (node.shadowRoot && !node.shadowRoot.__watched) { - flags.dom && console.log("watching shadow-root for: ", node.localName); - var root = node.shadowRoot; - while (root) { - observe(root); - root = root.olderShadowRoot; - } - } - } - function handler(root, mutations) { - if (flags.dom) { - var mx = mutations[0]; - if (mx && mx.type === "childList" && mx.addedNodes) { - if (mx.addedNodes) { - var d = mx.addedNodes[0]; - while (d && d !== document && !d.host) { - d = d.parentNode; - } - var u = d && (d.URL || d._URL || d.host && d.host.localName) || ""; - u = u.split("/?").shift().split("/").pop(); - } - } - console.group("mutations (%d) [%s]", mutations.length, u || ""); - } - var isAttached = inDocument(root); - mutations.forEach(function(mx) { - if (mx.type === "childList") { - forEach(mx.addedNodes, function(n) { - if (!n.localName) { - return; - } - addedNode(n, isAttached); - }); - forEach(mx.removedNodes, function(n) { - if (!n.localName) { - return; - } - detachedNode(n); - }); - } - }); - flags.dom && console.groupEnd(); - } - function takeRecords(node) { - node = window.wrap(node); - if (!node) { - node = window.wrap(document); - } - while (node.parentNode) { - node = node.parentNode; - } - var observer = node.__observer; - if (observer) { - handler(node, observer.takeRecords()); - takeMutations(); - } - } - var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); - function observe(inRoot) { - if (inRoot.__observer) { - return; - } - var observer = new MutationObserver(handler.bind(this, inRoot)); - observer.observe(inRoot, { - childList: true, - subtree: true - }); - inRoot.__observer = observer; - } - function upgradeDocument(doc) { - doc = window.wrap(doc); - flags.dom && console.group("upgradeDocument: ", doc.baseURI.split("/").pop()); - var isMainDocument = doc === window.wrap(document); - addedNode(doc, isMainDocument); - observe(doc); - flags.dom && console.groupEnd(); - } - function upgradeDocumentTree(doc) { - forDocumentTree(doc, upgradeDocument); - } - var originalCreateShadowRoot = Element.prototype.createShadowRoot; - if (originalCreateShadowRoot) { - Element.prototype.createShadowRoot = function() { - var root = originalCreateShadowRoot.call(this); - window.CustomElements.watchShadow(this); - return root; - }; - } - scope.watchShadow = watchShadow; - scope.upgradeDocumentTree = upgradeDocumentTree; - scope.upgradeDocument = upgradeDocument; - scope.upgradeSubtree = addedSubtree; - scope.upgradeAll = addedNode; - scope.attached = attached; - scope.takeRecords = takeRecords; -}); - -window.CustomElements.addModule(function(scope) { - var flags = scope.flags; - function upgrade(node, isAttached) { - if (node.localName === "template") { - if (window.HTMLTemplateElement && HTMLTemplateElement.decorate) { - HTMLTemplateElement.decorate(node); - } - } - if (!node.__upgraded__ && node.nodeType === Node.ELEMENT_NODE) { - var is = node.getAttribute("is"); - var definition = scope.getRegisteredDefinition(node.localName) || scope.getRegisteredDefinition(is); - if (definition) { - if (is && definition.tag == node.localName || !is && !definition.extends) { - return upgradeWithDefinition(node, definition, isAttached); - } - } - } - } - function upgradeWithDefinition(element, definition, isAttached) { - flags.upgrade && console.group("upgrade:", element.localName); - if (definition.is) { - element.setAttribute("is", definition.is); - } - implementPrototype(element, definition); - element.__upgraded__ = true; - created(element); - if (isAttached) { - scope.attached(element); - } - scope.upgradeSubtree(element, isAttached); - flags.upgrade && console.groupEnd(); - return element; - } - function implementPrototype(element, definition) { - if (Object.__proto__) { - element.__proto__ = definition.prototype; - } else { - customMixin(element, definition.prototype, definition.native); - element.__proto__ = definition.prototype; - } - } - function customMixin(inTarget, inSrc, inNative) { - var used = {}; - var p = inSrc; - while (p !== inNative && p !== HTMLElement.prototype) { - var keys = Object.getOwnPropertyNames(p); - for (var i = 0, k; k = keys[i]; i++) { - if (!used[k]) { - Object.defineProperty(inTarget, k, Object.getOwnPropertyDescriptor(p, k)); - used[k] = 1; - } - } - p = Object.getPrototypeOf(p); - } - } - function created(element) { - if (element.createdCallback) { - element.createdCallback(); - } - } - scope.upgrade = upgrade; - scope.upgradeWithDefinition = upgradeWithDefinition; - scope.implementPrototype = implementPrototype; -}); - -window.CustomElements.addModule(function(scope) { - var isIE = scope.isIE; - var upgradeDocumentTree = scope.upgradeDocumentTree; - var upgradeAll = scope.upgradeAll; - var upgradeWithDefinition = scope.upgradeWithDefinition; - var implementPrototype = scope.implementPrototype; - var useNative = scope.useNative; - function register(name, options) { - var definition = options || {}; - if (!name) { - throw new Error("document.registerElement: first argument `name` must not be empty"); - } - if (name.indexOf("-") < 0) { - throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '" + String(name) + "'."); - } - if (isReservedTag(name)) { - throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '" + String(name) + "'. The type name is invalid."); - } - if (getRegisteredDefinition(name)) { - throw new Error("DuplicateDefinitionError: a type with name '" + String(name) + "' is already registered"); - } - if (!definition.prototype) { - definition.prototype = Object.create(HTMLElement.prototype); - } - definition.__name = name.toLowerCase(); - definition.lifecycle = definition.lifecycle || {}; - definition.ancestry = ancestry(definition.extends); - resolveTagName(definition); - resolvePrototypeChain(definition); - overrideAttributeApi(definition.prototype); - registerDefinition(definition.__name, definition); - definition.ctor = generateConstructor(definition); - definition.ctor.prototype = definition.prototype; - definition.prototype.constructor = definition.ctor; - if (scope.ready) { - upgradeDocumentTree(document); - } - return definition.ctor; - } - function overrideAttributeApi(prototype) { - if (prototype.setAttribute._polyfilled) { - return; - } - var setAttribute = prototype.setAttribute; - prototype.setAttribute = function(name, value) { - changeAttribute.call(this, name, value, setAttribute); - }; - var removeAttribute = prototype.removeAttribute; - prototype.removeAttribute = function(name) { - changeAttribute.call(this, name, null, removeAttribute); - }; - prototype.setAttribute._polyfilled = true; - } - function changeAttribute(name, value, operation) { - name = name.toLowerCase(); - var oldValue = this.getAttribute(name); - operation.apply(this, arguments); - var newValue = this.getAttribute(name); - if (this.attributeChangedCallback && newValue !== oldValue) { - this.attributeChangedCallback(name, oldValue, newValue); - } - } - function isReservedTag(name) { - for (var i = 0; i < reservedTagList.length; i++) { - if (name === reservedTagList[i]) { - return true; - } - } - } - var reservedTagList = [ "annotation-xml", "color-profile", "font-face", "font-face-src", "font-face-uri", "font-face-format", "font-face-name", "missing-glyph" ]; - function ancestry(extnds) { - var extendee = getRegisteredDefinition(extnds); - if (extendee) { - return ancestry(extendee.extends).concat([ extendee ]); - } - return []; - } - function resolveTagName(definition) { - var baseTag = definition.extends; - for (var i = 0, a; a = definition.ancestry[i]; i++) { - baseTag = a.is && a.tag; - } - definition.tag = baseTag || definition.__name; - if (baseTag) { - definition.is = definition.__name; - } - } - function resolvePrototypeChain(definition) { - if (!Object.__proto__) { - var nativePrototype = HTMLElement.prototype; - if (definition.is) { - var inst = document.createElement(definition.tag); - nativePrototype = Object.getPrototypeOf(inst); - } - var proto = definition.prototype, ancestor; - var foundPrototype = false; - while (proto) { - if (proto == nativePrototype) { - foundPrototype = true; - } - ancestor = Object.getPrototypeOf(proto); - if (ancestor) { - proto.__proto__ = ancestor; - } - proto = ancestor; - } - if (!foundPrototype) { - console.warn(definition.tag + " prototype not found in prototype chain for " + definition.is); - } - definition.native = nativePrototype; - } - } - function instantiate(definition) { - return upgradeWithDefinition(domCreateElement(definition.tag), definition); - } - var registry = {}; - function getRegisteredDefinition(name) { - if (name) { - return registry[name.toLowerCase()]; - } - } - function registerDefinition(name, definition) { - registry[name] = definition; - } - function generateConstructor(definition) { - return function() { - return instantiate(definition); - }; - } - var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; - function createElementNS(namespace, tag, typeExtension) { - if (namespace === HTML_NAMESPACE) { - return createElement(tag, typeExtension); - } else { - return domCreateElementNS(namespace, tag); - } - } - function createElement(tag, typeExtension) { - if (tag) { - tag = tag.toLowerCase(); - } - if (typeExtension) { - typeExtension = typeExtension.toLowerCase(); - } - var definition = getRegisteredDefinition(typeExtension || tag); - if (definition) { - if (tag == definition.tag && typeExtension == definition.is) { - return new definition.ctor(); - } - if (!typeExtension && !definition.is) { - return new definition.ctor(); - } - } - var element; - if (typeExtension) { - element = createElement(tag); - element.setAttribute("is", typeExtension); - return element; - } - element = domCreateElement(tag); - if (tag.indexOf("-") >= 0) { - implementPrototype(element, HTMLElement); - } - return element; - } - var domCreateElement = document.createElement.bind(document); - var domCreateElementNS = document.createElementNS.bind(document); - var isInstance; - if (!Object.__proto__ && !useNative) { - isInstance = function(obj, ctor) { - if (obj instanceof ctor) { - return true; - } - var p = obj; - while (p) { - if (p === ctor.prototype) { - return true; - } - p = p.__proto__; - } - return false; - }; - } else { - isInstance = function(obj, base) { - return obj instanceof base; - }; - } - function wrapDomMethodToForceUpgrade(obj, methodName) { - var orig = obj[methodName]; - obj[methodName] = function() { - var n = orig.apply(this, arguments); - upgradeAll(n); - return n; - }; - } - wrapDomMethodToForceUpgrade(Node.prototype, "cloneNode"); - wrapDomMethodToForceUpgrade(document, "importNode"); - if (isIE) { - (function() { - var importNode = document.importNode; - document.importNode = function() { - var n = importNode.apply(document, arguments); - if (n.nodeType == n.DOCUMENT_FRAGMENT_NODE) { - var f = document.createDocumentFragment(); - f.appendChild(n); - return f; - } else { - return n; - } - }; - })(); - } - document.registerElement = register; - document.createElement = createElement; - document.createElementNS = createElementNS; - scope.registry = registry; - scope.instanceof = isInstance; - scope.reservedTagList = reservedTagList; - scope.getRegisteredDefinition = getRegisteredDefinition; - document.register = document.registerElement; -}); - -(function(scope) { - var useNative = scope.useNative; - var initializeModules = scope.initializeModules; - var isIE = scope.isIE; - if (useNative) { - var nop = function() {}; - scope.watchShadow = nop; - scope.upgrade = nop; - scope.upgradeAll = nop; - scope.upgradeDocumentTree = nop; - scope.upgradeSubtree = nop; - scope.takeRecords = nop; - scope.instanceof = function(obj, base) { - return obj instanceof base; - }; - } else { - initializeModules(); - } - var upgradeDocumentTree = scope.upgradeDocumentTree; - var upgradeDocument = scope.upgradeDocument; - if (!window.wrap) { - if (window.ShadowDOMPolyfill) { - window.wrap = window.ShadowDOMPolyfill.wrapIfNeeded; - window.unwrap = window.ShadowDOMPolyfill.unwrapIfNeeded; - } else { - window.wrap = window.unwrap = function(node) { - return node; - }; - } - } - if (window.HTMLImports) { - window.HTMLImports.__importsParsingHook = function(elt) { - if (elt.import) { - upgradeDocument(wrap(elt.import)); - } - }; - } - function bootstrap() { - upgradeDocumentTree(window.wrap(document)); - window.CustomElements.ready = true; - var requestAnimationFrame = window.requestAnimationFrame || function(f) { - setTimeout(f, 16); - }; - requestAnimationFrame(function() { - setTimeout(function() { - window.CustomElements.readyTime = Date.now(); - if (window.HTMLImports) { - window.CustomElements.elapsed = window.CustomElements.readyTime - window.HTMLImports.readyTime; - } - document.dispatchEvent(new CustomEvent("WebComponentsReady", { - bubbles: true - })); - }); - }); - } - if (document.readyState === "complete" || scope.flags.eager) { - bootstrap(); - } else if (document.readyState === "interactive" && !window.attachEvent && (!window.HTMLImports || window.HTMLImports.ready)) { - bootstrap(); - } else { - var loadEvent = window.HTMLImports && !window.HTMLImports.ready ? "HTMLImportsLoaded" : "DOMContentLoaded"; - window.addEventListener(loadEvent, bootstrap); - } -})(window.CustomElements); - -(function(scope) { - var style = document.createElement("style"); - style.textContent = "" + "body {" + "transition: opacity ease-in 0.2s;" + " } \n" + "body[unresolved] {" + "opacity: 0; display: block; overflow: hidden; position: relative;" + " } \n"; - var head = document.querySelector("head"); - head.insertBefore(style, head.firstChild); -})(window.WebComponents); \ No newline at end of file diff --git a/lib/webcomponents.js b/lib/webcomponents.js deleted file mode 100644 index 546067f..0000000 --- a/lib/webcomponents.js +++ /dev/null @@ -1,7221 +0,0 @@ -/** - * @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.20 -(function() { - window.WebComponents = window.WebComponents || { - flags: {} - }; - var file = "webcomponents.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 = {}; - } - } - flags.shadow = flags.shadow || flags.shadowdom || flags.polyfill; - if (flags.shadow === "native") { - flags.shadow = false; - } else { - flags.shadow = flags.shadow || !HTMLElement.prototype.createShadowRoot; - } - if (flags.register) { - window.CustomElements = window.CustomElements || { - flags: {} - }; - window.CustomElements.flags.register = flags.register; - } - WebComponents.flags = flags; -})(); - -if (WebComponents.flags.shadow) { - 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; - })(); - } - window.ShadowDOMPolyfill = {}; - (function(scope) { - "use strict"; - var constructorTable = new WeakMap(); - var nativePrototypeTable = new WeakMap(); - var wrappers = Object.create(null); - function detectEval() { - if (typeof chrome !== "undefined" && chrome.app && chrome.app.runtime) { - return false; - } - if (navigator.getDeviceStorage) { - return false; - } - try { - var f = new Function("return true;"); - return f(); - } catch (ex) { - return false; - } - } - var hasEval = detectEval(); - function assert(b) { - if (!b) throw new Error("Assertion failed"); - } - var defineProperty = Object.defineProperty; - var getOwnPropertyNames = Object.getOwnPropertyNames; - var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - function mixin(to, from) { - var names = getOwnPropertyNames(from); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - defineProperty(to, name, getOwnPropertyDescriptor(from, name)); - } - return to; - } - function mixinStatics(to, from) { - var names = getOwnPropertyNames(from); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - switch (name) { - case "arguments": - case "caller": - case "length": - case "name": - case "prototype": - case "toString": - continue; - } - defineProperty(to, name, getOwnPropertyDescriptor(from, name)); - } - return to; - } - function oneOf(object, propertyNames) { - for (var i = 0; i < propertyNames.length; i++) { - if (propertyNames[i] in object) return propertyNames[i]; - } - } - var nonEnumerableDataDescriptor = { - value: undefined, - configurable: true, - enumerable: false, - writable: true - }; - function defineNonEnumerableDataProperty(object, name, value) { - nonEnumerableDataDescriptor.value = value; - defineProperty(object, name, nonEnumerableDataDescriptor); - } - getOwnPropertyNames(window); - function getWrapperConstructor(node, opt_instance) { - var nativePrototype = node.__proto__ || Object.getPrototypeOf(node); - if (isFirefox) { - try { - getOwnPropertyNames(nativePrototype); - } catch (error) { - nativePrototype = nativePrototype.__proto__; - } - } - var wrapperConstructor = constructorTable.get(nativePrototype); - if (wrapperConstructor) return wrapperConstructor; - var parentWrapperConstructor = getWrapperConstructor(nativePrototype); - var GeneratedWrapper = createWrapperConstructor(parentWrapperConstructor); - registerInternal(nativePrototype, GeneratedWrapper, opt_instance); - return GeneratedWrapper; - } - function addForwardingProperties(nativePrototype, wrapperPrototype) { - installProperty(nativePrototype, wrapperPrototype, true); - } - function registerInstanceProperties(wrapperPrototype, instanceObject) { - installProperty(instanceObject, wrapperPrototype, false); - } - var isFirefox = /Firefox/.test(navigator.userAgent); - var dummyDescriptor = { - get: function() {}, - set: function(v) {}, - configurable: true, - enumerable: true - }; - function isEventHandlerName(name) { - return /^on[a-z]+$/.test(name); - } - function isIdentifierName(name) { - return /^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(name); - } - function getGetter(name) { - return hasEval && isIdentifierName(name) ? new Function("return this.__impl4cf1e782hg__." + name) : function() { - return this.__impl4cf1e782hg__[name]; - }; - } - function getSetter(name) { - return hasEval && isIdentifierName(name) ? new Function("v", "this.__impl4cf1e782hg__." + name + " = v") : function(v) { - this.__impl4cf1e782hg__[name] = v; - }; - } - function getMethod(name) { - return hasEval && isIdentifierName(name) ? new Function("return this.__impl4cf1e782hg__." + name + ".apply(this.__impl4cf1e782hg__, arguments)") : function() { - return this.__impl4cf1e782hg__[name].apply(this.__impl4cf1e782hg__, arguments); - }; - } - function getDescriptor(source, name) { - try { - return Object.getOwnPropertyDescriptor(source, name); - } catch (ex) { - return dummyDescriptor; - } - } - var isBrokenSafari = function() { - var descr = Object.getOwnPropertyDescriptor(Node.prototype, "nodeType"); - return descr && !descr.get && !descr.set; - }(); - function installProperty(source, target, allowMethod, opt_blacklist) { - var names = getOwnPropertyNames(source); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - if (name === "polymerBlackList_") continue; - if (name in target) continue; - if (source.polymerBlackList_ && source.polymerBlackList_[name]) continue; - if (isFirefox) { - source.__lookupGetter__(name); - } - var descriptor = getDescriptor(source, name); - var getter, setter; - if (typeof descriptor.value === "function") { - if (allowMethod) { - target[name] = getMethod(name); - } - continue; - } - var isEvent = isEventHandlerName(name); - if (isEvent) getter = scope.getEventHandlerGetter(name); else getter = getGetter(name); - if (descriptor.writable || descriptor.set || isBrokenSafari) { - if (isEvent) setter = scope.getEventHandlerSetter(name); else setter = getSetter(name); - } - var configurable = isBrokenSafari || descriptor.configurable; - defineProperty(target, name, { - get: getter, - set: setter, - configurable: configurable, - enumerable: descriptor.enumerable - }); - } - } - function register(nativeConstructor, wrapperConstructor, opt_instance) { - if (nativeConstructor == null) { - return; - } - var nativePrototype = nativeConstructor.prototype; - registerInternal(nativePrototype, wrapperConstructor, opt_instance); - mixinStatics(wrapperConstructor, nativeConstructor); - } - function registerInternal(nativePrototype, wrapperConstructor, opt_instance) { - var wrapperPrototype = wrapperConstructor.prototype; - assert(constructorTable.get(nativePrototype) === undefined); - constructorTable.set(nativePrototype, wrapperConstructor); - nativePrototypeTable.set(wrapperPrototype, nativePrototype); - addForwardingProperties(nativePrototype, wrapperPrototype); - if (opt_instance) registerInstanceProperties(wrapperPrototype, opt_instance); - defineNonEnumerableDataProperty(wrapperPrototype, "constructor", wrapperConstructor); - wrapperConstructor.prototype = wrapperPrototype; - } - function isWrapperFor(wrapperConstructor, nativeConstructor) { - return constructorTable.get(nativeConstructor.prototype) === wrapperConstructor; - } - function registerObject(object) { - var nativePrototype = Object.getPrototypeOf(object); - var superWrapperConstructor = getWrapperConstructor(nativePrototype); - var GeneratedWrapper = createWrapperConstructor(superWrapperConstructor); - registerInternal(nativePrototype, GeneratedWrapper, object); - return GeneratedWrapper; - } - function createWrapperConstructor(superWrapperConstructor) { - function GeneratedWrapper(node) { - superWrapperConstructor.call(this, node); - } - var p = Object.create(superWrapperConstructor.prototype); - p.constructor = GeneratedWrapper; - GeneratedWrapper.prototype = p; - return GeneratedWrapper; - } - function isWrapper(object) { - return object && object.__impl4cf1e782hg__; - } - function isNative(object) { - return !isWrapper(object); - } - function wrap(impl) { - if (impl === null) return null; - assert(isNative(impl)); - var wrapper = impl.__wrapper8e3dd93a60__; - if (wrapper != null) { - return wrapper; - } - return impl.__wrapper8e3dd93a60__ = new (getWrapperConstructor(impl, impl))(impl); - } - function unwrap(wrapper) { - if (wrapper === null) return null; - assert(isWrapper(wrapper)); - return wrapper.__impl4cf1e782hg__; - } - function unsafeUnwrap(wrapper) { - return wrapper.__impl4cf1e782hg__; - } - function setWrapper(impl, wrapper) { - wrapper.__impl4cf1e782hg__ = impl; - impl.__wrapper8e3dd93a60__ = wrapper; - } - function unwrapIfNeeded(object) { - return object && isWrapper(object) ? unwrap(object) : object; - } - function wrapIfNeeded(object) { - return object && !isWrapper(object) ? wrap(object) : object; - } - function rewrap(node, wrapper) { - if (wrapper === null) return; - assert(isNative(node)); - assert(wrapper === undefined || isWrapper(wrapper)); - node.__wrapper8e3dd93a60__ = wrapper; - } - var getterDescriptor = { - get: undefined, - configurable: true, - enumerable: true - }; - function defineGetter(constructor, name, getter) { - getterDescriptor.get = getter; - defineProperty(constructor.prototype, name, getterDescriptor); - } - function defineWrapGetter(constructor, name) { - defineGetter(constructor, name, function() { - return wrap(this.__impl4cf1e782hg__[name]); - }); - } - function forwardMethodsToWrapper(constructors, names) { - constructors.forEach(function(constructor) { - names.forEach(function(name) { - constructor.prototype[name] = function() { - var w = wrapIfNeeded(this); - return w[name].apply(w, arguments); - }; - }); - }); - } - scope.addForwardingProperties = addForwardingProperties; - scope.assert = assert; - scope.constructorTable = constructorTable; - scope.defineGetter = defineGetter; - scope.defineWrapGetter = defineWrapGetter; - scope.forwardMethodsToWrapper = forwardMethodsToWrapper; - scope.isIdentifierName = isIdentifierName; - scope.isWrapper = isWrapper; - scope.isWrapperFor = isWrapperFor; - scope.mixin = mixin; - scope.nativePrototypeTable = nativePrototypeTable; - scope.oneOf = oneOf; - scope.registerObject = registerObject; - scope.registerWrapper = register; - scope.rewrap = rewrap; - scope.setWrapper = setWrapper; - scope.unsafeUnwrap = unsafeUnwrap; - scope.unwrap = unwrap; - scope.unwrapIfNeeded = unwrapIfNeeded; - scope.wrap = wrap; - scope.wrapIfNeeded = wrapIfNeeded; - scope.wrappers = wrappers; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - function newSplice(index, removed, addedCount) { - return { - index: index, - removed: removed, - addedCount: addedCount - }; - } - var EDIT_LEAVE = 0; - var EDIT_UPDATE = 1; - var EDIT_ADD = 2; - var EDIT_DELETE = 3; - function ArraySplice() {} - ArraySplice.prototype = { - calcEditDistances: function(current, currentStart, currentEnd, old, oldStart, oldEnd) { - var rowCount = oldEnd - oldStart + 1; - var columnCount = currentEnd - currentStart + 1; - var distances = new Array(rowCount); - for (var i = 0; i < rowCount; i++) { - distances[i] = new Array(columnCount); - distances[i][0] = i; - } - for (var j = 0; j < columnCount; j++) distances[0][j] = j; - for (var i = 1; i < rowCount; i++) { - for (var j = 1; j < columnCount; j++) { - if (this.equals(current[currentStart + j - 1], old[oldStart + i - 1])) distances[i][j] = distances[i - 1][j - 1]; else { - var north = distances[i - 1][j] + 1; - var west = distances[i][j - 1] + 1; - distances[i][j] = north < west ? north : west; - } - } - } - return distances; - }, - spliceOperationsFromEditDistances: function(distances) { - var i = distances.length - 1; - var j = distances[0].length - 1; - var current = distances[i][j]; - var edits = []; - while (i > 0 || j > 0) { - if (i == 0) { - edits.push(EDIT_ADD); - j--; - continue; - } - if (j == 0) { - edits.push(EDIT_DELETE); - i--; - continue; - } - var northWest = distances[i - 1][j - 1]; - var west = distances[i - 1][j]; - var north = distances[i][j - 1]; - var min; - if (west < north) min = west < northWest ? west : northWest; else min = north < northWest ? north : northWest; - if (min == northWest) { - if (northWest == current) { - edits.push(EDIT_LEAVE); - } else { - edits.push(EDIT_UPDATE); - current = northWest; - } - i--; - j--; - } else if (min == west) { - edits.push(EDIT_DELETE); - i--; - current = west; - } else { - edits.push(EDIT_ADD); - j--; - current = north; - } - } - edits.reverse(); - return edits; - }, - calcSplices: function(current, currentStart, currentEnd, old, oldStart, oldEnd) { - var prefixCount = 0; - var suffixCount = 0; - var minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart); - if (currentStart == 0 && oldStart == 0) prefixCount = this.sharedPrefix(current, old, minLength); - if (currentEnd == current.length && oldEnd == old.length) suffixCount = this.sharedSuffix(current, old, minLength - prefixCount); - currentStart += prefixCount; - oldStart += prefixCount; - currentEnd -= suffixCount; - oldEnd -= suffixCount; - if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0) return []; - if (currentStart == currentEnd) { - var splice = newSplice(currentStart, [], 0); - while (oldStart < oldEnd) splice.removed.push(old[oldStart++]); - return [ splice ]; - } else if (oldStart == oldEnd) return [ newSplice(currentStart, [], currentEnd - currentStart) ]; - var ops = this.spliceOperationsFromEditDistances(this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd)); - var splice = undefined; - var splices = []; - var index = currentStart; - var oldIndex = oldStart; - for (var i = 0; i < ops.length; i++) { - switch (ops[i]) { - case EDIT_LEAVE: - if (splice) { - splices.push(splice); - splice = undefined; - } - index++; - oldIndex++; - break; - - case EDIT_UPDATE: - if (!splice) splice = newSplice(index, [], 0); - splice.addedCount++; - index++; - splice.removed.push(old[oldIndex]); - oldIndex++; - break; - - case EDIT_ADD: - if (!splice) splice = newSplice(index, [], 0); - splice.addedCount++; - index++; - break; - - case EDIT_DELETE: - if (!splice) splice = newSplice(index, [], 0); - splice.removed.push(old[oldIndex]); - oldIndex++; - break; - } - } - if (splice) { - splices.push(splice); - } - return splices; - }, - sharedPrefix: function(current, old, searchLength) { - for (var i = 0; i < searchLength; i++) if (!this.equals(current[i], old[i])) return i; - return searchLength; - }, - sharedSuffix: function(current, old, searchLength) { - var index1 = current.length; - var index2 = old.length; - var count = 0; - while (count < searchLength && this.equals(current[--index1], old[--index2])) count++; - return count; - }, - calculateSplices: function(current, previous) { - return this.calcSplices(current, 0, current.length, previous, 0, previous.length); - }, - equals: function(currentValue, previousValue) { - return currentValue === previousValue; - } - }; - scope.ArraySplice = ArraySplice; - })(window.ShadowDOMPolyfill); - (function(context) { - "use strict"; - var OriginalMutationObserver = window.MutationObserver; - var callbacks = []; - var pending = false; - var timerFunc; - function handle() { - pending = false; - var copies = callbacks.slice(0); - callbacks = []; - for (var i = 0; i < copies.length; i++) { - (0, copies[i])(); - } - } - if (OriginalMutationObserver) { - var counter = 1; - var observer = new OriginalMutationObserver(handle); - var textNode = document.createTextNode(counter); - observer.observe(textNode, { - characterData: true - }); - timerFunc = function() { - counter = (counter + 1) % 2; - textNode.data = counter; - }; - } else { - timerFunc = window.setTimeout; - } - function setEndOfMicrotask(func) { - callbacks.push(func); - if (pending) return; - pending = true; - timerFunc(handle, 0); - } - context.setEndOfMicrotask = setEndOfMicrotask; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var setEndOfMicrotask = scope.setEndOfMicrotask; - var wrapIfNeeded = scope.wrapIfNeeded; - var wrappers = scope.wrappers; - var registrationsTable = new WeakMap(); - var globalMutationObservers = []; - var isScheduled = false; - function scheduleCallback(observer) { - if (observer.scheduled_) return; - observer.scheduled_ = true; - globalMutationObservers.push(observer); - if (isScheduled) return; - setEndOfMicrotask(notifyObservers); - isScheduled = true; - } - function notifyObservers() { - isScheduled = false; - while (globalMutationObservers.length) { - var notifyList = globalMutationObservers; - globalMutationObservers = []; - notifyList.sort(function(x, y) { - return x.uid_ - y.uid_; - }); - for (var i = 0; i < notifyList.length; i++) { - var mo = notifyList[i]; - mo.scheduled_ = false; - var queue = mo.takeRecords(); - removeTransientObserversFor(mo); - if (queue.length) { - mo.callback_(queue, mo); - } - } - } - } - function MutationRecord(type, target) { - this.type = type; - this.target = target; - this.addedNodes = new wrappers.NodeList(); - this.removedNodes = new wrappers.NodeList(); - this.previousSibling = null; - this.nextSibling = null; - this.attributeName = null; - this.attributeNamespace = null; - this.oldValue = null; - } - function registerTransientObservers(ancestor, node) { - for (;ancestor; ancestor = ancestor.parentNode) { - var registrations = registrationsTable.get(ancestor); - if (!registrations) continue; - for (var i = 0; i < registrations.length; i++) { - var registration = registrations[i]; - if (registration.options.subtree) registration.addTransientObserver(node); - } - } - } - function removeTransientObserversFor(observer) { - for (var i = 0; i < observer.nodes_.length; i++) { - var node = observer.nodes_[i]; - var registrations = registrationsTable.get(node); - if (!registrations) return; - for (var j = 0; j < registrations.length; j++) { - var registration = registrations[j]; - if (registration.observer === observer) registration.removeTransientObservers(); - } - } - } - function enqueueMutation(target, type, data) { - var interestedObservers = Object.create(null); - var associatedStrings = Object.create(null); - for (var node = target; node; node = node.parentNode) { - var registrations = registrationsTable.get(node); - if (!registrations) continue; - for (var j = 0; j < registrations.length; j++) { - var registration = registrations[j]; - var options = registration.options; - if (node !== target && !options.subtree) continue; - if (type === "attributes" && !options.attributes) continue; - if (type === "attributes" && options.attributeFilter && (data.namespace !== null || options.attributeFilter.indexOf(data.name) === -1)) { - continue; - } - if (type === "characterData" && !options.characterData) continue; - if (type === "childList" && !options.childList) continue; - var observer = registration.observer; - interestedObservers[observer.uid_] = observer; - if (type === "attributes" && options.attributeOldValue || type === "characterData" && options.characterDataOldValue) { - associatedStrings[observer.uid_] = data.oldValue; - } - } - } - for (var uid in interestedObservers) { - var observer = interestedObservers[uid]; - var record = new MutationRecord(type, target); - if ("name" in data && "namespace" in data) { - record.attributeName = data.name; - record.attributeNamespace = data.namespace; - } - if (data.addedNodes) record.addedNodes = data.addedNodes; - if (data.removedNodes) record.removedNodes = data.removedNodes; - if (data.previousSibling) record.previousSibling = data.previousSibling; - if (data.nextSibling) record.nextSibling = data.nextSibling; - if (associatedStrings[uid] !== undefined) record.oldValue = associatedStrings[uid]; - scheduleCallback(observer); - observer.records_.push(record); - } - } - var slice = Array.prototype.slice; - function MutationObserverOptions(options) { - this.childList = !!options.childList; - this.subtree = !!options.subtree; - if (!("attributes" in options) && ("attributeOldValue" in options || "attributeFilter" in options)) { - this.attributes = true; - } else { - this.attributes = !!options.attributes; - } - if ("characterDataOldValue" in options && !("characterData" in options)) this.characterData = true; else this.characterData = !!options.characterData; - if (!this.attributes && (options.attributeOldValue || "attributeFilter" in options) || !this.characterData && options.characterDataOldValue) { - throw new TypeError(); - } - this.characterData = !!options.characterData; - this.attributeOldValue = !!options.attributeOldValue; - this.characterDataOldValue = !!options.characterDataOldValue; - if ("attributeFilter" in options) { - if (options.attributeFilter == null || typeof options.attributeFilter !== "object") { - throw new TypeError(); - } - this.attributeFilter = slice.call(options.attributeFilter); - } else { - this.attributeFilter = null; - } - } - var uidCounter = 0; - function MutationObserver(callback) { - this.callback_ = callback; - this.nodes_ = []; - this.records_ = []; - this.uid_ = ++uidCounter; - this.scheduled_ = false; - } - MutationObserver.prototype = { - constructor: MutationObserver, - observe: function(target, options) { - target = wrapIfNeeded(target); - var newOptions = new MutationObserverOptions(options); - var registration; - var registrations = registrationsTable.get(target); - if (!registrations) registrationsTable.set(target, registrations = []); - for (var i = 0; i < registrations.length; i++) { - if (registrations[i].observer === this) { - registration = registrations[i]; - registration.removeTransientObservers(); - registration.options = newOptions; - } - } - if (!registration) { - registration = new Registration(this, target, newOptions); - registrations.push(registration); - this.nodes_.push(target); - } - }, - 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) { - registrations.splice(i, 1); - break; - } - } - }, this); - this.records_ = []; - }, - takeRecords: function() { - var copyOfRecords = this.records_; - this.records_ = []; - return copyOfRecords; - } - }; - function Registration(observer, target, options) { - this.observer = observer; - this.target = target; - this.options = options; - this.transientObservedNodes = []; - } - Registration.prototype = { - addTransientObserver: function(node) { - if (node === this.target) return; - scheduleCallback(this.observer); - 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 = []; - for (var i = 0; i < transientObservedNodes.length; i++) { - var node = transientObservedNodes[i]; - var registrations = registrationsTable.get(node); - for (var j = 0; j < registrations.length; j++) { - if (registrations[j] === this) { - registrations.splice(j, 1); - break; - } - } - } - } - }; - scope.enqueueMutation = enqueueMutation; - scope.registerTransientObservers = registerTransientObservers; - scope.wrappers.MutationObserver = MutationObserver; - scope.wrappers.MutationRecord = MutationRecord; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - function TreeScope(root, parent) { - this.root = root; - this.parent = parent; - } - TreeScope.prototype = { - get renderer() { - if (this.root instanceof scope.wrappers.ShadowRoot) { - return scope.getRendererForHost(this.root.host); - } - return null; - }, - contains: function(treeScope) { - for (;treeScope; treeScope = treeScope.parent) { - if (treeScope === this) return true; - } - return false; - } - }; - function setTreeScope(node, treeScope) { - if (node.treeScope_ !== treeScope) { - node.treeScope_ = treeScope; - for (var sr = node.shadowRoot; sr; sr = sr.olderShadowRoot) { - sr.treeScope_.parent = treeScope; - } - for (var child = node.firstChild; child; child = child.nextSibling) { - setTreeScope(child, treeScope); - } - } - } - function getTreeScope(node) { - if (node instanceof scope.wrappers.Window) { - debugger; - } - if (node.treeScope_) return node.treeScope_; - var parent = node.parentNode; - var treeScope; - if (parent) treeScope = getTreeScope(parent); else treeScope = new TreeScope(node, null); - return node.treeScope_ = treeScope; - } - scope.TreeScope = TreeScope; - scope.getTreeScope = getTreeScope; - scope.setTreeScope = setTreeScope; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var forwardMethodsToWrapper = scope.forwardMethodsToWrapper; - var getTreeScope = scope.getTreeScope; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var wrappers = scope.wrappers; - var wrappedFuns = new WeakMap(); - var listenersTable = new WeakMap(); - var handledEventsTable = new WeakMap(); - var currentlyDispatchingEvents = new WeakMap(); - var targetTable = new WeakMap(); - var currentTargetTable = new WeakMap(); - var relatedTargetTable = new WeakMap(); - var eventPhaseTable = new WeakMap(); - var stopPropagationTable = new WeakMap(); - var stopImmediatePropagationTable = new WeakMap(); - var eventHandlersTable = new WeakMap(); - var eventPathTable = new WeakMap(); - function isShadowRoot(node) { - return node instanceof wrappers.ShadowRoot; - } - function rootOfNode(node) { - return getTreeScope(node).root; - } - function getEventPath(node, event) { - var path = []; - var current = node; - path.push(current); - while (current) { - var destinationInsertionPoints = getDestinationInsertionPoints(current); - if (destinationInsertionPoints && destinationInsertionPoints.length > 0) { - for (var i = 0; i < destinationInsertionPoints.length; i++) { - var insertionPoint = destinationInsertionPoints[i]; - if (isShadowInsertionPoint(insertionPoint)) { - var shadowRoot = rootOfNode(insertionPoint); - var olderShadowRoot = shadowRoot.olderShadowRoot; - if (olderShadowRoot) path.push(olderShadowRoot); - } - path.push(insertionPoint); - } - current = destinationInsertionPoints[destinationInsertionPoints.length - 1]; - } else { - if (isShadowRoot(current)) { - if (inSameTree(node, current) && eventMustBeStopped(event)) { - break; - } - current = current.host; - path.push(current); - } else { - current = current.parentNode; - if (current) path.push(current); - } - } - } - return path; - } - function eventMustBeStopped(event) { - if (!event) return false; - switch (event.type) { - case "abort": - case "error": - case "select": - case "change": - case "load": - case "reset": - case "resize": - case "scroll": - case "selectstart": - return true; - } - return false; - } - function isShadowInsertionPoint(node) { - return node instanceof HTMLShadowElement; - } - function getDestinationInsertionPoints(node) { - return scope.getDestinationInsertionPoints(node); - } - function eventRetargetting(path, currentTarget) { - if (path.length === 0) return currentTarget; - if (currentTarget instanceof wrappers.Window) currentTarget = currentTarget.document; - var currentTargetTree = getTreeScope(currentTarget); - var originalTarget = path[0]; - var originalTargetTree = getTreeScope(originalTarget); - var relativeTargetTree = lowestCommonInclusiveAncestor(currentTargetTree, originalTargetTree); - for (var i = 0; i < path.length; i++) { - var node = path[i]; - if (getTreeScope(node) === relativeTargetTree) return node; - } - return path[path.length - 1]; - } - function getTreeScopeAncestors(treeScope) { - var ancestors = []; - for (;treeScope; treeScope = treeScope.parent) { - ancestors.push(treeScope); - } - return ancestors; - } - function lowestCommonInclusiveAncestor(tsA, tsB) { - var ancestorsA = getTreeScopeAncestors(tsA); - var ancestorsB = getTreeScopeAncestors(tsB); - var result = null; - while (ancestorsA.length > 0 && ancestorsB.length > 0) { - var a = ancestorsA.pop(); - var b = ancestorsB.pop(); - if (a === b) result = a; else break; - } - return result; - } - function getTreeScopeRoot(ts) { - if (!ts.parent) return ts; - return getTreeScopeRoot(ts.parent); - } - function relatedTargetResolution(event, currentTarget, relatedTarget) { - if (currentTarget instanceof wrappers.Window) currentTarget = currentTarget.document; - var currentTargetTree = getTreeScope(currentTarget); - var relatedTargetTree = getTreeScope(relatedTarget); - var relatedTargetEventPath = getEventPath(relatedTarget, event); - var lowestCommonAncestorTree; - var lowestCommonAncestorTree = lowestCommonInclusiveAncestor(currentTargetTree, relatedTargetTree); - if (!lowestCommonAncestorTree) lowestCommonAncestorTree = relatedTargetTree.root; - for (var commonAncestorTree = lowestCommonAncestorTree; commonAncestorTree; commonAncestorTree = commonAncestorTree.parent) { - var adjustedRelatedTarget; - for (var i = 0; i < relatedTargetEventPath.length; i++) { - var node = relatedTargetEventPath[i]; - if (getTreeScope(node) === commonAncestorTree) return node; - } - } - return null; - } - function inSameTree(a, b) { - return getTreeScope(a) === getTreeScope(b); - } - var NONE = 0; - var CAPTURING_PHASE = 1; - var AT_TARGET = 2; - var BUBBLING_PHASE = 3; - var pendingError; - function dispatchOriginalEvent(originalEvent) { - if (handledEventsTable.get(originalEvent)) return; - handledEventsTable.set(originalEvent, true); - dispatchEvent(wrap(originalEvent), wrap(originalEvent.target)); - if (pendingError) { - var err = pendingError; - pendingError = null; - throw err; - } - } - function isLoadLikeEvent(event) { - switch (event.type) { - case "load": - case "beforeunload": - case "unload": - return true; - } - return false; - } - function dispatchEvent(event, originalWrapperTarget) { - if (currentlyDispatchingEvents.get(event)) throw new Error("InvalidStateError"); - currentlyDispatchingEvents.set(event, true); - scope.renderAllPending(); - var eventPath; - var overrideTarget; - var win; - if (isLoadLikeEvent(event) && !event.bubbles) { - var doc = originalWrapperTarget; - if (doc instanceof wrappers.Document && (win = doc.defaultView)) { - overrideTarget = doc; - eventPath = []; - } - } - if (!eventPath) { - if (originalWrapperTarget instanceof wrappers.Window) { - win = originalWrapperTarget; - eventPath = []; - } else { - eventPath = getEventPath(originalWrapperTarget, event); - if (!isLoadLikeEvent(event)) { - var doc = eventPath[eventPath.length - 1]; - if (doc instanceof wrappers.Document) win = doc.defaultView; - } - } - } - eventPathTable.set(event, eventPath); - if (dispatchCapturing(event, eventPath, win, overrideTarget)) { - if (dispatchAtTarget(event, eventPath, win, overrideTarget)) { - dispatchBubbling(event, eventPath, win, overrideTarget); - } - } - eventPhaseTable.set(event, NONE); - currentTargetTable.delete(event, null); - currentlyDispatchingEvents.delete(event); - return event.defaultPrevented; - } - function dispatchCapturing(event, eventPath, win, overrideTarget) { - var phase = CAPTURING_PHASE; - if (win) { - if (!invoke(win, event, phase, eventPath, overrideTarget)) return false; - } - for (var i = eventPath.length - 1; i > 0; i--) { - if (!invoke(eventPath[i], event, phase, eventPath, overrideTarget)) return false; - } - return true; - } - function dispatchAtTarget(event, eventPath, win, overrideTarget) { - var phase = AT_TARGET; - var currentTarget = eventPath[0] || win; - return invoke(currentTarget, event, phase, eventPath, overrideTarget); - } - function dispatchBubbling(event, eventPath, win, overrideTarget) { - var phase = BUBBLING_PHASE; - for (var i = 1; i < eventPath.length; i++) { - if (!invoke(eventPath[i], event, phase, eventPath, overrideTarget)) return; - } - if (win && eventPath.length > 0) { - invoke(win, event, phase, eventPath, overrideTarget); - } - } - function invoke(currentTarget, event, phase, eventPath, overrideTarget) { - var listeners = listenersTable.get(currentTarget); - if (!listeners) return true; - var target = overrideTarget || eventRetargetting(eventPath, currentTarget); - if (target === currentTarget) { - if (phase === CAPTURING_PHASE) return true; - if (phase === BUBBLING_PHASE) phase = AT_TARGET; - } else if (phase === BUBBLING_PHASE && !event.bubbles) { - return true; - } - if ("relatedTarget" in event) { - var originalEvent = unwrap(event); - var unwrappedRelatedTarget = originalEvent.relatedTarget; - if (unwrappedRelatedTarget) { - if (unwrappedRelatedTarget instanceof Object && unwrappedRelatedTarget.addEventListener) { - var relatedTarget = wrap(unwrappedRelatedTarget); - var adjusted = relatedTargetResolution(event, currentTarget, relatedTarget); - if (adjusted === target) return true; - } else { - adjusted = null; - } - relatedTargetTable.set(event, adjusted); - } - } - eventPhaseTable.set(event, phase); - var type = event.type; - var anyRemoved = false; - targetTable.set(event, target); - currentTargetTable.set(event, currentTarget); - listeners.depth++; - for (var i = 0, len = listeners.length; i < len; i++) { - var listener = listeners[i]; - if (listener.removed) { - anyRemoved = true; - continue; - } - if (listener.type !== type || !listener.capture && phase === CAPTURING_PHASE || listener.capture && phase === BUBBLING_PHASE) { - continue; - } - try { - if (typeof listener.handler === "function") listener.handler.call(currentTarget, event); else listener.handler.handleEvent(event); - if (stopImmediatePropagationTable.get(event)) return false; - } catch (ex) { - if (!pendingError) pendingError = ex; - } - } - listeners.depth--; - if (anyRemoved && listeners.depth === 0) { - var copy = listeners.slice(); - listeners.length = 0; - for (var i = 0; i < copy.length; i++) { - if (!copy[i].removed) listeners.push(copy[i]); - } - } - return !stopPropagationTable.get(event); - } - function Listener(type, handler, capture) { - this.type = type; - this.handler = handler; - this.capture = Boolean(capture); - } - Listener.prototype = { - equals: function(that) { - return this.handler === that.handler && this.type === that.type && this.capture === that.capture; - }, - get removed() { - return this.handler === null; - }, - remove: function() { - this.handler = null; - } - }; - var OriginalEvent = window.Event; - OriginalEvent.prototype.polymerBlackList_ = { - returnValue: true, - keyLocation: true - }; - function Event(type, options) { - if (type instanceof OriginalEvent) { - var impl = type; - if (!OriginalBeforeUnloadEvent && impl.type === "beforeunload" && !(this instanceof BeforeUnloadEvent)) { - return new BeforeUnloadEvent(impl); - } - setWrapper(impl, this); - } else { - return wrap(constructEvent(OriginalEvent, "Event", type, options)); - } - } - Event.prototype = { - get target() { - return targetTable.get(this); - }, - get currentTarget() { - return currentTargetTable.get(this); - }, - get eventPhase() { - return eventPhaseTable.get(this); - }, - get path() { - var eventPath = eventPathTable.get(this); - if (!eventPath) return []; - return eventPath.slice(); - }, - stopPropagation: function() { - stopPropagationTable.set(this, true); - }, - stopImmediatePropagation: function() { - stopPropagationTable.set(this, true); - stopImmediatePropagationTable.set(this, true); - } - }; - var supportsDefaultPrevented = function() { - var e = document.createEvent("Event"); - e.initEvent("test", true, true); - e.preventDefault(); - return e.defaultPrevented; - }(); - if (!supportsDefaultPrevented) { - Event.prototype.preventDefault = function() { - if (!this.cancelable) return; - unsafeUnwrap(this).preventDefault(); - Object.defineProperty(this, "defaultPrevented", { - get: function() { - return true; - }, - configurable: true - }); - }; - } - registerWrapper(OriginalEvent, Event, document.createEvent("Event")); - function unwrapOptions(options) { - if (!options || !options.relatedTarget) return options; - return Object.create(options, { - relatedTarget: { - value: unwrap(options.relatedTarget) - } - }); - } - function registerGenericEvent(name, SuperEvent, prototype) { - var OriginalEvent = window[name]; - var GenericEvent = function(type, options) { - if (type instanceof OriginalEvent) setWrapper(type, this); else return wrap(constructEvent(OriginalEvent, name, type, options)); - }; - GenericEvent.prototype = Object.create(SuperEvent.prototype); - if (prototype) mixin(GenericEvent.prototype, prototype); - if (OriginalEvent) { - try { - registerWrapper(OriginalEvent, GenericEvent, new OriginalEvent("temp")); - } catch (ex) { - registerWrapper(OriginalEvent, GenericEvent, document.createEvent(name)); - } - } - return GenericEvent; - } - var UIEvent = registerGenericEvent("UIEvent", Event); - var CustomEvent = registerGenericEvent("CustomEvent", Event); - var relatedTargetProto = { - get relatedTarget() { - var relatedTarget = relatedTargetTable.get(this); - if (relatedTarget !== undefined) return relatedTarget; - return wrap(unwrap(this).relatedTarget); - } - }; - function getInitFunction(name, relatedTargetIndex) { - return function() { - arguments[relatedTargetIndex] = unwrap(arguments[relatedTargetIndex]); - var impl = unwrap(this); - impl[name].apply(impl, arguments); - }; - } - var mouseEventProto = mixin({ - initMouseEvent: getInitFunction("initMouseEvent", 14) - }, relatedTargetProto); - var focusEventProto = mixin({ - initFocusEvent: getInitFunction("initFocusEvent", 5) - }, relatedTargetProto); - var MouseEvent = registerGenericEvent("MouseEvent", UIEvent, mouseEventProto); - var FocusEvent = registerGenericEvent("FocusEvent", UIEvent, focusEventProto); - var defaultInitDicts = Object.create(null); - var supportsEventConstructors = function() { - try { - new window.FocusEvent("focus"); - } catch (ex) { - return false; - } - return true; - }(); - function constructEvent(OriginalEvent, name, type, options) { - if (supportsEventConstructors) return new OriginalEvent(type, unwrapOptions(options)); - var event = unwrap(document.createEvent(name)); - var defaultDict = defaultInitDicts[name]; - var args = [ type ]; - Object.keys(defaultDict).forEach(function(key) { - var v = options != null && key in options ? options[key] : defaultDict[key]; - if (key === "relatedTarget") v = unwrap(v); - args.push(v); - }); - event["init" + name].apply(event, args); - return event; - } - if (!supportsEventConstructors) { - var configureEventConstructor = function(name, initDict, superName) { - if (superName) { - var superDict = defaultInitDicts[superName]; - initDict = mixin(mixin({}, superDict), initDict); - } - defaultInitDicts[name] = initDict; - }; - configureEventConstructor("Event", { - bubbles: false, - cancelable: false - }); - configureEventConstructor("CustomEvent", { - detail: null - }, "Event"); - configureEventConstructor("UIEvent", { - view: null, - detail: 0 - }, "Event"); - configureEventConstructor("MouseEvent", { - screenX: 0, - screenY: 0, - clientX: 0, - clientY: 0, - ctrlKey: false, - altKey: false, - shiftKey: false, - metaKey: false, - button: 0, - relatedTarget: null - }, "UIEvent"); - configureEventConstructor("FocusEvent", { - relatedTarget: null - }, "UIEvent"); - } - var OriginalBeforeUnloadEvent = window.BeforeUnloadEvent; - function BeforeUnloadEvent(impl) { - Event.call(this, impl); - } - BeforeUnloadEvent.prototype = Object.create(Event.prototype); - mixin(BeforeUnloadEvent.prototype, { - get returnValue() { - return unsafeUnwrap(this).returnValue; - }, - set returnValue(v) { - unsafeUnwrap(this).returnValue = v; - } - }); - if (OriginalBeforeUnloadEvent) registerWrapper(OriginalBeforeUnloadEvent, BeforeUnloadEvent); - function isValidListener(fun) { - if (typeof fun === "function") return true; - return fun && fun.handleEvent; - } - function isMutationEvent(type) { - switch (type) { - case "DOMAttrModified": - case "DOMAttributeNameChanged": - case "DOMCharacterDataModified": - case "DOMElementNameChanged": - case "DOMNodeInserted": - case "DOMNodeInsertedIntoDocument": - case "DOMNodeRemoved": - case "DOMNodeRemovedFromDocument": - case "DOMSubtreeModified": - return true; - } - return false; - } - var OriginalEventTarget = window.EventTarget; - function EventTarget(impl) { - setWrapper(impl, this); - } - var methodNames = [ "addEventListener", "removeEventListener", "dispatchEvent" ]; - [ Node, Window ].forEach(function(constructor) { - var p = constructor.prototype; - methodNames.forEach(function(name) { - Object.defineProperty(p, name + "_", { - value: p[name] - }); - }); - }); - function getTargetToListenAt(wrapper) { - if (wrapper instanceof wrappers.ShadowRoot) wrapper = wrapper.host; - return unwrap(wrapper); - } - EventTarget.prototype = { - addEventListener: function(type, fun, capture) { - if (!isValidListener(fun) || isMutationEvent(type)) return; - var listener = new Listener(type, fun, capture); - var listeners = listenersTable.get(this); - if (!listeners) { - listeners = []; - listeners.depth = 0; - listenersTable.set(this, listeners); - } else { - for (var i = 0; i < listeners.length; i++) { - if (listener.equals(listeners[i])) return; - } - } - listeners.push(listener); - var target = getTargetToListenAt(this); - target.addEventListener_(type, dispatchOriginalEvent, true); - }, - removeEventListener: function(type, fun, capture) { - capture = Boolean(capture); - var listeners = listenersTable.get(this); - if (!listeners) return; - var count = 0, found = false; - for (var i = 0; i < listeners.length; i++) { - if (listeners[i].type === type && listeners[i].capture === capture) { - count++; - if (listeners[i].handler === fun) { - found = true; - listeners[i].remove(); - } - } - } - if (found && count === 1) { - var target = getTargetToListenAt(this); - target.removeEventListener_(type, dispatchOriginalEvent, true); - } - }, - dispatchEvent: function(event) { - var nativeEvent = unwrap(event); - var eventType = nativeEvent.type; - handledEventsTable.set(nativeEvent, false); - scope.renderAllPending(); - var tempListener; - if (!hasListenerInAncestors(this, eventType)) { - tempListener = function() {}; - this.addEventListener(eventType, tempListener, true); - } - try { - return unwrap(this).dispatchEvent_(nativeEvent); - } finally { - if (tempListener) this.removeEventListener(eventType, tempListener, true); - } - } - }; - function hasListener(node, type) { - var listeners = listenersTable.get(node); - if (listeners) { - for (var i = 0; i < listeners.length; i++) { - if (!listeners[i].removed && listeners[i].type === type) return true; - } - } - return false; - } - function hasListenerInAncestors(target, type) { - for (var node = unwrap(target); node; node = node.parentNode) { - if (hasListener(wrap(node), type)) return true; - } - return false; - } - if (OriginalEventTarget) registerWrapper(OriginalEventTarget, EventTarget); - function wrapEventTargetMethods(constructors) { - forwardMethodsToWrapper(constructors, methodNames); - } - var originalElementFromPoint = document.elementFromPoint; - function elementFromPoint(self, document, x, y) { - scope.renderAllPending(); - var element = wrap(originalElementFromPoint.call(unsafeUnwrap(document), x, y)); - if (!element) return null; - var path = getEventPath(element, null); - var idx = path.lastIndexOf(self); - if (idx == -1) return null; else path = path.slice(0, idx); - return eventRetargetting(path, self); - } - function getEventHandlerGetter(name) { - return function() { - var inlineEventHandlers = eventHandlersTable.get(this); - return inlineEventHandlers && inlineEventHandlers[name] && inlineEventHandlers[name].value || null; - }; - } - function getEventHandlerSetter(name) { - var eventType = name.slice(2); - return function(value) { - var inlineEventHandlers = eventHandlersTable.get(this); - if (!inlineEventHandlers) { - inlineEventHandlers = Object.create(null); - eventHandlersTable.set(this, inlineEventHandlers); - } - var old = inlineEventHandlers[name]; - if (old) this.removeEventListener(eventType, old.wrapped, false); - if (typeof value === "function") { - var wrapped = function(e) { - var rv = value.call(this, e); - if (rv === false) e.preventDefault(); else if (name === "onbeforeunload" && typeof rv === "string") e.returnValue = rv; - }; - this.addEventListener(eventType, wrapped, false); - inlineEventHandlers[name] = { - value: value, - wrapped: wrapped - }; - } - }; - } - scope.elementFromPoint = elementFromPoint; - scope.getEventHandlerGetter = getEventHandlerGetter; - scope.getEventHandlerSetter = getEventHandlerSetter; - scope.wrapEventTargetMethods = wrapEventTargetMethods; - scope.wrappers.BeforeUnloadEvent = BeforeUnloadEvent; - scope.wrappers.CustomEvent = CustomEvent; - scope.wrappers.Event = Event; - scope.wrappers.EventTarget = EventTarget; - scope.wrappers.FocusEvent = FocusEvent; - scope.wrappers.MouseEvent = MouseEvent; - scope.wrappers.UIEvent = UIEvent; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var UIEvent = scope.wrappers.UIEvent; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrap = scope.wrap; - var OriginalTouchEvent = window.TouchEvent; - if (!OriginalTouchEvent) return; - var nativeEvent; - try { - nativeEvent = document.createEvent("TouchEvent"); - } catch (ex) { - return; - } - var nonEnumDescriptor = { - enumerable: false - }; - function nonEnum(obj, prop) { - Object.defineProperty(obj, prop, nonEnumDescriptor); - } - function Touch(impl) { - setWrapper(impl, this); - } - Touch.prototype = { - get target() { - return wrap(unsafeUnwrap(this).target); - } - }; - var descr = { - configurable: true, - enumerable: true, - get: null - }; - [ "clientX", "clientY", "screenX", "screenY", "pageX", "pageY", "identifier", "webkitRadiusX", "webkitRadiusY", "webkitRotationAngle", "webkitForce" ].forEach(function(name) { - descr.get = function() { - return unsafeUnwrap(this)[name]; - }; - Object.defineProperty(Touch.prototype, name, descr); - }); - function TouchList() { - this.length = 0; - nonEnum(this, "length"); - } - TouchList.prototype = { - item: function(index) { - return this[index]; - } - }; - function wrapTouchList(nativeTouchList) { - var list = new TouchList(); - for (var i = 0; i < nativeTouchList.length; i++) { - list[i] = new Touch(nativeTouchList[i]); - } - list.length = i; - return list; - } - function TouchEvent(impl) { - UIEvent.call(this, impl); - } - TouchEvent.prototype = Object.create(UIEvent.prototype); - mixin(TouchEvent.prototype, { - get touches() { - return wrapTouchList(unsafeUnwrap(this).touches); - }, - get targetTouches() { - return wrapTouchList(unsafeUnwrap(this).targetTouches); - }, - get changedTouches() { - return wrapTouchList(unsafeUnwrap(this).changedTouches); - }, - initTouchEvent: function() { - throw new Error("Not implemented"); - } - }); - registerWrapper(OriginalTouchEvent, TouchEvent, nativeEvent); - scope.wrappers.Touch = Touch; - scope.wrappers.TouchEvent = TouchEvent; - scope.wrappers.TouchList = TouchList; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrap = scope.wrap; - var nonEnumDescriptor = { - enumerable: false - }; - function nonEnum(obj, prop) { - Object.defineProperty(obj, prop, nonEnumDescriptor); - } - function NodeList() { - this.length = 0; - nonEnum(this, "length"); - } - NodeList.prototype = { - item: function(index) { - return this[index]; - } - }; - nonEnum(NodeList.prototype, "item"); - function wrapNodeList(list) { - if (list == null) return list; - var wrapperList = new NodeList(); - for (var i = 0, length = list.length; i < length; i++) { - wrapperList[i] = wrap(list[i]); - } - wrapperList.length = length; - return wrapperList; - } - function addWrapNodeListMethod(wrapperConstructor, name) { - wrapperConstructor.prototype[name] = function() { - return wrapNodeList(unsafeUnwrap(this)[name].apply(unsafeUnwrap(this), arguments)); - }; - } - scope.wrappers.NodeList = NodeList; - scope.addWrapNodeListMethod = addWrapNodeListMethod; - scope.wrapNodeList = wrapNodeList; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - scope.wrapHTMLCollection = scope.wrapNodeList; - scope.wrappers.HTMLCollection = scope.wrappers.NodeList; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var EventTarget = scope.wrappers.EventTarget; - var NodeList = scope.wrappers.NodeList; - var TreeScope = scope.TreeScope; - var assert = scope.assert; - var defineWrapGetter = scope.defineWrapGetter; - var enqueueMutation = scope.enqueueMutation; - var getTreeScope = scope.getTreeScope; - var isWrapper = scope.isWrapper; - var mixin = scope.mixin; - var registerTransientObservers = scope.registerTransientObservers; - var registerWrapper = scope.registerWrapper; - var setTreeScope = scope.setTreeScope; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var wrapIfNeeded = scope.wrapIfNeeded; - var wrappers = scope.wrappers; - function assertIsNodeWrapper(node) { - assert(node instanceof Node); - } - function createOneElementNodeList(node) { - var nodes = new NodeList(); - nodes[0] = node; - nodes.length = 1; - return nodes; - } - var surpressMutations = false; - function enqueueRemovalForInsertedNodes(node, parent, nodes) { - enqueueMutation(parent, "childList", { - removedNodes: nodes, - previousSibling: node.previousSibling, - nextSibling: node.nextSibling - }); - } - function enqueueRemovalForInsertedDocumentFragment(df, nodes) { - enqueueMutation(df, "childList", { - removedNodes: nodes - }); - } - function collectNodes(node, parentNode, previousNode, nextNode) { - if (node instanceof DocumentFragment) { - var nodes = collectNodesForDocumentFragment(node); - surpressMutations = true; - for (var i = nodes.length - 1; i >= 0; i--) { - node.removeChild(nodes[i]); - nodes[i].parentNode_ = parentNode; - } - surpressMutations = false; - for (var i = 0; i < nodes.length; i++) { - nodes[i].previousSibling_ = nodes[i - 1] || previousNode; - nodes[i].nextSibling_ = nodes[i + 1] || nextNode; - } - if (previousNode) previousNode.nextSibling_ = nodes[0]; - if (nextNode) nextNode.previousSibling_ = nodes[nodes.length - 1]; - return nodes; - } - var nodes = createOneElementNodeList(node); - var oldParent = node.parentNode; - if (oldParent) { - oldParent.removeChild(node); - } - node.parentNode_ = parentNode; - node.previousSibling_ = previousNode; - node.nextSibling_ = nextNode; - if (previousNode) previousNode.nextSibling_ = node; - if (nextNode) nextNode.previousSibling_ = node; - return nodes; - } - function collectNodesNative(node) { - if (node instanceof DocumentFragment) return collectNodesForDocumentFragment(node); - var nodes = createOneElementNodeList(node); - var oldParent = node.parentNode; - if (oldParent) enqueueRemovalForInsertedNodes(node, oldParent, nodes); - return nodes; - } - function collectNodesForDocumentFragment(node) { - var nodes = new NodeList(); - var i = 0; - for (var child = node.firstChild; child; child = child.nextSibling) { - nodes[i++] = child; - } - nodes.length = i; - enqueueRemovalForInsertedDocumentFragment(node, nodes); - return nodes; - } - function snapshotNodeList(nodeList) { - return nodeList; - } - function nodeWasAdded(node, treeScope) { - setTreeScope(node, treeScope); - node.nodeIsInserted_(); - } - function nodesWereAdded(nodes, parent) { - var treeScope = getTreeScope(parent); - for (var i = 0; i < nodes.length; i++) { - nodeWasAdded(nodes[i], treeScope); - } - } - function nodeWasRemoved(node) { - setTreeScope(node, new TreeScope(node, null)); - } - function nodesWereRemoved(nodes) { - for (var i = 0; i < nodes.length; i++) { - nodeWasRemoved(nodes[i]); - } - } - function ensureSameOwnerDocument(parent, child) { - var ownerDoc = parent.nodeType === Node.DOCUMENT_NODE ? parent : parent.ownerDocument; - if (ownerDoc !== child.ownerDocument) ownerDoc.adoptNode(child); - } - function adoptNodesIfNeeded(owner, nodes) { - if (!nodes.length) return; - var ownerDoc = owner.ownerDocument; - if (ownerDoc === nodes[0].ownerDocument) return; - for (var i = 0; i < nodes.length; i++) { - scope.adoptNodeNoRemove(nodes[i], ownerDoc); - } - } - function unwrapNodesForInsertion(owner, nodes) { - adoptNodesIfNeeded(owner, nodes); - var length = nodes.length; - if (length === 1) return unwrap(nodes[0]); - var df = unwrap(owner.ownerDocument.createDocumentFragment()); - for (var i = 0; i < length; i++) { - df.appendChild(unwrap(nodes[i])); - } - return df; - } - function clearChildNodes(wrapper) { - if (wrapper.firstChild_ !== undefined) { - var child = wrapper.firstChild_; - while (child) { - var tmp = child; - child = child.nextSibling_; - tmp.parentNode_ = tmp.previousSibling_ = tmp.nextSibling_ = undefined; - } - } - wrapper.firstChild_ = wrapper.lastChild_ = undefined; - } - function removeAllChildNodes(wrapper) { - if (wrapper.invalidateShadowRenderer()) { - var childWrapper = wrapper.firstChild; - while (childWrapper) { - assert(childWrapper.parentNode === wrapper); - var nextSibling = childWrapper.nextSibling; - var childNode = unwrap(childWrapper); - var parentNode = childNode.parentNode; - if (parentNode) originalRemoveChild.call(parentNode, childNode); - childWrapper.previousSibling_ = childWrapper.nextSibling_ = childWrapper.parentNode_ = null; - childWrapper = nextSibling; - } - wrapper.firstChild_ = wrapper.lastChild_ = null; - } else { - var node = unwrap(wrapper); - var child = node.firstChild; - var nextSibling; - while (child) { - nextSibling = child.nextSibling; - originalRemoveChild.call(node, child); - child = nextSibling; - } - } - } - function invalidateParent(node) { - var p = node.parentNode; - return p && p.invalidateShadowRenderer(); - } - function cleanupNodes(nodes) { - for (var i = 0, n; i < nodes.length; i++) { - n = nodes[i]; - n.parentNode.removeChild(n); - } - } - var originalImportNode = document.importNode; - var originalCloneNode = window.Node.prototype.cloneNode; - function cloneNode(node, deep, opt_doc) { - var clone; - if (opt_doc) clone = wrap(originalImportNode.call(opt_doc, unsafeUnwrap(node), false)); else clone = wrap(originalCloneNode.call(unsafeUnwrap(node), false)); - if (deep) { - for (var child = node.firstChild; child; child = child.nextSibling) { - clone.appendChild(cloneNode(child, true, opt_doc)); - } - if (node instanceof wrappers.HTMLTemplateElement) { - var cloneContent = clone.content; - for (var child = node.content.firstChild; child; child = child.nextSibling) { - cloneContent.appendChild(cloneNode(child, true, opt_doc)); - } - } - } - return clone; - } - function contains(self, child) { - if (!child || getTreeScope(self) !== getTreeScope(child)) return false; - for (var node = child; node; node = node.parentNode) { - if (node === self) return true; - } - return false; - } - var OriginalNode = window.Node; - function Node(original) { - assert(original instanceof OriginalNode); - EventTarget.call(this, original); - this.parentNode_ = undefined; - this.firstChild_ = undefined; - this.lastChild_ = undefined; - this.nextSibling_ = undefined; - this.previousSibling_ = undefined; - this.treeScope_ = undefined; - } - var OriginalDocumentFragment = window.DocumentFragment; - var originalAppendChild = OriginalNode.prototype.appendChild; - var originalCompareDocumentPosition = OriginalNode.prototype.compareDocumentPosition; - var originalIsEqualNode = OriginalNode.prototype.isEqualNode; - var originalInsertBefore = OriginalNode.prototype.insertBefore; - var originalRemoveChild = OriginalNode.prototype.removeChild; - var originalReplaceChild = OriginalNode.prototype.replaceChild; - var isIEOrEdge = /Trident|Edge/.test(navigator.userAgent); - var removeChildOriginalHelper = isIEOrEdge ? function(parent, child) { - try { - originalRemoveChild.call(parent, child); - } catch (ex) { - if (!(parent instanceof OriginalDocumentFragment)) throw ex; - } - } : function(parent, child) { - originalRemoveChild.call(parent, child); - }; - Node.prototype = Object.create(EventTarget.prototype); - mixin(Node.prototype, { - appendChild: function(childWrapper) { - return this.insertBefore(childWrapper, null); - }, - insertBefore: function(childWrapper, refWrapper) { - assertIsNodeWrapper(childWrapper); - var refNode; - if (refWrapper) { - if (isWrapper(refWrapper)) { - refNode = unwrap(refWrapper); - } else { - refNode = refWrapper; - refWrapper = wrap(refNode); - } - } else { - refWrapper = null; - refNode = null; - } - refWrapper && assert(refWrapper.parentNode === this); - var nodes; - var previousNode = refWrapper ? refWrapper.previousSibling : this.lastChild; - var useNative = !this.invalidateShadowRenderer() && !invalidateParent(childWrapper); - if (useNative) nodes = collectNodesNative(childWrapper); else nodes = collectNodes(childWrapper, this, previousNode, refWrapper); - if (useNative) { - ensureSameOwnerDocument(this, childWrapper); - clearChildNodes(this); - originalInsertBefore.call(unsafeUnwrap(this), unwrap(childWrapper), refNode); - } else { - if (!previousNode) this.firstChild_ = nodes[0]; - if (!refWrapper) { - this.lastChild_ = nodes[nodes.length - 1]; - if (this.firstChild_ === undefined) this.firstChild_ = this.firstChild; - } - var parentNode = refNode ? refNode.parentNode : unsafeUnwrap(this); - if (parentNode) { - originalInsertBefore.call(parentNode, unwrapNodesForInsertion(this, nodes), refNode); - } else { - adoptNodesIfNeeded(this, nodes); - } - } - enqueueMutation(this, "childList", { - addedNodes: nodes, - nextSibling: refWrapper, - previousSibling: previousNode - }); - nodesWereAdded(nodes, this); - return childWrapper; - }, - removeChild: function(childWrapper) { - assertIsNodeWrapper(childWrapper); - if (childWrapper.parentNode !== this) { - var found = false; - var childNodes = this.childNodes; - for (var ieChild = this.firstChild; ieChild; ieChild = ieChild.nextSibling) { - if (ieChild === childWrapper) { - found = true; - break; - } - } - if (!found) { - throw new Error("NotFoundError"); - } - } - var childNode = unwrap(childWrapper); - var childWrapperNextSibling = childWrapper.nextSibling; - var childWrapperPreviousSibling = childWrapper.previousSibling; - if (this.invalidateShadowRenderer()) { - var thisFirstChild = this.firstChild; - var thisLastChild = this.lastChild; - var parentNode = childNode.parentNode; - if (parentNode) removeChildOriginalHelper(parentNode, childNode); - if (thisFirstChild === childWrapper) this.firstChild_ = childWrapperNextSibling; - if (thisLastChild === childWrapper) this.lastChild_ = childWrapperPreviousSibling; - if (childWrapperPreviousSibling) childWrapperPreviousSibling.nextSibling_ = childWrapperNextSibling; - if (childWrapperNextSibling) { - childWrapperNextSibling.previousSibling_ = childWrapperPreviousSibling; - } - childWrapper.previousSibling_ = childWrapper.nextSibling_ = childWrapper.parentNode_ = undefined; - } else { - clearChildNodes(this); - removeChildOriginalHelper(unsafeUnwrap(this), childNode); - } - if (!surpressMutations) { - enqueueMutation(this, "childList", { - removedNodes: createOneElementNodeList(childWrapper), - nextSibling: childWrapperNextSibling, - previousSibling: childWrapperPreviousSibling - }); - } - registerTransientObservers(this, childWrapper); - return childWrapper; - }, - replaceChild: function(newChildWrapper, oldChildWrapper) { - assertIsNodeWrapper(newChildWrapper); - var oldChildNode; - if (isWrapper(oldChildWrapper)) { - oldChildNode = unwrap(oldChildWrapper); - } else { - oldChildNode = oldChildWrapper; - oldChildWrapper = wrap(oldChildNode); - } - if (oldChildWrapper.parentNode !== this) { - throw new Error("NotFoundError"); - } - var nextNode = oldChildWrapper.nextSibling; - var previousNode = oldChildWrapper.previousSibling; - var nodes; - var useNative = !this.invalidateShadowRenderer() && !invalidateParent(newChildWrapper); - if (useNative) { - nodes = collectNodesNative(newChildWrapper); - } else { - if (nextNode === newChildWrapper) nextNode = newChildWrapper.nextSibling; - nodes = collectNodes(newChildWrapper, this, previousNode, nextNode); - } - if (!useNative) { - if (this.firstChild === oldChildWrapper) this.firstChild_ = nodes[0]; - if (this.lastChild === oldChildWrapper) this.lastChild_ = nodes[nodes.length - 1]; - oldChildWrapper.previousSibling_ = oldChildWrapper.nextSibling_ = oldChildWrapper.parentNode_ = undefined; - if (oldChildNode.parentNode) { - originalReplaceChild.call(oldChildNode.parentNode, unwrapNodesForInsertion(this, nodes), oldChildNode); - } - } else { - ensureSameOwnerDocument(this, newChildWrapper); - clearChildNodes(this); - originalReplaceChild.call(unsafeUnwrap(this), unwrap(newChildWrapper), oldChildNode); - } - enqueueMutation(this, "childList", { - addedNodes: nodes, - removedNodes: createOneElementNodeList(oldChildWrapper), - nextSibling: nextNode, - previousSibling: previousNode - }); - nodeWasRemoved(oldChildWrapper); - nodesWereAdded(nodes, this); - return oldChildWrapper; - }, - nodeIsInserted_: function() { - for (var child = this.firstChild; child; child = child.nextSibling) { - child.nodeIsInserted_(); - } - }, - hasChildNodes: function() { - return this.firstChild !== null; - }, - get parentNode() { - return this.parentNode_ !== undefined ? this.parentNode_ : wrap(unsafeUnwrap(this).parentNode); - }, - get firstChild() { - return this.firstChild_ !== undefined ? this.firstChild_ : wrap(unsafeUnwrap(this).firstChild); - }, - get lastChild() { - return this.lastChild_ !== undefined ? this.lastChild_ : wrap(unsafeUnwrap(this).lastChild); - }, - get nextSibling() { - return this.nextSibling_ !== undefined ? this.nextSibling_ : wrap(unsafeUnwrap(this).nextSibling); - }, - get previousSibling() { - return this.previousSibling_ !== undefined ? this.previousSibling_ : wrap(unsafeUnwrap(this).previousSibling); - }, - get parentElement() { - var p = this.parentNode; - while (p && p.nodeType !== Node.ELEMENT_NODE) { - p = p.parentNode; - } - return p; - }, - get textContent() { - var s = ""; - for (var child = this.firstChild; child; child = child.nextSibling) { - if (child.nodeType != Node.COMMENT_NODE) { - s += child.textContent; - } - } - return s; - }, - set textContent(textContent) { - if (textContent == null) textContent = ""; - var removedNodes = snapshotNodeList(this.childNodes); - if (this.invalidateShadowRenderer()) { - removeAllChildNodes(this); - if (textContent !== "") { - var textNode = unsafeUnwrap(this).ownerDocument.createTextNode(textContent); - this.appendChild(textNode); - } - } else { - clearChildNodes(this); - unsafeUnwrap(this).textContent = textContent; - } - var addedNodes = snapshotNodeList(this.childNodes); - enqueueMutation(this, "childList", { - addedNodes: addedNodes, - removedNodes: removedNodes - }); - nodesWereRemoved(removedNodes); - nodesWereAdded(addedNodes, this); - }, - get childNodes() { - var wrapperList = new NodeList(); - var i = 0; - for (var child = this.firstChild; child; child = child.nextSibling) { - wrapperList[i++] = child; - } - wrapperList.length = i; - return wrapperList; - }, - cloneNode: function(deep) { - return cloneNode(this, deep); - }, - contains: function(child) { - return contains(this, wrapIfNeeded(child)); - }, - compareDocumentPosition: function(otherNode) { - return originalCompareDocumentPosition.call(unsafeUnwrap(this), unwrapIfNeeded(otherNode)); - }, - isEqualNode: function(otherNode) { - return originalIsEqualNode.call(unsafeUnwrap(this), unwrapIfNeeded(otherNode)); - }, - normalize: function() { - var nodes = snapshotNodeList(this.childNodes); - var remNodes = []; - var s = ""; - var modNode; - for (var i = 0, n; i < nodes.length; i++) { - n = nodes[i]; - if (n.nodeType === Node.TEXT_NODE) { - if (!modNode && !n.data.length) this.removeChild(n); else if (!modNode) modNode = n; else { - s += n.data; - remNodes.push(n); - } - } else { - if (modNode && remNodes.length) { - modNode.data += s; - cleanupNodes(remNodes); - } - remNodes = []; - s = ""; - modNode = null; - if (n.childNodes.length) n.normalize(); - } - } - if (modNode && remNodes.length) { - modNode.data += s; - cleanupNodes(remNodes); - } - } - }); - defineWrapGetter(Node, "ownerDocument"); - registerWrapper(OriginalNode, Node, document.createDocumentFragment()); - delete Node.prototype.querySelector; - delete Node.prototype.querySelectorAll; - Node.prototype = mixin(Object.create(EventTarget.prototype), Node.prototype); - scope.cloneNode = cloneNode; - scope.nodeWasAdded = nodeWasAdded; - scope.nodeWasRemoved = nodeWasRemoved; - scope.nodesWereAdded = nodesWereAdded; - scope.nodesWereRemoved = nodesWereRemoved; - scope.originalInsertBefore = originalInsertBefore; - scope.originalRemoveChild = originalRemoveChild; - scope.snapshotNodeList = snapshotNodeList; - scope.wrappers.Node = Node; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLCollection = scope.wrappers.HTMLCollection; - var NodeList = scope.wrappers.NodeList; - var getTreeScope = scope.getTreeScope; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrap = scope.wrap; - var originalDocumentQuerySelector = document.querySelector; - var originalElementQuerySelector = document.documentElement.querySelector; - var originalDocumentQuerySelectorAll = document.querySelectorAll; - var originalElementQuerySelectorAll = document.documentElement.querySelectorAll; - var originalDocumentGetElementsByTagName = document.getElementsByTagName; - var originalElementGetElementsByTagName = document.documentElement.getElementsByTagName; - var originalDocumentGetElementsByTagNameNS = document.getElementsByTagNameNS; - var originalElementGetElementsByTagNameNS = document.documentElement.getElementsByTagNameNS; - var OriginalElement = window.Element; - var OriginalDocument = window.HTMLDocument || window.Document; - function filterNodeList(list, index, result, deep) { - var wrappedItem = null; - var root = null; - for (var i = 0, length = list.length; i < length; i++) { - wrappedItem = wrap(list[i]); - if (!deep && (root = getTreeScope(wrappedItem).root)) { - if (root instanceof scope.wrappers.ShadowRoot) { - continue; - } - } - result[index++] = wrappedItem; - } - return index; - } - function shimSelector(selector) { - return String(selector).replace(/\/deep\/|::shadow|>>>/g, " "); - } - function shimMatchesSelector(selector) { - return String(selector).replace(/:host\(([^\s]+)\)/g, "$1").replace(/([^\s]):host/g, "$1").replace(":host", "*").replace(/\^|\/shadow\/|\/shadow-deep\/|::shadow|\/deep\/|::content|>>>/g, " "); - } - function findOne(node, selector) { - var m, el = node.firstElementChild; - while (el) { - if (el.matches(selector)) return el; - m = findOne(el, selector); - if (m) return m; - el = el.nextElementSibling; - } - return null; - } - function matchesSelector(el, selector) { - return el.matches(selector); - } - var XHTML_NS = "http://www.w3.org/1999/xhtml"; - function matchesTagName(el, localName, localNameLowerCase) { - var ln = el.localName; - return ln === localName || ln === localNameLowerCase && el.namespaceURI === XHTML_NS; - } - function matchesEveryThing() { - return true; - } - function matchesLocalNameOnly(el, ns, localName) { - return el.localName === localName; - } - function matchesNameSpace(el, ns) { - return el.namespaceURI === ns; - } - function matchesLocalNameNS(el, ns, localName) { - return el.namespaceURI === ns && el.localName === localName; - } - function findElements(node, index, result, p, arg0, arg1) { - var el = node.firstElementChild; - while (el) { - if (p(el, arg0, arg1)) result[index++] = el; - index = findElements(el, index, result, p, arg0, arg1); - el = el.nextElementSibling; - } - return index; - } - function querySelectorAllFiltered(p, index, result, selector, deep) { - var target = unsafeUnwrap(this); - var list; - var root = getTreeScope(this).root; - if (root instanceof scope.wrappers.ShadowRoot) { - return findElements(this, index, result, p, selector, null); - } else if (target instanceof OriginalElement) { - list = originalElementQuerySelectorAll.call(target, selector); - } else if (target instanceof OriginalDocument) { - list = originalDocumentQuerySelectorAll.call(target, selector); - } else { - return findElements(this, index, result, p, selector, null); - } - return filterNodeList(list, index, result, deep); - } - var SelectorsInterface = { - querySelector: function(selector) { - var shimmed = shimSelector(selector); - var deep = shimmed !== selector; - selector = shimmed; - var target = unsafeUnwrap(this); - var wrappedItem; - var root = getTreeScope(this).root; - if (root instanceof scope.wrappers.ShadowRoot) { - return findOne(this, selector); - } else if (target instanceof OriginalElement) { - wrappedItem = wrap(originalElementQuerySelector.call(target, selector)); - } else if (target instanceof OriginalDocument) { - wrappedItem = wrap(originalDocumentQuerySelector.call(target, selector)); - } else { - return findOne(this, selector); - } - if (!wrappedItem) { - return wrappedItem; - } else if (!deep && (root = getTreeScope(wrappedItem).root)) { - if (root instanceof scope.wrappers.ShadowRoot) { - return findOne(this, selector); - } - } - return wrappedItem; - }, - querySelectorAll: function(selector) { - var shimmed = shimSelector(selector); - var deep = shimmed !== selector; - selector = shimmed; - var result = new NodeList(); - result.length = querySelectorAllFiltered.call(this, matchesSelector, 0, result, selector, deep); - return result; - } - }; - var MatchesInterface = { - matches: function(selector) { - selector = shimMatchesSelector(selector); - return scope.originalMatches.call(unsafeUnwrap(this), selector); - } - }; - function getElementsByTagNameFiltered(p, index, result, localName, lowercase) { - var target = unsafeUnwrap(this); - var list; - var root = getTreeScope(this).root; - if (root instanceof scope.wrappers.ShadowRoot) { - return findElements(this, index, result, p, localName, lowercase); - } else if (target instanceof OriginalElement) { - list = originalElementGetElementsByTagName.call(target, localName, lowercase); - } else if (target instanceof OriginalDocument) { - list = originalDocumentGetElementsByTagName.call(target, localName, lowercase); - } else { - return findElements(this, index, result, p, localName, lowercase); - } - return filterNodeList(list, index, result, false); - } - function getElementsByTagNameNSFiltered(p, index, result, ns, localName) { - var target = unsafeUnwrap(this); - var list; - var root = getTreeScope(this).root; - if (root instanceof scope.wrappers.ShadowRoot) { - return findElements(this, index, result, p, ns, localName); - } else if (target instanceof OriginalElement) { - list = originalElementGetElementsByTagNameNS.call(target, ns, localName); - } else if (target instanceof OriginalDocument) { - list = originalDocumentGetElementsByTagNameNS.call(target, ns, localName); - } else { - return findElements(this, index, result, p, ns, localName); - } - return filterNodeList(list, index, result, false); - } - var GetElementsByInterface = { - getElementsByTagName: function(localName) { - var result = new HTMLCollection(); - var match = localName === "*" ? matchesEveryThing : matchesTagName; - result.length = getElementsByTagNameFiltered.call(this, match, 0, result, localName, localName.toLowerCase()); - return result; - }, - getElementsByClassName: function(className) { - return this.querySelectorAll("." + className); - }, - getElementsByTagNameNS: function(ns, localName) { - var result = new HTMLCollection(); - var match = null; - if (ns === "*") { - match = localName === "*" ? matchesEveryThing : matchesLocalNameOnly; - } else { - match = localName === "*" ? matchesNameSpace : matchesLocalNameNS; - } - result.length = getElementsByTagNameNSFiltered.call(this, match, 0, result, ns || null, localName); - return result; - } - }; - scope.GetElementsByInterface = GetElementsByInterface; - scope.SelectorsInterface = SelectorsInterface; - scope.MatchesInterface = MatchesInterface; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var NodeList = scope.wrappers.NodeList; - function forwardElement(node) { - while (node && node.nodeType !== Node.ELEMENT_NODE) { - node = node.nextSibling; - } - return node; - } - function backwardsElement(node) { - while (node && node.nodeType !== Node.ELEMENT_NODE) { - node = node.previousSibling; - } - return node; - } - var ParentNodeInterface = { - get firstElementChild() { - return forwardElement(this.firstChild); - }, - get lastElementChild() { - return backwardsElement(this.lastChild); - }, - get childElementCount() { - var count = 0; - for (var child = this.firstElementChild; child; child = child.nextElementSibling) { - count++; - } - return count; - }, - get children() { - var wrapperList = new NodeList(); - var i = 0; - for (var child = this.firstElementChild; child; child = child.nextElementSibling) { - wrapperList[i++] = child; - } - wrapperList.length = i; - return wrapperList; - }, - remove: function() { - var p = this.parentNode; - if (p) p.removeChild(this); - } - }; - var ChildNodeInterface = { - get nextElementSibling() { - return forwardElement(this.nextSibling); - }, - get previousElementSibling() { - return backwardsElement(this.previousSibling); - } - }; - var NonElementParentNodeInterface = { - getElementById: function(id) { - if (/[ \t\n\r\f]/.test(id)) return null; - return this.querySelector('[id="' + id + '"]'); - } - }; - scope.ChildNodeInterface = ChildNodeInterface; - scope.NonElementParentNodeInterface = NonElementParentNodeInterface; - scope.ParentNodeInterface = ParentNodeInterface; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var ChildNodeInterface = scope.ChildNodeInterface; - var Node = scope.wrappers.Node; - var enqueueMutation = scope.enqueueMutation; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var OriginalCharacterData = window.CharacterData; - function CharacterData(node) { - Node.call(this, node); - } - CharacterData.prototype = Object.create(Node.prototype); - mixin(CharacterData.prototype, { - get nodeValue() { - return this.data; - }, - set nodeValue(data) { - this.data = data; - }, - get textContent() { - return this.data; - }, - set textContent(value) { - this.data = value; - }, - get data() { - return unsafeUnwrap(this).data; - }, - set data(value) { - var oldValue = unsafeUnwrap(this).data; - enqueueMutation(this, "characterData", { - oldValue: oldValue - }); - unsafeUnwrap(this).data = value; - } - }); - mixin(CharacterData.prototype, ChildNodeInterface); - registerWrapper(OriginalCharacterData, CharacterData, document.createTextNode("")); - scope.wrappers.CharacterData = CharacterData; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var CharacterData = scope.wrappers.CharacterData; - var enqueueMutation = scope.enqueueMutation; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - function toUInt32(x) { - return x >>> 0; - } - var OriginalText = window.Text; - function Text(node) { - CharacterData.call(this, node); - } - Text.prototype = Object.create(CharacterData.prototype); - mixin(Text.prototype, { - splitText: function(offset) { - offset = toUInt32(offset); - var s = this.data; - if (offset > s.length) throw new Error("IndexSizeError"); - var head = s.slice(0, offset); - var tail = s.slice(offset); - this.data = head; - var newTextNode = this.ownerDocument.createTextNode(tail); - if (this.parentNode) this.parentNode.insertBefore(newTextNode, this.nextSibling); - return newTextNode; - } - }); - registerWrapper(OriginalText, Text, document.createTextNode("")); - scope.wrappers.Text = Text; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - if (!window.DOMTokenList) { - console.warn("Missing DOMTokenList prototype, please include a " + "compatible classList polyfill such as http://goo.gl/uTcepH."); - return; - } - var unsafeUnwrap = scope.unsafeUnwrap; - var enqueueMutation = scope.enqueueMutation; - function getClass(el) { - return unsafeUnwrap(el).getAttribute("class"); - } - function enqueueClassAttributeChange(el, oldValue) { - enqueueMutation(el, "attributes", { - name: "class", - namespace: null, - oldValue: oldValue - }); - } - function invalidateClass(el) { - scope.invalidateRendererBasedOnAttribute(el, "class"); - } - function changeClass(tokenList, method, args) { - var ownerElement = tokenList.ownerElement_; - if (ownerElement == null) { - return method.apply(tokenList, args); - } - var oldValue = getClass(ownerElement); - var retv = method.apply(tokenList, args); - if (getClass(ownerElement) !== oldValue) { - enqueueClassAttributeChange(ownerElement, oldValue); - invalidateClass(ownerElement); - } - return retv; - } - var oldAdd = DOMTokenList.prototype.add; - DOMTokenList.prototype.add = function() { - changeClass(this, oldAdd, arguments); - }; - var oldRemove = DOMTokenList.prototype.remove; - DOMTokenList.prototype.remove = function() { - changeClass(this, oldRemove, arguments); - }; - var oldToggle = DOMTokenList.prototype.toggle; - DOMTokenList.prototype.toggle = function() { - return changeClass(this, oldToggle, arguments); - }; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var ChildNodeInterface = scope.ChildNodeInterface; - var GetElementsByInterface = scope.GetElementsByInterface; - var Node = scope.wrappers.Node; - var ParentNodeInterface = scope.ParentNodeInterface; - var SelectorsInterface = scope.SelectorsInterface; - var MatchesInterface = scope.MatchesInterface; - var addWrapNodeListMethod = scope.addWrapNodeListMethod; - var enqueueMutation = scope.enqueueMutation; - var mixin = scope.mixin; - var oneOf = scope.oneOf; - var registerWrapper = scope.registerWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrappers = scope.wrappers; - var OriginalElement = window.Element; - var matchesNames = [ "matches", "mozMatchesSelector", "msMatchesSelector", "webkitMatchesSelector" ].filter(function(name) { - return OriginalElement.prototype[name]; - }); - var matchesName = matchesNames[0]; - var originalMatches = OriginalElement.prototype[matchesName]; - function invalidateRendererBasedOnAttribute(element, name) { - var p = element.parentNode; - if (!p || !p.shadowRoot) return; - var renderer = scope.getRendererForHost(p); - if (renderer.dependsOnAttribute(name)) renderer.invalidate(); - } - function enqueAttributeChange(element, name, oldValue) { - enqueueMutation(element, "attributes", { - name: name, - namespace: null, - oldValue: oldValue - }); - } - var classListTable = new WeakMap(); - function Element(node) { - Node.call(this, node); - } - Element.prototype = Object.create(Node.prototype); - mixin(Element.prototype, { - createShadowRoot: function() { - var newShadowRoot = new wrappers.ShadowRoot(this); - unsafeUnwrap(this).polymerShadowRoot_ = newShadowRoot; - var renderer = scope.getRendererForHost(this); - renderer.invalidate(); - return newShadowRoot; - }, - get shadowRoot() { - return unsafeUnwrap(this).polymerShadowRoot_ || null; - }, - setAttribute: function(name, value) { - var oldValue = unsafeUnwrap(this).getAttribute(name); - unsafeUnwrap(this).setAttribute(name, value); - enqueAttributeChange(this, name, oldValue); - invalidateRendererBasedOnAttribute(this, name); - }, - removeAttribute: function(name) { - var oldValue = unsafeUnwrap(this).getAttribute(name); - unsafeUnwrap(this).removeAttribute(name); - enqueAttributeChange(this, name, oldValue); - invalidateRendererBasedOnAttribute(this, name); - }, - get classList() { - var list = classListTable.get(this); - if (!list) { - list = unsafeUnwrap(this).classList; - if (!list) return; - list.ownerElement_ = this; - classListTable.set(this, list); - } - return list; - }, - get className() { - return unsafeUnwrap(this).className; - }, - set className(v) { - this.setAttribute("class", v); - }, - get id() { - return unsafeUnwrap(this).id; - }, - set id(v) { - this.setAttribute("id", v); - } - }); - matchesNames.forEach(function(name) { - if (name !== "matches") { - Element.prototype[name] = function(selector) { - return this.matches(selector); - }; - } - }); - if (OriginalElement.prototype.webkitCreateShadowRoot) { - Element.prototype.webkitCreateShadowRoot = Element.prototype.createShadowRoot; - } - mixin(Element.prototype, ChildNodeInterface); - mixin(Element.prototype, GetElementsByInterface); - mixin(Element.prototype, ParentNodeInterface); - mixin(Element.prototype, SelectorsInterface); - mixin(Element.prototype, MatchesInterface); - registerWrapper(OriginalElement, Element, document.createElementNS(null, "x")); - scope.invalidateRendererBasedOnAttribute = invalidateRendererBasedOnAttribute; - scope.matchesNames = matchesNames; - scope.originalMatches = originalMatches; - scope.wrappers.Element = Element; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var Element = scope.wrappers.Element; - var defineGetter = scope.defineGetter; - var enqueueMutation = scope.enqueueMutation; - var mixin = scope.mixin; - var nodesWereAdded = scope.nodesWereAdded; - var nodesWereRemoved = scope.nodesWereRemoved; - var registerWrapper = scope.registerWrapper; - var snapshotNodeList = scope.snapshotNodeList; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var wrappers = scope.wrappers; - var escapeAttrRegExp = /[&\u00A0"]/g; - var escapeDataRegExp = /[&\u00A0<>]/g; - function escapeReplace(c) { - switch (c) { - case "&": - return "&"; - - case "<": - return "<"; - - case ">": - return ">"; - - case '"': - return """; - - case " ": - return " "; - } - } - function escapeAttr(s) { - return s.replace(escapeAttrRegExp, escapeReplace); - } - function escapeData(s) { - return s.replace(escapeDataRegExp, escapeReplace); - } - function makeSet(arr) { - var set = {}; - for (var i = 0; i < arr.length; i++) { - set[arr[i]] = true; - } - return set; - } - var voidElements = makeSet([ "area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr" ]); - var plaintextParents = makeSet([ "style", "script", "xmp", "iframe", "noembed", "noframes", "plaintext", "noscript" ]); - var XHTML_NS = "http://www.w3.org/1999/xhtml"; - function needsSelfClosingSlash(node) { - if (node.namespaceURI !== XHTML_NS) return true; - var doctype = node.ownerDocument.doctype; - return doctype && doctype.publicId && doctype.systemId; - } - function getOuterHTML(node, parentNode) { - switch (node.nodeType) { - case Node.ELEMENT_NODE: - var tagName = node.tagName.toLowerCase(); - var s = "<" + tagName; - var attrs = node.attributes; - for (var i = 0, attr; attr = attrs[i]; i++) { - s += " " + attr.name + '="' + escapeAttr(attr.value) + '"'; - } - if (voidElements[tagName]) { - if (needsSelfClosingSlash(node)) s += "/"; - return s + ">"; - } - return s + ">" + getInnerHTML(node) + ""; - - case Node.TEXT_NODE: - var data = node.data; - if (parentNode && plaintextParents[parentNode.localName]) return data; - return escapeData(data); - - case Node.COMMENT_NODE: - return ""; - - default: - console.error(node); - throw new Error("not implemented"); - } - } - function getInnerHTML(node) { - if (node instanceof wrappers.HTMLTemplateElement) node = node.content; - var s = ""; - for (var child = node.firstChild; child; child = child.nextSibling) { - s += getOuterHTML(child, node); - } - return s; - } - function setInnerHTML(node, value, opt_tagName) { - var tagName = opt_tagName || "div"; - node.textContent = ""; - var tempElement = unwrap(node.ownerDocument.createElement(tagName)); - tempElement.innerHTML = value; - var firstChild; - while (firstChild = tempElement.firstChild) { - node.appendChild(wrap(firstChild)); - } - } - var oldIe = /MSIE/.test(navigator.userAgent); - var OriginalHTMLElement = window.HTMLElement; - var OriginalHTMLTemplateElement = window.HTMLTemplateElement; - function HTMLElement(node) { - Element.call(this, node); - } - HTMLElement.prototype = Object.create(Element.prototype); - mixin(HTMLElement.prototype, { - get innerHTML() { - return getInnerHTML(this); - }, - set innerHTML(value) { - if (oldIe && plaintextParents[this.localName]) { - this.textContent = value; - return; - } - var removedNodes = snapshotNodeList(this.childNodes); - if (this.invalidateShadowRenderer()) { - if (this instanceof wrappers.HTMLTemplateElement) setInnerHTML(this.content, value); else setInnerHTML(this, value, this.tagName); - } else if (!OriginalHTMLTemplateElement && this instanceof wrappers.HTMLTemplateElement) { - setInnerHTML(this.content, value); - } else { - unsafeUnwrap(this).innerHTML = value; - } - var addedNodes = snapshotNodeList(this.childNodes); - enqueueMutation(this, "childList", { - addedNodes: addedNodes, - removedNodes: removedNodes - }); - nodesWereRemoved(removedNodes); - nodesWereAdded(addedNodes, this); - }, - get outerHTML() { - return getOuterHTML(this, this.parentNode); - }, - set outerHTML(value) { - var p = this.parentNode; - if (p) { - p.invalidateShadowRenderer(); - var df = frag(p, value); - p.replaceChild(df, this); - } - }, - insertAdjacentHTML: function(position, text) { - var contextElement, refNode; - switch (String(position).toLowerCase()) { - case "beforebegin": - contextElement = this.parentNode; - refNode = this; - break; - - case "afterend": - contextElement = this.parentNode; - refNode = this.nextSibling; - break; - - case "afterbegin": - contextElement = this; - refNode = this.firstChild; - break; - - case "beforeend": - contextElement = this; - refNode = null; - break; - - default: - return; - } - var df = frag(contextElement, text); - contextElement.insertBefore(df, refNode); - }, - get hidden() { - return this.hasAttribute("hidden"); - }, - set hidden(v) { - if (v) { - this.setAttribute("hidden", ""); - } else { - this.removeAttribute("hidden"); - } - } - }); - function frag(contextElement, html) { - var p = unwrap(contextElement.cloneNode(false)); - p.innerHTML = html; - var df = unwrap(document.createDocumentFragment()); - var c; - while (c = p.firstChild) { - df.appendChild(c); - } - return wrap(df); - } - function getter(name) { - return function() { - scope.renderAllPending(); - return unsafeUnwrap(this)[name]; - }; - } - function getterRequiresRendering(name) { - defineGetter(HTMLElement, name, getter(name)); - } - [ "clientHeight", "clientLeft", "clientTop", "clientWidth", "offsetHeight", "offsetLeft", "offsetTop", "offsetWidth", "scrollHeight", "scrollWidth" ].forEach(getterRequiresRendering); - function getterAndSetterRequiresRendering(name) { - Object.defineProperty(HTMLElement.prototype, name, { - get: getter(name), - set: function(v) { - scope.renderAllPending(); - unsafeUnwrap(this)[name] = v; - }, - configurable: true, - enumerable: true - }); - } - [ "scrollLeft", "scrollTop" ].forEach(getterAndSetterRequiresRendering); - function methodRequiresRendering(name) { - Object.defineProperty(HTMLElement.prototype, name, { - value: function() { - scope.renderAllPending(); - return unsafeUnwrap(this)[name].apply(unsafeUnwrap(this), arguments); - }, - configurable: true, - enumerable: true - }); - } - [ "focus", "getBoundingClientRect", "getClientRects", "scrollIntoView" ].forEach(methodRequiresRendering); - registerWrapper(OriginalHTMLElement, HTMLElement, document.createElement("b")); - scope.wrappers.HTMLElement = HTMLElement; - scope.getInnerHTML = getInnerHTML; - scope.setInnerHTML = setInnerHTML; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrap = scope.wrap; - var OriginalHTMLCanvasElement = window.HTMLCanvasElement; - function HTMLCanvasElement(node) { - HTMLElement.call(this, node); - } - HTMLCanvasElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLCanvasElement.prototype, { - getContext: function() { - var context = unsafeUnwrap(this).getContext.apply(unsafeUnwrap(this), arguments); - return context && wrap(context); - } - }); - registerWrapper(OriginalHTMLCanvasElement, HTMLCanvasElement, document.createElement("canvas")); - scope.wrappers.HTMLCanvasElement = HTMLCanvasElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var OriginalHTMLContentElement = window.HTMLContentElement; - function HTMLContentElement(node) { - HTMLElement.call(this, node); - } - HTMLContentElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLContentElement.prototype, { - constructor: HTMLContentElement, - get select() { - return this.getAttribute("select"); - }, - set select(value) { - this.setAttribute("select", value); - }, - setAttribute: function(n, v) { - HTMLElement.prototype.setAttribute.call(this, n, v); - if (String(n).toLowerCase() === "select") this.invalidateShadowRenderer(true); - } - }); - if (OriginalHTMLContentElement) registerWrapper(OriginalHTMLContentElement, HTMLContentElement); - scope.wrappers.HTMLContentElement = HTMLContentElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var wrapHTMLCollection = scope.wrapHTMLCollection; - var unwrap = scope.unwrap; - var OriginalHTMLFormElement = window.HTMLFormElement; - function HTMLFormElement(node) { - HTMLElement.call(this, node); - } - HTMLFormElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLFormElement.prototype, { - get elements() { - return wrapHTMLCollection(unwrap(this).elements); - } - }); - registerWrapper(OriginalHTMLFormElement, HTMLFormElement, document.createElement("form")); - scope.wrappers.HTMLFormElement = HTMLFormElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var registerWrapper = scope.registerWrapper; - var unwrap = scope.unwrap; - var rewrap = scope.rewrap; - var OriginalHTMLImageElement = window.HTMLImageElement; - function HTMLImageElement(node) { - HTMLElement.call(this, node); - } - HTMLImageElement.prototype = Object.create(HTMLElement.prototype); - registerWrapper(OriginalHTMLImageElement, HTMLImageElement, document.createElement("img")); - function Image(width, height) { - if (!(this instanceof Image)) { - throw new TypeError("DOM object constructor cannot be called as a function."); - } - var node = unwrap(document.createElement("img")); - HTMLElement.call(this, node); - rewrap(node, this); - if (width !== undefined) node.width = width; - if (height !== undefined) node.height = height; - } - Image.prototype = HTMLImageElement.prototype; - scope.wrappers.HTMLImageElement = HTMLImageElement; - scope.wrappers.Image = Image; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var NodeList = scope.wrappers.NodeList; - var registerWrapper = scope.registerWrapper; - var OriginalHTMLShadowElement = window.HTMLShadowElement; - function HTMLShadowElement(node) { - HTMLElement.call(this, node); - } - HTMLShadowElement.prototype = Object.create(HTMLElement.prototype); - HTMLShadowElement.prototype.constructor = HTMLShadowElement; - if (OriginalHTMLShadowElement) registerWrapper(OriginalHTMLShadowElement, HTMLShadowElement); - scope.wrappers.HTMLShadowElement = HTMLShadowElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var contentTable = new WeakMap(); - var templateContentsOwnerTable = new WeakMap(); - function getTemplateContentsOwner(doc) { - if (!doc.defaultView) return doc; - var d = templateContentsOwnerTable.get(doc); - if (!d) { - d = doc.implementation.createHTMLDocument(""); - while (d.lastChild) { - d.removeChild(d.lastChild); - } - templateContentsOwnerTable.set(doc, d); - } - return d; - } - function extractContent(templateElement) { - var doc = getTemplateContentsOwner(templateElement.ownerDocument); - var df = unwrap(doc.createDocumentFragment()); - var child; - while (child = templateElement.firstChild) { - df.appendChild(child); - } - return df; - } - var OriginalHTMLTemplateElement = window.HTMLTemplateElement; - function HTMLTemplateElement(node) { - HTMLElement.call(this, node); - if (!OriginalHTMLTemplateElement) { - var content = extractContent(node); - contentTable.set(this, wrap(content)); - } - } - HTMLTemplateElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLTemplateElement.prototype, { - constructor: HTMLTemplateElement, - get content() { - if (OriginalHTMLTemplateElement) return wrap(unsafeUnwrap(this).content); - return contentTable.get(this); - } - }); - if (OriginalHTMLTemplateElement) registerWrapper(OriginalHTMLTemplateElement, HTMLTemplateElement); - scope.wrappers.HTMLTemplateElement = HTMLTemplateElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var registerWrapper = scope.registerWrapper; - var OriginalHTMLMediaElement = window.HTMLMediaElement; - if (!OriginalHTMLMediaElement) return; - function HTMLMediaElement(node) { - HTMLElement.call(this, node); - } - HTMLMediaElement.prototype = Object.create(HTMLElement.prototype); - registerWrapper(OriginalHTMLMediaElement, HTMLMediaElement, document.createElement("audio")); - scope.wrappers.HTMLMediaElement = HTMLMediaElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLMediaElement = scope.wrappers.HTMLMediaElement; - var registerWrapper = scope.registerWrapper; - var unwrap = scope.unwrap; - var rewrap = scope.rewrap; - var OriginalHTMLAudioElement = window.HTMLAudioElement; - if (!OriginalHTMLAudioElement) return; - function HTMLAudioElement(node) { - HTMLMediaElement.call(this, node); - } - HTMLAudioElement.prototype = Object.create(HTMLMediaElement.prototype); - registerWrapper(OriginalHTMLAudioElement, HTMLAudioElement, document.createElement("audio")); - function Audio(src) { - if (!(this instanceof Audio)) { - throw new TypeError("DOM object constructor cannot be called as a function."); - } - var node = unwrap(document.createElement("audio")); - HTMLMediaElement.call(this, node); - rewrap(node, this); - node.setAttribute("preload", "auto"); - if (src !== undefined) node.setAttribute("src", src); - } - Audio.prototype = HTMLAudioElement.prototype; - scope.wrappers.HTMLAudioElement = HTMLAudioElement; - scope.wrappers.Audio = Audio; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var rewrap = scope.rewrap; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var OriginalHTMLOptionElement = window.HTMLOptionElement; - function trimText(s) { - return s.replace(/\s+/g, " ").trim(); - } - function HTMLOptionElement(node) { - HTMLElement.call(this, node); - } - HTMLOptionElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLOptionElement.prototype, { - get text() { - return trimText(this.textContent); - }, - set text(value) { - this.textContent = trimText(String(value)); - }, - get form() { - return wrap(unwrap(this).form); - } - }); - registerWrapper(OriginalHTMLOptionElement, HTMLOptionElement, document.createElement("option")); - function Option(text, value, defaultSelected, selected) { - if (!(this instanceof Option)) { - throw new TypeError("DOM object constructor cannot be called as a function."); - } - var node = unwrap(document.createElement("option")); - HTMLElement.call(this, node); - rewrap(node, this); - if (text !== undefined) node.text = text; - if (value !== undefined) node.setAttribute("value", value); - if (defaultSelected === true) node.setAttribute("selected", ""); - node.selected = selected === true; - } - Option.prototype = HTMLOptionElement.prototype; - scope.wrappers.HTMLOptionElement = HTMLOptionElement; - scope.wrappers.Option = Option; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var OriginalHTMLSelectElement = window.HTMLSelectElement; - function HTMLSelectElement(node) { - HTMLElement.call(this, node); - } - HTMLSelectElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLSelectElement.prototype, { - add: function(element, before) { - if (typeof before === "object") before = unwrap(before); - unwrap(this).add(unwrap(element), before); - }, - remove: function(indexOrNode) { - if (indexOrNode === undefined) { - HTMLElement.prototype.remove.call(this); - return; - } - if (typeof indexOrNode === "object") indexOrNode = unwrap(indexOrNode); - unwrap(this).remove(indexOrNode); - }, - get form() { - return wrap(unwrap(this).form); - } - }); - registerWrapper(OriginalHTMLSelectElement, HTMLSelectElement, document.createElement("select")); - scope.wrappers.HTMLSelectElement = HTMLSelectElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var wrapHTMLCollection = scope.wrapHTMLCollection; - var OriginalHTMLTableElement = window.HTMLTableElement; - function HTMLTableElement(node) { - HTMLElement.call(this, node); - } - HTMLTableElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLTableElement.prototype, { - get caption() { - return wrap(unwrap(this).caption); - }, - createCaption: function() { - return wrap(unwrap(this).createCaption()); - }, - get tHead() { - return wrap(unwrap(this).tHead); - }, - createTHead: function() { - return wrap(unwrap(this).createTHead()); - }, - createTFoot: function() { - return wrap(unwrap(this).createTFoot()); - }, - get tFoot() { - return wrap(unwrap(this).tFoot); - }, - get tBodies() { - return wrapHTMLCollection(unwrap(this).tBodies); - }, - createTBody: function() { - return wrap(unwrap(this).createTBody()); - }, - get rows() { - return wrapHTMLCollection(unwrap(this).rows); - }, - insertRow: function(index) { - return wrap(unwrap(this).insertRow(index)); - } - }); - registerWrapper(OriginalHTMLTableElement, HTMLTableElement, document.createElement("table")); - scope.wrappers.HTMLTableElement = HTMLTableElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var wrapHTMLCollection = scope.wrapHTMLCollection; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var OriginalHTMLTableSectionElement = window.HTMLTableSectionElement; - function HTMLTableSectionElement(node) { - HTMLElement.call(this, node); - } - HTMLTableSectionElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLTableSectionElement.prototype, { - constructor: HTMLTableSectionElement, - get rows() { - return wrapHTMLCollection(unwrap(this).rows); - }, - insertRow: function(index) { - return wrap(unwrap(this).insertRow(index)); - } - }); - registerWrapper(OriginalHTMLTableSectionElement, HTMLTableSectionElement, document.createElement("thead")); - scope.wrappers.HTMLTableSectionElement = HTMLTableSectionElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var wrapHTMLCollection = scope.wrapHTMLCollection; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var OriginalHTMLTableRowElement = window.HTMLTableRowElement; - function HTMLTableRowElement(node) { - HTMLElement.call(this, node); - } - HTMLTableRowElement.prototype = Object.create(HTMLElement.prototype); - mixin(HTMLTableRowElement.prototype, { - get cells() { - return wrapHTMLCollection(unwrap(this).cells); - }, - insertCell: function(index) { - return wrap(unwrap(this).insertCell(index)); - } - }); - registerWrapper(OriginalHTMLTableRowElement, HTMLTableRowElement, document.createElement("tr")); - scope.wrappers.HTMLTableRowElement = HTMLTableRowElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLContentElement = scope.wrappers.HTMLContentElement; - var HTMLElement = scope.wrappers.HTMLElement; - var HTMLShadowElement = scope.wrappers.HTMLShadowElement; - var HTMLTemplateElement = scope.wrappers.HTMLTemplateElement; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var OriginalHTMLUnknownElement = window.HTMLUnknownElement; - function HTMLUnknownElement(node) { - switch (node.localName) { - case "content": - return new HTMLContentElement(node); - - case "shadow": - return new HTMLShadowElement(node); - - case "template": - return new HTMLTemplateElement(node); - } - HTMLElement.call(this, node); - } - HTMLUnknownElement.prototype = Object.create(HTMLElement.prototype); - registerWrapper(OriginalHTMLUnknownElement, HTMLUnknownElement); - scope.wrappers.HTMLUnknownElement = HTMLUnknownElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var Element = scope.wrappers.Element; - var HTMLElement = scope.wrappers.HTMLElement; - var registerWrapper = scope.registerWrapper; - var defineWrapGetter = scope.defineWrapGetter; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrap = scope.wrap; - var mixin = scope.mixin; - var SVG_NS = "http://www.w3.org/2000/svg"; - var OriginalSVGElement = window.SVGElement; - var svgTitleElement = document.createElementNS(SVG_NS, "title"); - if (!("classList" in svgTitleElement)) { - var descr = Object.getOwnPropertyDescriptor(Element.prototype, "classList"); - Object.defineProperty(HTMLElement.prototype, "classList", descr); - delete Element.prototype.classList; - } - function SVGElement(node) { - Element.call(this, node); - } - SVGElement.prototype = Object.create(Element.prototype); - mixin(SVGElement.prototype, { - get ownerSVGElement() { - return wrap(unsafeUnwrap(this).ownerSVGElement); - } - }); - registerWrapper(OriginalSVGElement, SVGElement, document.createElementNS(SVG_NS, "title")); - scope.wrappers.SVGElement = SVGElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var OriginalSVGUseElement = window.SVGUseElement; - var SVG_NS = "http://www.w3.org/2000/svg"; - var gWrapper = wrap(document.createElementNS(SVG_NS, "g")); - var useElement = document.createElementNS(SVG_NS, "use"); - var SVGGElement = gWrapper.constructor; - var parentInterfacePrototype = Object.getPrototypeOf(SVGGElement.prototype); - var parentInterface = parentInterfacePrototype.constructor; - function SVGUseElement(impl) { - parentInterface.call(this, impl); - } - SVGUseElement.prototype = Object.create(parentInterfacePrototype); - if ("instanceRoot" in useElement) { - mixin(SVGUseElement.prototype, { - get instanceRoot() { - return wrap(unwrap(this).instanceRoot); - }, - get animatedInstanceRoot() { - return wrap(unwrap(this).animatedInstanceRoot); - } - }); - } - registerWrapper(OriginalSVGUseElement, SVGUseElement, useElement); - scope.wrappers.SVGUseElement = SVGUseElement; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var EventTarget = scope.wrappers.EventTarget; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var wrap = scope.wrap; - var OriginalSVGElementInstance = window.SVGElementInstance; - if (!OriginalSVGElementInstance) return; - function SVGElementInstance(impl) { - EventTarget.call(this, impl); - } - SVGElementInstance.prototype = Object.create(EventTarget.prototype); - mixin(SVGElementInstance.prototype, { - get correspondingElement() { - return wrap(unsafeUnwrap(this).correspondingElement); - }, - get correspondingUseElement() { - return wrap(unsafeUnwrap(this).correspondingUseElement); - }, - get parentNode() { - return wrap(unsafeUnwrap(this).parentNode); - }, - get childNodes() { - throw new Error("Not implemented"); - }, - get firstChild() { - return wrap(unsafeUnwrap(this).firstChild); - }, - get lastChild() { - return wrap(unsafeUnwrap(this).lastChild); - }, - get previousSibling() { - return wrap(unsafeUnwrap(this).previousSibling); - }, - get nextSibling() { - return wrap(unsafeUnwrap(this).nextSibling); - } - }); - registerWrapper(OriginalSVGElementInstance, SVGElementInstance); - scope.wrappers.SVGElementInstance = SVGElementInstance; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var OriginalCanvasRenderingContext2D = window.CanvasRenderingContext2D; - function CanvasRenderingContext2D(impl) { - setWrapper(impl, this); - } - mixin(CanvasRenderingContext2D.prototype, { - get canvas() { - return wrap(unsafeUnwrap(this).canvas); - }, - drawImage: function() { - arguments[0] = unwrapIfNeeded(arguments[0]); - unsafeUnwrap(this).drawImage.apply(unsafeUnwrap(this), arguments); - }, - createPattern: function() { - arguments[0] = unwrap(arguments[0]); - return unsafeUnwrap(this).createPattern.apply(unsafeUnwrap(this), arguments); - } - }); - registerWrapper(OriginalCanvasRenderingContext2D, CanvasRenderingContext2D, document.createElement("canvas").getContext("2d")); - scope.wrappers.CanvasRenderingContext2D = CanvasRenderingContext2D; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var addForwardingProperties = scope.addForwardingProperties; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var OriginalWebGLRenderingContext = window.WebGLRenderingContext; - if (!OriginalWebGLRenderingContext) return; - function WebGLRenderingContext(impl) { - setWrapper(impl, this); - } - mixin(WebGLRenderingContext.prototype, { - get canvas() { - return wrap(unsafeUnwrap(this).canvas); - }, - texImage2D: function() { - arguments[5] = unwrapIfNeeded(arguments[5]); - unsafeUnwrap(this).texImage2D.apply(unsafeUnwrap(this), arguments); - }, - texSubImage2D: function() { - arguments[6] = unwrapIfNeeded(arguments[6]); - unsafeUnwrap(this).texSubImage2D.apply(unsafeUnwrap(this), arguments); - } - }); - var OriginalWebGLRenderingContextBase = Object.getPrototypeOf(OriginalWebGLRenderingContext.prototype); - if (OriginalWebGLRenderingContextBase !== Object.prototype) { - addForwardingProperties(OriginalWebGLRenderingContextBase, WebGLRenderingContext.prototype); - } - var instanceProperties = /WebKit/.test(navigator.userAgent) ? { - drawingBufferHeight: null, - drawingBufferWidth: null - } : {}; - registerWrapper(OriginalWebGLRenderingContext, WebGLRenderingContext, instanceProperties); - scope.wrappers.WebGLRenderingContext = WebGLRenderingContext; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var Node = scope.wrappers.Node; - var GetElementsByInterface = scope.GetElementsByInterface; - var NonElementParentNodeInterface = scope.NonElementParentNodeInterface; - var ParentNodeInterface = scope.ParentNodeInterface; - var SelectorsInterface = scope.SelectorsInterface; - var mixin = scope.mixin; - var registerObject = scope.registerObject; - var registerWrapper = scope.registerWrapper; - var OriginalDocumentFragment = window.DocumentFragment; - function DocumentFragment(node) { - Node.call(this, node); - } - DocumentFragment.prototype = Object.create(Node.prototype); - mixin(DocumentFragment.prototype, ParentNodeInterface); - mixin(DocumentFragment.prototype, SelectorsInterface); - mixin(DocumentFragment.prototype, GetElementsByInterface); - mixin(DocumentFragment.prototype, NonElementParentNodeInterface); - registerWrapper(OriginalDocumentFragment, DocumentFragment, document.createDocumentFragment()); - scope.wrappers.DocumentFragment = DocumentFragment; - var Comment = registerObject(document.createComment("")); - scope.wrappers.Comment = Comment; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var DocumentFragment = scope.wrappers.DocumentFragment; - var TreeScope = scope.TreeScope; - var elementFromPoint = scope.elementFromPoint; - var getInnerHTML = scope.getInnerHTML; - var getTreeScope = scope.getTreeScope; - var mixin = scope.mixin; - var rewrap = scope.rewrap; - var setInnerHTML = scope.setInnerHTML; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var shadowHostTable = new WeakMap(); - var nextOlderShadowTreeTable = new WeakMap(); - function ShadowRoot(hostWrapper) { - var node = unwrap(unsafeUnwrap(hostWrapper).ownerDocument.createDocumentFragment()); - DocumentFragment.call(this, node); - rewrap(node, this); - var oldShadowRoot = hostWrapper.shadowRoot; - nextOlderShadowTreeTable.set(this, oldShadowRoot); - this.treeScope_ = new TreeScope(this, getTreeScope(oldShadowRoot || hostWrapper)); - shadowHostTable.set(this, hostWrapper); - } - ShadowRoot.prototype = Object.create(DocumentFragment.prototype); - mixin(ShadowRoot.prototype, { - constructor: ShadowRoot, - get innerHTML() { - return getInnerHTML(this); - }, - set innerHTML(value) { - setInnerHTML(this, value); - this.invalidateShadowRenderer(); - }, - get olderShadowRoot() { - return nextOlderShadowTreeTable.get(this) || null; - }, - get host() { - return shadowHostTable.get(this) || null; - }, - invalidateShadowRenderer: function() { - return shadowHostTable.get(this).invalidateShadowRenderer(); - }, - elementFromPoint: function(x, y) { - return elementFromPoint(this, this.ownerDocument, x, y); - }, - getSelection: function() { - return document.getSelection(); - }, - get activeElement() { - var unwrappedActiveElement = unwrap(this).ownerDocument.activeElement; - if (!unwrappedActiveElement || !unwrappedActiveElement.nodeType) return null; - var activeElement = wrap(unwrappedActiveElement); - if (activeElement === this.host) { - return null; - } - while (!this.contains(activeElement) && !this.host.contains(activeElement)) { - while (activeElement.parentNode) { - activeElement = activeElement.parentNode; - } - if (activeElement.host) { - activeElement = activeElement.host; - } else { - return null; - } - } - return activeElement; - } - }); - scope.wrappers.ShadowRoot = ShadowRoot; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var getTreeScope = scope.getTreeScope; - var OriginalRange = window.Range; - var ShadowRoot = scope.wrappers.ShadowRoot; - function getHost(node) { - var root = getTreeScope(node).root; - if (root instanceof ShadowRoot) { - return root.host; - } - return null; - } - function hostNodeToShadowNode(refNode, offset) { - if (refNode.shadowRoot) { - offset = Math.min(refNode.childNodes.length - 1, offset); - var child = refNode.childNodes[offset]; - if (child) { - var insertionPoint = scope.getDestinationInsertionPoints(child); - if (insertionPoint.length > 0) { - var parentNode = insertionPoint[0].parentNode; - if (parentNode.nodeType == Node.ELEMENT_NODE) { - refNode = parentNode; - } - } - } - } - return refNode; - } - function shadowNodeToHostNode(node) { - node = wrap(node); - return getHost(node) || node; - } - function Range(impl) { - setWrapper(impl, this); - } - Range.prototype = { - get startContainer() { - return shadowNodeToHostNode(unsafeUnwrap(this).startContainer); - }, - get endContainer() { - return shadowNodeToHostNode(unsafeUnwrap(this).endContainer); - }, - get commonAncestorContainer() { - return shadowNodeToHostNode(unsafeUnwrap(this).commonAncestorContainer); - }, - setStart: function(refNode, offset) { - refNode = hostNodeToShadowNode(refNode, offset); - unsafeUnwrap(this).setStart(unwrapIfNeeded(refNode), offset); - }, - setEnd: function(refNode, offset) { - refNode = hostNodeToShadowNode(refNode, offset); - unsafeUnwrap(this).setEnd(unwrapIfNeeded(refNode), offset); - }, - setStartBefore: function(refNode) { - unsafeUnwrap(this).setStartBefore(unwrapIfNeeded(refNode)); - }, - setStartAfter: function(refNode) { - unsafeUnwrap(this).setStartAfter(unwrapIfNeeded(refNode)); - }, - setEndBefore: function(refNode) { - unsafeUnwrap(this).setEndBefore(unwrapIfNeeded(refNode)); - }, - setEndAfter: function(refNode) { - unsafeUnwrap(this).setEndAfter(unwrapIfNeeded(refNode)); - }, - selectNode: function(refNode) { - unsafeUnwrap(this).selectNode(unwrapIfNeeded(refNode)); - }, - selectNodeContents: function(refNode) { - unsafeUnwrap(this).selectNodeContents(unwrapIfNeeded(refNode)); - }, - compareBoundaryPoints: function(how, sourceRange) { - return unsafeUnwrap(this).compareBoundaryPoints(how, unwrap(sourceRange)); - }, - extractContents: function() { - return wrap(unsafeUnwrap(this).extractContents()); - }, - cloneContents: function() { - return wrap(unsafeUnwrap(this).cloneContents()); - }, - insertNode: function(node) { - unsafeUnwrap(this).insertNode(unwrapIfNeeded(node)); - }, - surroundContents: function(newParent) { - unsafeUnwrap(this).surroundContents(unwrapIfNeeded(newParent)); - }, - cloneRange: function() { - return wrap(unsafeUnwrap(this).cloneRange()); - }, - isPointInRange: function(node, offset) { - return unsafeUnwrap(this).isPointInRange(unwrapIfNeeded(node), offset); - }, - comparePoint: function(node, offset) { - return unsafeUnwrap(this).comparePoint(unwrapIfNeeded(node), offset); - }, - intersectsNode: function(node) { - return unsafeUnwrap(this).intersectsNode(unwrapIfNeeded(node)); - }, - toString: function() { - return unsafeUnwrap(this).toString(); - } - }; - if (OriginalRange.prototype.createContextualFragment) { - Range.prototype.createContextualFragment = function(html) { - return wrap(unsafeUnwrap(this).createContextualFragment(html)); - }; - } - registerWrapper(window.Range, Range, document.createRange()); - scope.wrappers.Range = Range; - })(window.ShadowDOMPolyfill); - (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; - var ArraySplice = scope.ArraySplice; - function updateWrapperUpAndSideways(wrapper) { - wrapper.previousSibling_ = wrapper.previousSibling; - wrapper.nextSibling_ = wrapper.nextSibling; - wrapper.parentNode_ = wrapper.parentNode; - } - 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() { - 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(); - } - 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; - }; - 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; - var newChildren = this.childNodes; - 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); - 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 = { - 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); - } - }, - 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); - }, - distributionResolution: function(node) { - if (isShadowHost(node)) { - var shadowHost = node; - var pool = poolPopulation(shadowHost); - var shadowTrees = getShadowTrees(shadowHost); - for (var i = 0; i < shadowTrees.length; i++) { - this.poolDistribution(shadowTrees[i], pool); - } - for (var i = shadowTrees.length - 1; i >= 0; i--) { - var shadowTree = shadowTrees[i]; - var shadow = getShadowInsertionPoint(shadowTree); - if (shadow) { - var olderShadowRoot = shadowTree.olderShadowRoot; - if (olderShadowRoot) { - pool = poolPopulation(olderShadowRoot); - } - for (var j = 0; j < pool.length; j++) { - destributeNodeInto(pool[j], shadow); - } - } - this.distributionResolution(shadowTree); - } - } - for (var child = node.firstChild; child; child = child.nextSibling) { - this.distributionResolution(child); - } - }, - poolDistribution: function(node, pool) { - if (node instanceof HTMLShadowElement) return; - if (node instanceof HTMLContentElement) { - var content = node; - this.updateDependentAttributes(content.getAttribute("select")); - var anyDistributed = false; - 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; - } - } - 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; - }, - invalidateAttributes: function() { - this.attributes = Object.create(null); - }, - updateDependentAttributes: function(selector) { - if (!selector) return; - var attributes = this.attributes; - if (/\.\w+/.test(selector)) attributes["class"] = true; - if (/#\w+/.test(selector)) attributes["id"] = true; - selector.replace(/\[\s*([^\s=\|~\]]+)/g, function(_, name) { - attributes[name] = true; - }); - }, - dependsOnAttribute: function(name) { - return this.attributes[name]; - }, - associateNode: function(node) { - unsafeUnwrap(node).polymerShadowRenderer_ = this; - } - }; - 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) { - destinationInsertionPointsTable.set(node, undefined); - } - var selectorStartCharRe = /^(:not\()?[*.#[a-zA-Z_|]/; - function matches(node, contentElement) { - var select = contentElement.getAttribute("select"); - if (!select) return true; - 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) { - 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; - } - 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(); - } - 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() { - renderAllPending(); - return getDistributedNodes(this); - }; - Element.prototype.getDestinationInsertionPoints = function() { - renderAllPending(); - return getDestinationInsertionPoints(this) || []; - }; - HTMLContentElement.prototype.nodeIsInserted_ = HTMLShadowElement.prototype.nodeIsInserted_ = function() { - 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; - scope.visual = { - insertBefore: insertBefore, - remove: remove - }; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var HTMLElement = scope.wrappers.HTMLElement; - var assert = scope.assert; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var elementsWithFormProperty = [ "HTMLButtonElement", "HTMLFieldSetElement", "HTMLInputElement", "HTMLKeygenElement", "HTMLLabelElement", "HTMLLegendElement", "HTMLObjectElement", "HTMLOutputElement", "HTMLTextAreaElement" ]; - function createWrapperConstructor(name) { - if (!window[name]) return; - assert(!scope.wrappers[name]); - var GeneratedWrapper = function(node) { - HTMLElement.call(this, node); - }; - GeneratedWrapper.prototype = Object.create(HTMLElement.prototype); - mixin(GeneratedWrapper.prototype, { - get form() { - return wrap(unwrap(this).form); - } - }); - registerWrapper(window[name], GeneratedWrapper, document.createElement(name.slice(4, -7))); - scope.wrappers[name] = GeneratedWrapper; - } - elementsWithFormProperty.forEach(createWrapperConstructor); - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var OriginalSelection = window.Selection; - function Selection(impl) { - setWrapper(impl, this); - } - Selection.prototype = { - get anchorNode() { - return wrap(unsafeUnwrap(this).anchorNode); - }, - get focusNode() { - return wrap(unsafeUnwrap(this).focusNode); - }, - addRange: function(range) { - unsafeUnwrap(this).addRange(unwrapIfNeeded(range)); - }, - collapse: function(node, index) { - unsafeUnwrap(this).collapse(unwrapIfNeeded(node), index); - }, - containsNode: function(node, allowPartial) { - return unsafeUnwrap(this).containsNode(unwrapIfNeeded(node), allowPartial); - }, - getRangeAt: function(index) { - return wrap(unsafeUnwrap(this).getRangeAt(index)); - }, - removeRange: function(range) { - unsafeUnwrap(this).removeRange(unwrap(range)); - }, - selectAllChildren: function(node) { - unsafeUnwrap(this).selectAllChildren(node instanceof ShadowRoot ? unsafeUnwrap(node.host) : unwrapIfNeeded(node)); - }, - toString: function() { - return unsafeUnwrap(this).toString(); - } - }; - if (OriginalSelection.prototype.extend) { - Selection.prototype.extend = function(node, offset) { - unsafeUnwrap(this).extend(unwrapIfNeeded(node), offset); - }; - } - registerWrapper(window.Selection, Selection, window.getSelection()); - scope.wrappers.Selection = Selection; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var OriginalTreeWalker = window.TreeWalker; - function TreeWalker(impl) { - setWrapper(impl, this); - } - TreeWalker.prototype = { - get root() { - return wrap(unsafeUnwrap(this).root); - }, - get currentNode() { - return wrap(unsafeUnwrap(this).currentNode); - }, - set currentNode(node) { - unsafeUnwrap(this).currentNode = unwrapIfNeeded(node); - }, - get filter() { - return unsafeUnwrap(this).filter; - }, - parentNode: function() { - return wrap(unsafeUnwrap(this).parentNode()); - }, - firstChild: function() { - return wrap(unsafeUnwrap(this).firstChild()); - }, - lastChild: function() { - return wrap(unsafeUnwrap(this).lastChild()); - }, - previousSibling: function() { - return wrap(unsafeUnwrap(this).previousSibling()); - }, - previousNode: function() { - return wrap(unsafeUnwrap(this).previousNode()); - }, - nextNode: function() { - return wrap(unsafeUnwrap(this).nextNode()); - } - }; - registerWrapper(OriginalTreeWalker, TreeWalker); - scope.wrappers.TreeWalker = TreeWalker; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var GetElementsByInterface = scope.GetElementsByInterface; - var Node = scope.wrappers.Node; - var ParentNodeInterface = scope.ParentNodeInterface; - var NonElementParentNodeInterface = scope.NonElementParentNodeInterface; - var Selection = scope.wrappers.Selection; - var SelectorsInterface = scope.SelectorsInterface; - var ShadowRoot = scope.wrappers.ShadowRoot; - var TreeScope = scope.TreeScope; - var cloneNode = scope.cloneNode; - var defineGetter = scope.defineGetter; - var defineWrapGetter = scope.defineWrapGetter; - var elementFromPoint = scope.elementFromPoint; - var forwardMethodsToWrapper = scope.forwardMethodsToWrapper; - var matchesNames = scope.matchesNames; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var renderAllPending = scope.renderAllPending; - var rewrap = scope.rewrap; - var setWrapper = scope.setWrapper; - var unsafeUnwrap = scope.unsafeUnwrap; - var unwrap = scope.unwrap; - var wrap = scope.wrap; - var wrapEventTargetMethods = scope.wrapEventTargetMethods; - var wrapNodeList = scope.wrapNodeList; - var implementationTable = new WeakMap(); - function Document(node) { - Node.call(this, node); - this.treeScope_ = new TreeScope(this, null); - } - Document.prototype = Object.create(Node.prototype); - defineWrapGetter(Document, "documentElement"); - defineWrapGetter(Document, "body"); - defineWrapGetter(Document, "head"); - defineGetter(Document, "activeElement", function() { - var unwrappedActiveElement = unwrap(this).activeElement; - if (!unwrappedActiveElement || !unwrappedActiveElement.nodeType) return null; - var activeElement = wrap(unwrappedActiveElement); - while (!this.contains(activeElement)) { - while (activeElement.parentNode) { - activeElement = activeElement.parentNode; - } - if (activeElement.host) { - activeElement = activeElement.host; - } else { - return null; - } - } - return activeElement; - }); - function wrapMethod(name) { - var original = document[name]; - Document.prototype[name] = function() { - return wrap(original.apply(unsafeUnwrap(this), arguments)); - }; - } - [ "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode" ].forEach(wrapMethod); - var originalAdoptNode = document.adoptNode; - function adoptNodeNoRemove(node, doc) { - originalAdoptNode.call(unsafeUnwrap(doc), unwrap(node)); - adoptSubtree(node, doc); - } - function adoptSubtree(node, doc) { - if (node.shadowRoot) doc.adoptNode(node.shadowRoot); - if (node instanceof ShadowRoot) adoptOlderShadowRoots(node, doc); - for (var child = node.firstChild; child; child = child.nextSibling) { - adoptSubtree(child, doc); - } - } - function adoptOlderShadowRoots(shadowRoot, doc) { - var oldShadowRoot = shadowRoot.olderShadowRoot; - if (oldShadowRoot) doc.adoptNode(oldShadowRoot); - } - var originalGetSelection = document.getSelection; - mixin(Document.prototype, { - adoptNode: function(node) { - if (node.parentNode) node.parentNode.removeChild(node); - adoptNodeNoRemove(node, this); - return node; - }, - elementFromPoint: function(x, y) { - return elementFromPoint(this, this, x, y); - }, - importNode: function(node, deep) { - return cloneNode(node, deep, unsafeUnwrap(this)); - }, - getSelection: function() { - renderAllPending(); - return new Selection(originalGetSelection.call(unwrap(this))); - }, - getElementsByName: function(name) { - return SelectorsInterface.querySelectorAll.call(this, "[name=" + JSON.stringify(String(name)) + "]"); - } - }); - var originalCreateTreeWalker = document.createTreeWalker; - var TreeWalkerWrapper = scope.wrappers.TreeWalker; - Document.prototype.createTreeWalker = function(root, whatToShow, filter, expandEntityReferences) { - var newFilter = null; - if (filter) { - if (filter.acceptNode && typeof filter.acceptNode === "function") { - newFilter = { - acceptNode: function(node) { - return filter.acceptNode(wrap(node)); - } - }; - } else if (typeof filter === "function") { - newFilter = function(node) { - return filter(wrap(node)); - }; - } - } - return new TreeWalkerWrapper(originalCreateTreeWalker.call(unwrap(this), unwrap(root), whatToShow, newFilter, expandEntityReferences)); - }; - if (document.registerElement) { - var originalRegisterElement = document.registerElement; - Document.prototype.registerElement = function(tagName, object) { - var prototype, extendsOption; - if (object !== undefined) { - prototype = object.prototype; - extendsOption = object.extends; - } - if (!prototype) prototype = Object.create(HTMLElement.prototype); - if (scope.nativePrototypeTable.get(prototype)) { - throw new Error("NotSupportedError"); - } - var proto = Object.getPrototypeOf(prototype); - var nativePrototype; - var prototypes = []; - while (proto) { - nativePrototype = scope.nativePrototypeTable.get(proto); - if (nativePrototype) break; - prototypes.push(proto); - proto = Object.getPrototypeOf(proto); - } - if (!nativePrototype) { - throw new Error("NotSupportedError"); - } - var newPrototype = Object.create(nativePrototype); - for (var i = prototypes.length - 1; i >= 0; i--) { - newPrototype = Object.create(newPrototype); - } - [ "createdCallback", "attachedCallback", "detachedCallback", "attributeChangedCallback" ].forEach(function(name) { - var f = prototype[name]; - if (!f) return; - newPrototype[name] = function() { - if (!(wrap(this) instanceof CustomElementConstructor)) { - rewrap(this); - } - f.apply(wrap(this), arguments); - }; - }); - var p = { - prototype: newPrototype - }; - if (extendsOption) p.extends = extendsOption; - function CustomElementConstructor(node) { - if (!node) { - if (extendsOption) { - return document.createElement(extendsOption, tagName); - } else { - return document.createElement(tagName); - } - } - setWrapper(node, this); - } - CustomElementConstructor.prototype = prototype; - CustomElementConstructor.prototype.constructor = CustomElementConstructor; - scope.constructorTable.set(newPrototype, CustomElementConstructor); - scope.nativePrototypeTable.set(prototype, newPrototype); - var nativeConstructor = originalRegisterElement.call(unwrap(this), tagName, p); - return CustomElementConstructor; - }; - forwardMethodsToWrapper([ window.HTMLDocument || window.Document ], [ "registerElement" ]); - } - forwardMethodsToWrapper([ window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement, window.HTMLHtmlElement ], [ "appendChild", "compareDocumentPosition", "contains", "getElementsByClassName", "getElementsByTagName", "getElementsByTagNameNS", "insertBefore", "querySelector", "querySelectorAll", "removeChild", "replaceChild" ]); - forwardMethodsToWrapper([ window.HTMLBodyElement, window.HTMLHeadElement, window.HTMLHtmlElement ], matchesNames); - forwardMethodsToWrapper([ window.HTMLDocument || window.Document ], [ "adoptNode", "importNode", "contains", "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode", "createTreeWalker", "elementFromPoint", "getElementById", "getElementsByName", "getSelection" ]); - mixin(Document.prototype, GetElementsByInterface); - mixin(Document.prototype, ParentNodeInterface); - mixin(Document.prototype, SelectorsInterface); - mixin(Document.prototype, NonElementParentNodeInterface); - mixin(Document.prototype, { - get implementation() { - var implementation = implementationTable.get(this); - if (implementation) return implementation; - implementation = new DOMImplementation(unwrap(this).implementation); - implementationTable.set(this, implementation); - return implementation; - }, - get defaultView() { - return wrap(unwrap(this).defaultView); - } - }); - registerWrapper(window.Document, Document, document.implementation.createHTMLDocument("")); - if (window.HTMLDocument) registerWrapper(window.HTMLDocument, Document); - wrapEventTargetMethods([ window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement ]); - function DOMImplementation(impl) { - setWrapper(impl, this); - } - var originalCreateDocument = document.implementation.createDocument; - DOMImplementation.prototype.createDocument = function() { - arguments[2] = unwrap(arguments[2]); - return wrap(originalCreateDocument.apply(unsafeUnwrap(this), arguments)); - }; - function wrapImplMethod(constructor, name) { - var original = document.implementation[name]; - constructor.prototype[name] = function() { - return wrap(original.apply(unsafeUnwrap(this), arguments)); - }; - } - function forwardImplMethod(constructor, name) { - var original = document.implementation[name]; - constructor.prototype[name] = function() { - return original.apply(unsafeUnwrap(this), arguments); - }; - } - wrapImplMethod(DOMImplementation, "createDocumentType"); - wrapImplMethod(DOMImplementation, "createHTMLDocument"); - forwardImplMethod(DOMImplementation, "hasFeature"); - registerWrapper(window.DOMImplementation, DOMImplementation); - forwardMethodsToWrapper([ window.DOMImplementation ], [ "createDocument", "createDocumentType", "createHTMLDocument", "hasFeature" ]); - scope.adoptNodeNoRemove = adoptNodeNoRemove; - scope.wrappers.DOMImplementation = DOMImplementation; - scope.wrappers.Document = Document; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var EventTarget = scope.wrappers.EventTarget; - var Selection = scope.wrappers.Selection; - var mixin = scope.mixin; - var registerWrapper = scope.registerWrapper; - var renderAllPending = scope.renderAllPending; - var unwrap = scope.unwrap; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var wrap = scope.wrap; - var OriginalWindow = window.Window; - var originalGetComputedStyle = window.getComputedStyle; - var originalGetDefaultComputedStyle = window.getDefaultComputedStyle; - var originalGetSelection = window.getSelection; - function Window(impl) { - EventTarget.call(this, impl); - } - Window.prototype = Object.create(EventTarget.prototype); - OriginalWindow.prototype.getComputedStyle = function(el, pseudo) { - return wrap(this || window).getComputedStyle(unwrapIfNeeded(el), pseudo); - }; - if (originalGetDefaultComputedStyle) { - OriginalWindow.prototype.getDefaultComputedStyle = function(el, pseudo) { - return wrap(this || window).getDefaultComputedStyle(unwrapIfNeeded(el), pseudo); - }; - } - OriginalWindow.prototype.getSelection = function() { - return wrap(this || window).getSelection(); - }; - delete window.getComputedStyle; - delete window.getDefaultComputedStyle; - delete window.getSelection; - [ "addEventListener", "removeEventListener", "dispatchEvent" ].forEach(function(name) { - OriginalWindow.prototype[name] = function() { - var w = wrap(this || window); - return w[name].apply(w, arguments); - }; - delete window[name]; - }); - mixin(Window.prototype, { - getComputedStyle: function(el, pseudo) { - renderAllPending(); - return originalGetComputedStyle.call(unwrap(this), unwrapIfNeeded(el), pseudo); - }, - getSelection: function() { - renderAllPending(); - return new Selection(originalGetSelection.call(unwrap(this))); - }, - get document() { - return wrap(unwrap(this).document); - } - }); - if (originalGetDefaultComputedStyle) { - Window.prototype.getDefaultComputedStyle = function(el, pseudo) { - renderAllPending(); - return originalGetDefaultComputedStyle.call(unwrap(this), unwrapIfNeeded(el), pseudo); - }; - } - registerWrapper(OriginalWindow, Window, window); - scope.wrappers.Window = Window; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var unwrap = scope.unwrap; - var OriginalDataTransfer = window.DataTransfer || window.Clipboard; - var OriginalDataTransferSetDragImage = OriginalDataTransfer.prototype.setDragImage; - if (OriginalDataTransferSetDragImage) { - OriginalDataTransfer.prototype.setDragImage = function(image, x, y) { - OriginalDataTransferSetDragImage.call(this, unwrap(image), x, y); - }; - } - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var registerWrapper = scope.registerWrapper; - var setWrapper = scope.setWrapper; - var unwrap = scope.unwrap; - var OriginalFormData = window.FormData; - if (!OriginalFormData) return; - function FormData(formElement) { - var impl; - if (formElement instanceof OriginalFormData) { - impl = formElement; - } else { - impl = new OriginalFormData(formElement && unwrap(formElement)); - } - setWrapper(impl, this); - } - registerWrapper(OriginalFormData, FormData, new OriginalFormData()); - scope.wrappers.FormData = FormData; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var unwrapIfNeeded = scope.unwrapIfNeeded; - var originalSend = XMLHttpRequest.prototype.send; - XMLHttpRequest.prototype.send = function(obj) { - return originalSend.call(this, unwrapIfNeeded(obj)); - }; - })(window.ShadowDOMPolyfill); - (function(scope) { - "use strict"; - var isWrapperFor = scope.isWrapperFor; - var elements = { - a: "HTMLAnchorElement", - area: "HTMLAreaElement", - audio: "HTMLAudioElement", - base: "HTMLBaseElement", - body: "HTMLBodyElement", - br: "HTMLBRElement", - button: "HTMLButtonElement", - canvas: "HTMLCanvasElement", - caption: "HTMLTableCaptionElement", - col: "HTMLTableColElement", - content: "HTMLContentElement", - data: "HTMLDataElement", - datalist: "HTMLDataListElement", - del: "HTMLModElement", - dir: "HTMLDirectoryElement", - div: "HTMLDivElement", - dl: "HTMLDListElement", - embed: "HTMLEmbedElement", - fieldset: "HTMLFieldSetElement", - font: "HTMLFontElement", - form: "HTMLFormElement", - frame: "HTMLFrameElement", - frameset: "HTMLFrameSetElement", - h1: "HTMLHeadingElement", - head: "HTMLHeadElement", - hr: "HTMLHRElement", - html: "HTMLHtmlElement", - iframe: "HTMLIFrameElement", - img: "HTMLImageElement", - input: "HTMLInputElement", - keygen: "HTMLKeygenElement", - label: "HTMLLabelElement", - legend: "HTMLLegendElement", - li: "HTMLLIElement", - link: "HTMLLinkElement", - map: "HTMLMapElement", - marquee: "HTMLMarqueeElement", - menu: "HTMLMenuElement", - menuitem: "HTMLMenuItemElement", - meta: "HTMLMetaElement", - meter: "HTMLMeterElement", - object: "HTMLObjectElement", - ol: "HTMLOListElement", - optgroup: "HTMLOptGroupElement", - option: "HTMLOptionElement", - output: "HTMLOutputElement", - p: "HTMLParagraphElement", - param: "HTMLParamElement", - pre: "HTMLPreElement", - progress: "HTMLProgressElement", - q: "HTMLQuoteElement", - script: "HTMLScriptElement", - select: "HTMLSelectElement", - shadow: "HTMLShadowElement", - source: "HTMLSourceElement", - span: "HTMLSpanElement", - style: "HTMLStyleElement", - table: "HTMLTableElement", - tbody: "HTMLTableSectionElement", - template: "HTMLTemplateElement", - textarea: "HTMLTextAreaElement", - thead: "HTMLTableSectionElement", - time: "HTMLTimeElement", - title: "HTMLTitleElement", - tr: "HTMLTableRowElement", - track: "HTMLTrackElement", - ul: "HTMLUListElement", - video: "HTMLVideoElement" - }; - function overrideConstructor(tagName) { - var nativeConstructorName = elements[tagName]; - var nativeConstructor = window[nativeConstructorName]; - if (!nativeConstructor) return; - var element = document.createElement(tagName); - var wrapperConstructor = element.constructor; - window[nativeConstructorName] = wrapperConstructor; - } - Object.keys(elements).forEach(overrideConstructor); - Object.getOwnPropertyNames(scope.wrappers).forEach(function(name) { - window[name] = scope.wrappers[name]; - }); - })(window.ShadowDOMPolyfill); - (function(scope) { - var ShadowCSS = { - strictStyling: false, - registry: {}, - shimStyling: function(root, name, extendsName) { - var scopeStyles = this.prepareRoot(root, name, extendsName); - var typeExtension = this.isTypeExtension(extendsName); - var scopeSelector = this.makeScopeSelector(name, typeExtension); - var cssText = stylesToCssText(scopeStyles, true); - cssText = this.scopeCssText(cssText, scopeSelector); - if (root) { - root.shimmedStyle = cssText; - } - this.addCssToDocument(cssText, name); - }, - shimStyle: function(style, selector) { - return this.shimCssText(style.textContent, selector); - }, - shimCssText: function(cssText, selector) { - cssText = this.insertDirectives(cssText); - return this.scopeCssText(cssText, selector); - }, - makeScopeSelector: function(name, typeExtension) { - if (name) { - return typeExtension ? "[is=" + name + "]" : name; - } - return ""; - }, - isTypeExtension: function(extendsName) { - return extendsName && extendsName.indexOf("-") < 0; - }, - prepareRoot: function(root, name, extendsName) { - var def = this.registerRoot(root, name, extendsName); - this.replaceTextInStyles(def.rootStyles, this.insertDirectives); - this.removeStyles(root, def.rootStyles); - if (this.strictStyling) { - this.applyScopeToContent(root, name); - } - return def.scopeStyles; - }, - removeStyles: function(root, styles) { - for (var i = 0, l = styles.length, s; i < l && (s = styles[i]); i++) { - s.parentNode.removeChild(s); - } - }, - registerRoot: function(root, name, extendsName) { - var def = this.registry[name] = { - root: root, - name: name, - extendsName: extendsName - }; - var styles = this.findStyles(root); - def.rootStyles = styles; - def.scopeStyles = def.rootStyles; - var extendee = this.registry[def.extendsName]; - if (extendee) { - def.scopeStyles = extendee.scopeStyles.concat(def.scopeStyles); - } - return def; - }, - findStyles: function(root) { - if (!root) { - return []; - } - var styles = root.querySelectorAll("style"); - return Array.prototype.filter.call(styles, function(s) { - return !s.hasAttribute(NO_SHIM_ATTRIBUTE); - }); - }, - applyScopeToContent: function(root, name) { - if (root) { - Array.prototype.forEach.call(root.querySelectorAll("*"), function(node) { - node.setAttribute(name, ""); - }); - Array.prototype.forEach.call(root.querySelectorAll("template"), function(template) { - this.applyScopeToContent(template.content, name); - }, this); - } - }, - insertDirectives: function(cssText) { - cssText = this.insertPolyfillDirectivesInCssText(cssText); - return this.insertPolyfillRulesInCssText(cssText); - }, - insertPolyfillDirectivesInCssText: function(cssText) { - cssText = cssText.replace(cssCommentNextSelectorRe, function(match, p1) { - return p1.slice(0, -2) + "{"; - }); - return cssText.replace(cssContentNextSelectorRe, function(match, p1) { - return p1 + " {"; - }); - }, - insertPolyfillRulesInCssText: function(cssText) { - cssText = cssText.replace(cssCommentRuleRe, function(match, p1) { - return p1.slice(0, -1); - }); - return cssText.replace(cssContentRuleRe, function(match, p1, p2, p3) { - var rule = match.replace(p1, "").replace(p2, ""); - return p3 + rule; - }); - }, - scopeCssText: function(cssText, scopeSelector) { - var unscoped = this.extractUnscopedRulesFromCssText(cssText); - cssText = this.insertPolyfillHostInCssText(cssText); - cssText = this.convertColonHost(cssText); - cssText = this.convertColonHostContext(cssText); - cssText = this.convertShadowDOMSelectors(cssText); - if (scopeSelector) { - var self = this, cssText; - withCssRules(cssText, function(rules) { - cssText = self.scopeRules(rules, scopeSelector); - }); - } - cssText = cssText + "\n" + unscoped; - return cssText.trim(); - }, - extractUnscopedRulesFromCssText: function(cssText) { - var r = "", m; - while (m = cssCommentUnscopedRuleRe.exec(cssText)) { - r += m[1].slice(0, -1) + "\n\n"; - } - while (m = cssContentUnscopedRuleRe.exec(cssText)) { - r += m[0].replace(m[2], "").replace(m[1], m[3]) + "\n\n"; - } - return r; - }, - convertColonHost: function(cssText) { - return this.convertColonRule(cssText, cssColonHostRe, this.colonHostPartReplacer); - }, - convertColonHostContext: function(cssText) { - return this.convertColonRule(cssText, cssColonHostContextRe, this.colonHostContextPartReplacer); - }, - convertColonRule: function(cssText, regExp, partReplacer) { - return cssText.replace(regExp, function(m, p1, p2, p3) { - p1 = polyfillHostNoCombinator; - if (p2) { - var parts = p2.split(","), r = []; - for (var i = 0, l = parts.length, p; i < l && (p = parts[i]); i++) { - p = p.trim(); - r.push(partReplacer(p1, p, p3)); - } - return r.join(","); - } else { - return p1 + p3; - } - }); - }, - colonHostContextPartReplacer: function(host, part, suffix) { - if (part.match(polyfillHost)) { - return this.colonHostPartReplacer(host, part, suffix); - } else { - return host + part + suffix + ", " + part + " " + host + suffix; - } - }, - colonHostPartReplacer: function(host, part, suffix) { - return host + part.replace(polyfillHost, "") + suffix; - }, - convertShadowDOMSelectors: function(cssText) { - for (var i = 0; i < shadowDOMSelectorsRe.length; i++) { - cssText = cssText.replace(shadowDOMSelectorsRe[i], " "); - } - return cssText; - }, - scopeRules: function(cssRules, scopeSelector) { - var cssText = ""; - if (cssRules) { - Array.prototype.forEach.call(cssRules, function(rule) { - if (rule.selectorText && (rule.style && rule.style.cssText !== undefined)) { - cssText += this.scopeSelector(rule.selectorText, scopeSelector, this.strictStyling) + " {\n "; - cssText += this.propertiesFromRule(rule) + "\n}\n\n"; - } else if (rule.type === CSSRule.MEDIA_RULE) { - cssText += "@media " + rule.media.mediaText + " {\n"; - cssText += this.scopeRules(rule.cssRules, scopeSelector); - cssText += "\n}\n\n"; - } else { - try { - if (rule.cssText) { - cssText += rule.cssText + "\n\n"; - } - } catch (x) { - if (rule.type === CSSRule.KEYFRAMES_RULE && rule.cssRules) { - cssText += this.ieSafeCssTextFromKeyFrameRule(rule); - } - } - } - }, this); - } - return cssText; - }, - ieSafeCssTextFromKeyFrameRule: function(rule) { - var cssText = "@keyframes " + rule.name + " {"; - Array.prototype.forEach.call(rule.cssRules, function(rule) { - cssText += " " + rule.keyText + " {" + rule.style.cssText + "}"; - }); - cssText += " }"; - return cssText; - }, - scopeSelector: function(selector, scopeSelector, strict) { - var r = [], parts = selector.split(","); - parts.forEach(function(p) { - p = p.trim(); - if (this.selectorNeedsScoping(p, scopeSelector)) { - p = strict && !p.match(polyfillHostNoCombinator) ? this.applyStrictSelectorScope(p, scopeSelector) : this.applySelectorScope(p, scopeSelector); - } - r.push(p); - }, this); - return r.join(", "); - }, - selectorNeedsScoping: function(selector, scopeSelector) { - if (Array.isArray(scopeSelector)) { - return true; - } - var re = this.makeScopeMatcher(scopeSelector); - return !selector.match(re); - }, - makeScopeMatcher: function(scopeSelector) { - scopeSelector = scopeSelector.replace(/\[/g, "\\[").replace(/\]/g, "\\]"); - return new RegExp("^(" + scopeSelector + ")" + selectorReSuffix, "m"); - }, - applySelectorScope: function(selector, selectorScope) { - return Array.isArray(selectorScope) ? this.applySelectorScopeList(selector, selectorScope) : this.applySimpleSelectorScope(selector, selectorScope); - }, - applySelectorScopeList: function(selector, scopeSelectorList) { - var r = []; - for (var i = 0, s; s = scopeSelectorList[i]; i++) { - r.push(this.applySimpleSelectorScope(selector, s)); - } - return r.join(", "); - }, - applySimpleSelectorScope: function(selector, scopeSelector) { - if (selector.match(polyfillHostRe)) { - selector = selector.replace(polyfillHostNoCombinator, scopeSelector); - return selector.replace(polyfillHostRe, scopeSelector + " "); - } else { - return scopeSelector + " " + selector; - } - }, - applyStrictSelectorScope: function(selector, scopeSelector) { - scopeSelector = scopeSelector.replace(/\[is=([^\]]*)\]/g, "$1"); - var splits = [ " ", ">", "+", "~" ], scoped = selector, attrName = "[" + scopeSelector + "]"; - splits.forEach(function(sep) { - var parts = scoped.split(sep); - scoped = parts.map(function(p) { - var t = p.trim().replace(polyfillHostRe, ""); - if (t && splits.indexOf(t) < 0 && t.indexOf(attrName) < 0) { - p = t.replace(/([^:]*)(:*)(.*)/, "$1" + attrName + "$2$3"); - } - return p; - }).join(sep); - }); - return scoped; - }, - insertPolyfillHostInCssText: function(selector) { - return selector.replace(colonHostContextRe, polyfillHostContext).replace(colonHostRe, polyfillHost); - }, - propertiesFromRule: function(rule) { - var cssText = rule.style.cssText; - if (rule.style.content && !rule.style.content.match(/['"]+|attr/)) { - cssText = cssText.replace(/content:[^;]*;/g, "content: '" + rule.style.content + "';"); - } - var style = rule.style; - for (var i in style) { - if (style[i] === "initial") { - cssText += i + ": initial; "; - } - } - return cssText; - }, - replaceTextInStyles: function(styles, action) { - if (styles && action) { - if (!(styles instanceof Array)) { - styles = [ styles ]; - } - Array.prototype.forEach.call(styles, function(s) { - s.textContent = action.call(this, s.textContent); - }, this); - } - }, - addCssToDocument: function(cssText, name) { - if (cssText.match("@import")) { - addOwnSheet(cssText, name); - } else { - addCssToDocument(cssText); - } - } - }; - var selectorRe = /([^{]*)({[\s\S]*?})/gim, cssCommentRe = /\/\*[^*]*\*+([^\/*][^*]*\*+)*\//gim, cssCommentNextSelectorRe = /\/\*\s*@polyfill ([^*]*\*+([^\/*][^*]*\*+)*\/)([^{]*?){/gim, cssContentNextSelectorRe = /polyfill-next-selector[^}]*content\:[\s]*?['"](.*?)['"][;\s]*}([^{]*?){/gim, cssCommentRuleRe = /\/\*\s@polyfill-rule([^*]*\*+([^\/*][^*]*\*+)*)\//gim, cssContentRuleRe = /(polyfill-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim, cssCommentUnscopedRuleRe = /\/\*\s@polyfill-unscoped-rule([^*]*\*+([^\/*][^*]*\*+)*)\//gim, cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim, cssPseudoRe = /::(x-[^\s{,(]*)/gim, cssPartRe = /::part\(([^)]*)\)/gim, polyfillHost = "-shadowcsshost", polyfillHostContext = "-shadowcsscontext", parenSuffix = ")(?:\\((" + "(?:\\([^)(]*\\)|[^)(]*)+?" + ")\\))?([^,{]*)"; - var cssColonHostRe = new RegExp("(" + polyfillHost + parenSuffix, "gim"), cssColonHostContextRe = new RegExp("(" + polyfillHostContext + parenSuffix, "gim"), selectorReSuffix = "([>\\s~+[.,{:][\\s\\S]*)?$", colonHostRe = /\:host/gim, colonHostContextRe = /\:host-context/gim, polyfillHostNoCombinator = polyfillHost + "-no-combinator", polyfillHostRe = new RegExp(polyfillHost, "gim"), polyfillHostContextRe = new RegExp(polyfillHostContext, "gim"), shadowDOMSelectorsRe = [ />>>/g, /::shadow/g, /::content/g, /\/deep\//g, /\/shadow\//g, /\/shadow-deep\//g, /\^\^/g, /\^/g ]; - function stylesToCssText(styles, preserveComments) { - var cssText = ""; - Array.prototype.forEach.call(styles, function(s) { - cssText += s.textContent + "\n\n"; - }); - if (!preserveComments) { - cssText = cssText.replace(cssCommentRe, ""); - } - return cssText; - } - function cssTextToStyle(cssText) { - var style = document.createElement("style"); - style.textContent = cssText; - return style; - } - function cssToRules(cssText) { - var style = cssTextToStyle(cssText); - document.head.appendChild(style); - var rules = []; - if (style.sheet) { - try { - rules = style.sheet.cssRules; - } catch (e) {} - } else { - console.warn("sheet not found", style); - } - style.parentNode.removeChild(style); - return rules; - } - var frame = document.createElement("iframe"); - frame.style.display = "none"; - function initFrame() { - frame.initialized = true; - document.body.appendChild(frame); - var doc = frame.contentDocument; - var base = doc.createElement("base"); - base.href = document.baseURI; - doc.head.appendChild(base); - } - function inFrame(fn) { - if (!frame.initialized) { - initFrame(); - } - document.body.appendChild(frame); - fn(frame.contentDocument); - document.body.removeChild(frame); - } - var isChrome = navigator.userAgent.match("Chrome"); - function withCssRules(cssText, callback) { - if (!callback) { - return; - } - var rules; - if (cssText.match("@import") && isChrome) { - var style = cssTextToStyle(cssText); - inFrame(function(doc) { - doc.head.appendChild(style.impl); - rules = Array.prototype.slice.call(style.sheet.cssRules, 0); - callback(rules); - }); - } else { - rules = cssToRules(cssText); - callback(rules); - } - } - function rulesToCss(cssRules) { - for (var i = 0, css = []; i < cssRules.length; i++) { - css.push(cssRules[i].cssText); - } - return css.join("\n\n"); - } - function addCssToDocument(cssText) { - if (cssText) { - getSheet().appendChild(document.createTextNode(cssText)); - } - } - function addOwnSheet(cssText, name) { - var style = cssTextToStyle(cssText); - style.setAttribute(name, ""); - style.setAttribute(SHIMMED_ATTRIBUTE, ""); - document.head.appendChild(style); - } - var SHIM_ATTRIBUTE = "shim-shadowdom"; - var SHIMMED_ATTRIBUTE = "shim-shadowdom-css"; - var NO_SHIM_ATTRIBUTE = "no-shim"; - var sheet; - function getSheet() { - if (!sheet) { - sheet = document.createElement("style"); - sheet.setAttribute(SHIMMED_ATTRIBUTE, ""); - sheet[SHIMMED_ATTRIBUTE] = true; - } - return sheet; - } - if (window.ShadowDOMPolyfill) { - addCssToDocument("style { display: none !important; }\n"); - var doc = ShadowDOMPolyfill.wrap(document); - var head = doc.querySelector("head"); - head.insertBefore(getSheet(), head.childNodes[0]); - document.addEventListener("DOMContentLoaded", function() { - var urlResolver = scope.urlResolver; - if (window.HTMLImports && !HTMLImports.useNative) { - var SHIM_SHEET_SELECTOR = "link[rel=stylesheet]" + "[" + SHIM_ATTRIBUTE + "]"; - var SHIM_STYLE_SELECTOR = "style[" + SHIM_ATTRIBUTE + "]"; - HTMLImports.importer.documentPreloadSelectors += "," + SHIM_SHEET_SELECTOR; - HTMLImports.importer.importsPreloadSelectors += "," + SHIM_SHEET_SELECTOR; - HTMLImports.parser.documentSelectors = [ HTMLImports.parser.documentSelectors, SHIM_SHEET_SELECTOR, SHIM_STYLE_SELECTOR ].join(","); - var originalParseGeneric = HTMLImports.parser.parseGeneric; - HTMLImports.parser.parseGeneric = function(elt) { - if (elt[SHIMMED_ATTRIBUTE]) { - return; - } - var style = elt.__importElement || elt; - if (!style.hasAttribute(SHIM_ATTRIBUTE)) { - originalParseGeneric.call(this, elt); - return; - } - if (elt.__resource) { - style = elt.ownerDocument.createElement("style"); - style.textContent = elt.__resource; - } - HTMLImports.path.resolveUrlsInStyle(style, elt.href); - style.textContent = ShadowCSS.shimStyle(style); - style.removeAttribute(SHIM_ATTRIBUTE, ""); - style.setAttribute(SHIMMED_ATTRIBUTE, ""); - style[SHIMMED_ATTRIBUTE] = true; - if (style.parentNode !== head) { - if (elt.parentNode === head) { - head.replaceChild(style, elt); - } else { - this.addElementToDocument(style); - } - } - style.__importParsed = true; - this.markParsingComplete(elt); - this.parseNext(); - }; - var hasResource = HTMLImports.parser.hasResource; - HTMLImports.parser.hasResource = function(node) { - if (node.localName === "link" && node.rel === "stylesheet" && node.hasAttribute(SHIM_ATTRIBUTE)) { - return node.__resource; - } else { - return hasResource.call(this, node); - } - }; - } - }); - } - scope.ShadowCSS = ShadowCSS; - })(window.WebComponents); -} - -(function(scope) { - if (window.ShadowDOMPolyfill) { - window.wrap = ShadowDOMPolyfill.wrapIfNeeded; - window.unwrap = ShadowDOMPolyfill.unwrapIfNeeded; - } else { - window.wrap = window.unwrap = function(n) { - return n; - }; - } -})(window.WebComponents); - -(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 && " " != 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 (" " == 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 (" " == 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 (" " != 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 (" " == 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 (" " != c && "\n" != c && "\r" != c) { - buffer += percentEscape(c); - } - break; - - case "query": - if (!stateOverride && "#" == c) { - this._fragment = "#"; - state = "fragment"; - } else if (EOF != c && " " != c && "\n" != c && "\r" != c) { - this._query += percentEscapeQuery(c); - } - break; - - case "fragment": - if (EOF != c && " " != 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); - -(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(scope) { - "use strict"; - if (!window.performance) { - 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.HTMLImports.__importsParsingHook) { - window.HTMLImports.__importsParsingHook(elt); - } - if (elt.import) { - elt.import.__importParsed = true; - } - this.markParsingComplete(elt); - if (elt.__resource && !elt.__error) { - elt.dispatchEvent(new CustomEvent("load", { - bubbles: false - })); - } else { - elt.dispatchEvent(new CustomEvent("error", { - bubbles: false - })); - } - if (elt.__pending) { - var fn; - while (elt.__pending.length) { - fn = elt.__pending.shift(); - if (fn) { - fn({ - target: elt - }); - } - } - } - this.parseNext(); - }, - parseLink: function(linkElt) { - if (nodeIsImport(linkElt)) { - this.parseImport(linkElt); - } else { - linkElt.href = linkElt.href; - this.parseGeneric(linkElt); - } - }, - parseStyle: function(elt) { - var src = elt; - elt = cloneStyle(elt); - src.__appliedElement = elt; - elt.__importElement = src; - this.parseGeneric(elt); - }, - parseGeneric: function(elt) { - this.trackElement(elt); - this.addElementToDocument(elt); - }, - rootImportForElement: function(elt) { - var n = elt; - while (n.ownerDocument.__importLink) { - n = n.ownerDocument.__importLink; - } - return n; - }, - addElementToDocument: function(elt) { - var port = this.rootImportForElement(elt.__importElement || elt); - port.parentNode.insertBefore(elt, port); - }, - trackElement: function(elt, callback) { - var self = this; - var done = function(e) { - elt.removeEventListener("load", done); - elt.removeEventListener("error", done); - if (callback) { - callback(e); - } - self.markParsingComplete(elt); - self.parseNext(); - }; - elt.addEventListener("load", done); - elt.addEventListener("error", done); - if (isIE && elt.localName === "style") { - var fakeLoad = false; - if (elt.textContent.indexOf("@import") == -1) { - fakeLoad = true; - } else if (elt.sheet) { - fakeLoad = true; - var csr = elt.sheet.cssRules; - var len = csr ? csr.length : 0; - for (var i = 0, r; i < len && (r = csr[i]); i++) { - if (r.type === CSSRule.IMPORT_RULE) { - fakeLoad = fakeLoad && Boolean(r.styleSheet); - } - } - } - if (fakeLoad) { - setTimeout(function() { - elt.dispatchEvent(new CustomEvent("load", { - bubbles: false - })); - }); - } - } - }, - parseScript: function(scriptElt) { - var script = document.createElement("script"); - script.__importElement = scriptElt; - script.src = scriptElt.src ? scriptElt.src : generateScriptDataUrl(scriptElt); - scope.currentScript = scriptElt; - this.trackElement(script, function(e) { - if (script.parentNode) { - script.parentNode.removeChild(script); - } - scope.currentScript = null; - }); - this.addElementToDocument(script); - }, - nextToParse: function() { - this._mayParse = []; - return !this.parsingElement && (this.nextToParseInDoc(rootDocument) || this.nextToParseDynamic()); - }, - nextToParseInDoc: function(doc, link) { - if (doc && this._mayParse.indexOf(doc) < 0) { - this._mayParse.push(doc); - var nodes = doc.querySelectorAll(this.parseSelectorsForNode(doc)); - for (var i = 0, l = nodes.length, p = 0, n; i < l && (n = nodes[i]); i++) { - if (!this.isParsed(n)) { - if (this.hasResource(n)) { - return nodeIsImport(n) ? this.nextToParseInDoc(n.__doc, n) : n; - } else { - return; - } - } - } - } - return link; - }, - nextToParseDynamic: function() { - return this.dynamicElements[0]; - }, - parseSelectorsForNode: function(node) { - var doc = node.ownerDocument || node; - return doc === rootDocument ? this.documentSelectors : this.importsSelectors; - }, - isParsed: function(node) { - return node.__importParsed; - }, - needsDynamicParsing: function(elt) { - return this.dynamicElements.indexOf(elt) >= 0; - }, - hasResource: function(node) { - if (nodeIsImport(node) && node.__doc === undefined) { - return false; - } - return true; - } - }; - function nodeIsImport(elt) { - return elt.localName === "link" && elt.rel === IMPORT_LINK_TYPE; - } - function generateScriptDataUrl(script) { - var scriptContent = generateScriptContent(script); - return "data:text/javascript;charset=utf-8," + encodeURIComponent(scriptContent); - } - function generateScriptContent(script) { - return script.textContent + generateSourceMapHint(script); - } - function generateSourceMapHint(script) { - var owner = script.ownerDocument; - owner.__importedScripts = owner.__importedScripts || 0; - var moniker = script.ownerDocument.baseURI; - var num = owner.__importedScripts ? "-" + owner.__importedScripts : ""; - owner.__importedScripts++; - return "\n//# sourceURL=" + moniker + num + ".js\n"; - } - function cloneStyle(style) { - var clone = style.ownerDocument.createElement("style"); - clone.textContent = style.textContent; - path.resolveUrlsInStyle(clone); - return clone; - } - scope.parser = importParser; - scope.IMPORT_SELECTOR = IMPORT_SELECTOR; -}); - -window.HTMLImports.addModule(function(scope) { - var flags = scope.flags; - var IMPORT_LINK_TYPE = scope.IMPORT_LINK_TYPE; - var IMPORT_SELECTOR = scope.IMPORT_SELECTOR; - var rootDocument = scope.rootDocument; - var Loader = scope.Loader; - var Observer = scope.Observer; - var parser = scope.parser; - var importer = { - documents: {}, - documentPreloadSelectors: IMPORT_SELECTOR, - importsPreloadSelectors: [ IMPORT_SELECTOR ].join(","), - loadNode: function(node) { - importLoader.addNode(node); - }, - loadSubtree: function(parent) { - var nodes = this.marshalNodes(parent); - importLoader.addNodes(nodes); - }, - marshalNodes: function(parent) { - return parent.querySelectorAll(this.loadSelectorsForNode(parent)); - }, - loadSelectorsForNode: function(node) { - var doc = node.ownerDocument || node; - return doc === rootDocument ? this.documentPreloadSelectors : this.importsPreloadSelectors; - }, - loaded: function(url, elt, resource, err, redirectedUrl) { - flags.load && console.log("loaded", url, elt); - elt.__resource = resource; - elt.__error = err; - if (isImportLink(elt)) { - var doc = this.documents[url]; - if (doc === undefined) { - doc = err ? null : makeDocument(resource, redirectedUrl || url); - if (doc) { - doc.__importLink = elt; - this.bootDocument(doc); - } - this.documents[url] = doc; - } - elt.__doc = doc; - } - parser.parseNext(); - }, - bootDocument: function(doc) { - this.loadSubtree(doc); - this.observer.observe(doc); - parser.parseNext(); - }, - loadedAll: function() { - parser.parseNext(); - } - }; - var importLoader = new Loader(importer.loaded.bind(importer), importer.loadedAll.bind(importer)); - importer.observer = new Observer(); - function isImportLink(elt) { - return isLinkRel(elt, IMPORT_LINK_TYPE); - } - function isLinkRel(elt, rel) { - return elt.localName === "link" && elt.getAttribute("rel") === rel; - } - function hasBaseURIAccessor(doc) { - return !!Object.getOwnPropertyDescriptor(doc, "baseURI"); - } - function makeDocument(resource, url) { - var doc = document.implementation.createHTMLDocument(IMPORT_LINK_TYPE); - doc._URL = url; - var base = doc.createElement("base"); - base.setAttribute("href", url); - if (!doc.baseURI && !hasBaseURIAccessor(doc)) { - Object.defineProperty(doc, "baseURI", { - value: url - }); - } - var meta = doc.createElement("meta"); - meta.setAttribute("charset", "utf-8"); - doc.head.appendChild(meta); - doc.head.appendChild(base); - doc.body.innerHTML = resource; - if (window.HTMLTemplateElement && HTMLTemplateElement.bootstrap) { - HTMLTemplateElement.bootstrap(doc); - } - return doc; - } - if (!document.baseURI) { - var baseURIDescriptor = { - get: function() { - var base = document.querySelector("base"); - return base ? base.href : window.location.href; - }, - configurable: true - }; - Object.defineProperty(document, "baseURI", baseURIDescriptor); - Object.defineProperty(rootDocument, "baseURI", baseURIDescriptor); - } - scope.importer = importer; - scope.importLoader = importLoader; -}); - -window.HTMLImports.addModule(function(scope) { - var parser = scope.parser; - var importer = scope.importer; - var dynamic = { - added: function(nodes) { - var owner, parsed, loading; - for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) { - if (!owner) { - owner = n.ownerDocument; - parsed = parser.isParsed(owner); - } - loading = this.shouldLoadNode(n); - if (loading) { - importer.loadNode(n); - } - if (this.shouldParseNode(n) && parsed) { - parser.parseDynamic(n, loading); - } - } - }, - shouldLoadNode: function(node) { - return node.nodeType === 1 && matches.call(node, importer.loadSelectorsForNode(node)); - }, - shouldParseNode: function(node) { - return node.nodeType === 1 && matches.call(node, parser.parseSelectorsForNode(node)); - } - }; - importer.observer.addCallback = dynamic.added.bind(dynamic); - var matches = HTMLElement.prototype.matches || HTMLElement.prototype.matchesSelector || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector || HTMLElement.prototype.msMatchesSelector; -}); - -(function(scope) { - var initializeModules = scope.initializeModules; - var isIE = scope.isIE; - if (scope.useNative) { - return; - } - initializeModules(); - var rootDocument = scope.rootDocument; - function bootstrap() { - window.HTMLImports.importer.bootDocument(rootDocument); - } - if (document.readyState === "complete" || document.readyState === "interactive" && !window.attachEvent) { - bootstrap(); - } else { - document.addEventListener("DOMContentLoaded", bootstrap); - } -})(window.HTMLImports); - -window.CustomElements = window.CustomElements || { - flags: {} -}; - -(function(scope) { - var flags = scope.flags; - var modules = []; - var addModule = function(module) { - modules.push(module); - }; - var initializeModules = function() { - modules.forEach(function(module) { - module(scope); - }); - }; - scope.addModule = addModule; - scope.initializeModules = initializeModules; - scope.hasNative = Boolean(document.registerElement); - scope.isIE = /Trident/.test(navigator.userAgent); - scope.useNative = !flags.register && scope.hasNative && !window.ShadowDOMPolyfill && (!window.HTMLImports || window.HTMLImports.useNative); -})(window.CustomElements); - -window.CustomElements.addModule(function(scope) { - var IMPORT_LINK_TYPE = window.HTMLImports ? window.HTMLImports.IMPORT_LINK_TYPE : "none"; - function forSubtree(node, cb) { - findAllElements(node, function(e) { - if (cb(e)) { - return true; - } - forRoots(e, cb); - }); - forRoots(node, cb); - } - function findAllElements(node, find, data) { - var e = node.firstElementChild; - if (!e) { - e = node.firstChild; - while (e && e.nodeType !== Node.ELEMENT_NODE) { - e = e.nextSibling; - } - } - while (e) { - if (find(e, data) !== true) { - findAllElements(e, find, data); - } - e = e.nextElementSibling; - } - return null; - } - function forRoots(node, cb) { - var root = node.shadowRoot; - while (root) { - forSubtree(root, cb); - root = root.olderShadowRoot; - } - } - function forDocumentTree(doc, cb) { - _forDocumentTree(doc, cb, []); - } - function _forDocumentTree(doc, cb, processingDocuments) { - doc = window.wrap(doc); - if (processingDocuments.indexOf(doc) >= 0) { - return; - } - processingDocuments.push(doc); - var imports = doc.querySelectorAll("link[rel=" + IMPORT_LINK_TYPE + "]"); - for (var i = 0, l = imports.length, n; i < l && (n = imports[i]); i++) { - if (n.import) { - _forDocumentTree(n.import, cb, processingDocuments); - } - } - cb(doc); - } - scope.forDocumentTree = forDocumentTree; - scope.forSubtree = forSubtree; -}); - -window.CustomElements.addModule(function(scope) { - var flags = scope.flags; - var forSubtree = scope.forSubtree; - var forDocumentTree = scope.forDocumentTree; - function addedNode(node, isAttached) { - return added(node, isAttached) || addedSubtree(node, isAttached); - } - function added(node, isAttached) { - if (scope.upgrade(node, isAttached)) { - return true; - } - if (isAttached) { - attached(node); - } - } - function addedSubtree(node, isAttached) { - forSubtree(node, function(e) { - if (added(e, isAttached)) { - return true; - } - }); - } - var hasThrottledAttached = window.MutationObserver._isPolyfilled && flags["throttle-attached"]; - scope.hasPolyfillMutations = hasThrottledAttached; - scope.hasThrottledAttached = hasThrottledAttached; - var isPendingMutations = false; - var pendingMutations = []; - function deferMutation(fn) { - pendingMutations.push(fn); - if (!isPendingMutations) { - isPendingMutations = true; - setTimeout(takeMutations); - } - } - function takeMutations() { - isPendingMutations = false; - var $p = pendingMutations; - for (var i = 0, l = $p.length, p; i < l && (p = $p[i]); i++) { - p(); - } - pendingMutations = []; - } - function attached(element) { - if (hasThrottledAttached) { - deferMutation(function() { - _attached(element); - }); - } else { - _attached(element); - } - } - function _attached(element) { - if (element.__upgraded__ && !element.__attached) { - element.__attached = true; - if (element.attachedCallback) { - element.attachedCallback(); - } - } - } - function detachedNode(node) { - detached(node); - forSubtree(node, function(e) { - detached(e); - }); - } - function detached(element) { - if (hasThrottledAttached) { - deferMutation(function() { - _detached(element); - }); - } else { - _detached(element); - } - } - function _detached(element) { - if (element.__upgraded__ && element.__attached) { - element.__attached = false; - if (element.detachedCallback) { - element.detachedCallback(); - } - } - } - function inDocument(element) { - var p = element; - var doc = window.wrap(document); - while (p) { - if (p == doc) { - return true; - } - p = p.parentNode || p.nodeType === Node.DOCUMENT_FRAGMENT_NODE && p.host; - } - } - function watchShadow(node) { - if (node.shadowRoot && !node.shadowRoot.__watched) { - flags.dom && console.log("watching shadow-root for: ", node.localName); - var root = node.shadowRoot; - while (root) { - observe(root); - root = root.olderShadowRoot; - } - } - } - function handler(root, mutations) { - if (flags.dom) { - var mx = mutations[0]; - if (mx && mx.type === "childList" && mx.addedNodes) { - if (mx.addedNodes) { - var d = mx.addedNodes[0]; - while (d && d !== document && !d.host) { - d = d.parentNode; - } - var u = d && (d.URL || d._URL || d.host && d.host.localName) || ""; - u = u.split("/?").shift().split("/").pop(); - } - } - console.group("mutations (%d) [%s]", mutations.length, u || ""); - } - var isAttached = inDocument(root); - mutations.forEach(function(mx) { - if (mx.type === "childList") { - forEach(mx.addedNodes, function(n) { - if (!n.localName) { - return; - } - addedNode(n, isAttached); - }); - forEach(mx.removedNodes, function(n) { - if (!n.localName) { - return; - } - detachedNode(n); - }); - } - }); - flags.dom && console.groupEnd(); - } - function takeRecords(node) { - node = window.wrap(node); - if (!node) { - node = window.wrap(document); - } - while (node.parentNode) { - node = node.parentNode; - } - var observer = node.__observer; - if (observer) { - handler(node, observer.takeRecords()); - takeMutations(); - } - } - var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); - function observe(inRoot) { - if (inRoot.__observer) { - return; - } - var observer = new MutationObserver(handler.bind(this, inRoot)); - observer.observe(inRoot, { - childList: true, - subtree: true - }); - inRoot.__observer = observer; - } - function upgradeDocument(doc) { - doc = window.wrap(doc); - flags.dom && console.group("upgradeDocument: ", doc.baseURI.split("/").pop()); - var isMainDocument = doc === window.wrap(document); - addedNode(doc, isMainDocument); - observe(doc); - flags.dom && console.groupEnd(); - } - function upgradeDocumentTree(doc) { - forDocumentTree(doc, upgradeDocument); - } - var originalCreateShadowRoot = Element.prototype.createShadowRoot; - if (originalCreateShadowRoot) { - Element.prototype.createShadowRoot = function() { - var root = originalCreateShadowRoot.call(this); - window.CustomElements.watchShadow(this); - return root; - }; - } - scope.watchShadow = watchShadow; - scope.upgradeDocumentTree = upgradeDocumentTree; - scope.upgradeDocument = upgradeDocument; - scope.upgradeSubtree = addedSubtree; - scope.upgradeAll = addedNode; - scope.attached = attached; - scope.takeRecords = takeRecords; -}); - -window.CustomElements.addModule(function(scope) { - var flags = scope.flags; - function upgrade(node, isAttached) { - if (node.localName === "template") { - if (window.HTMLTemplateElement && HTMLTemplateElement.decorate) { - HTMLTemplateElement.decorate(node); - } - } - if (!node.__upgraded__ && node.nodeType === Node.ELEMENT_NODE) { - var is = node.getAttribute("is"); - var definition = scope.getRegisteredDefinition(node.localName) || scope.getRegisteredDefinition(is); - if (definition) { - if (is && definition.tag == node.localName || !is && !definition.extends) { - return upgradeWithDefinition(node, definition, isAttached); - } - } - } - } - function upgradeWithDefinition(element, definition, isAttached) { - flags.upgrade && console.group("upgrade:", element.localName); - if (definition.is) { - element.setAttribute("is", definition.is); - } - implementPrototype(element, definition); - element.__upgraded__ = true; - created(element); - if (isAttached) { - scope.attached(element); - } - scope.upgradeSubtree(element, isAttached); - flags.upgrade && console.groupEnd(); - return element; - } - function implementPrototype(element, definition) { - if (Object.__proto__) { - element.__proto__ = definition.prototype; - } else { - customMixin(element, definition.prototype, definition.native); - element.__proto__ = definition.prototype; - } - } - function customMixin(inTarget, inSrc, inNative) { - var used = {}; - var p = inSrc; - while (p !== inNative && p !== HTMLElement.prototype) { - var keys = Object.getOwnPropertyNames(p); - for (var i = 0, k; k = keys[i]; i++) { - if (!used[k]) { - Object.defineProperty(inTarget, k, Object.getOwnPropertyDescriptor(p, k)); - used[k] = 1; - } - } - p = Object.getPrototypeOf(p); - } - } - function created(element) { - if (element.createdCallback) { - element.createdCallback(); - } - } - scope.upgrade = upgrade; - scope.upgradeWithDefinition = upgradeWithDefinition; - scope.implementPrototype = implementPrototype; -}); - -window.CustomElements.addModule(function(scope) { - var isIE = scope.isIE; - var upgradeDocumentTree = scope.upgradeDocumentTree; - var upgradeAll = scope.upgradeAll; - var upgradeWithDefinition = scope.upgradeWithDefinition; - var implementPrototype = scope.implementPrototype; - var useNative = scope.useNative; - function register(name, options) { - var definition = options || {}; - if (!name) { - throw new Error("document.registerElement: first argument `name` must not be empty"); - } - if (name.indexOf("-") < 0) { - throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '" + String(name) + "'."); - } - if (isReservedTag(name)) { - throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '" + String(name) + "'. The type name is invalid."); - } - if (getRegisteredDefinition(name)) { - throw new Error("DuplicateDefinitionError: a type with name '" + String(name) + "' is already registered"); - } - if (!definition.prototype) { - definition.prototype = Object.create(HTMLElement.prototype); - } - definition.__name = name.toLowerCase(); - definition.lifecycle = definition.lifecycle || {}; - definition.ancestry = ancestry(definition.extends); - resolveTagName(definition); - resolvePrototypeChain(definition); - overrideAttributeApi(definition.prototype); - registerDefinition(definition.__name, definition); - definition.ctor = generateConstructor(definition); - definition.ctor.prototype = definition.prototype; - definition.prototype.constructor = definition.ctor; - if (scope.ready) { - upgradeDocumentTree(document); - } - return definition.ctor; - } - function overrideAttributeApi(prototype) { - if (prototype.setAttribute._polyfilled) { - return; - } - var setAttribute = prototype.setAttribute; - prototype.setAttribute = function(name, value) { - changeAttribute.call(this, name, value, setAttribute); - }; - var removeAttribute = prototype.removeAttribute; - prototype.removeAttribute = function(name) { - changeAttribute.call(this, name, null, removeAttribute); - }; - prototype.setAttribute._polyfilled = true; - } - function changeAttribute(name, value, operation) { - name = name.toLowerCase(); - var oldValue = this.getAttribute(name); - operation.apply(this, arguments); - var newValue = this.getAttribute(name); - if (this.attributeChangedCallback && newValue !== oldValue) { - this.attributeChangedCallback(name, oldValue, newValue); - } - } - function isReservedTag(name) { - for (var i = 0; i < reservedTagList.length; i++) { - if (name === reservedTagList[i]) { - return true; - } - } - } - var reservedTagList = [ "annotation-xml", "color-profile", "font-face", "font-face-src", "font-face-uri", "font-face-format", "font-face-name", "missing-glyph" ]; - function ancestry(extnds) { - var extendee = getRegisteredDefinition(extnds); - if (extendee) { - return ancestry(extendee.extends).concat([ extendee ]); - } - return []; - } - function resolveTagName(definition) { - var baseTag = definition.extends; - for (var i = 0, a; a = definition.ancestry[i]; i++) { - baseTag = a.is && a.tag; - } - definition.tag = baseTag || definition.__name; - if (baseTag) { - definition.is = definition.__name; - } - } - function resolvePrototypeChain(definition) { - if (!Object.__proto__) { - var nativePrototype = HTMLElement.prototype; - if (definition.is) { - var inst = document.createElement(definition.tag); - nativePrototype = Object.getPrototypeOf(inst); - } - var proto = definition.prototype, ancestor; - var foundPrototype = false; - while (proto) { - if (proto == nativePrototype) { - foundPrototype = true; - } - ancestor = Object.getPrototypeOf(proto); - if (ancestor) { - proto.__proto__ = ancestor; - } - proto = ancestor; - } - if (!foundPrototype) { - console.warn(definition.tag + " prototype not found in prototype chain for " + definition.is); - } - definition.native = nativePrototype; - } - } - function instantiate(definition) { - return upgradeWithDefinition(domCreateElement(definition.tag), definition); - } - var registry = {}; - function getRegisteredDefinition(name) { - if (name) { - return registry[name.toLowerCase()]; - } - } - function registerDefinition(name, definition) { - registry[name] = definition; - } - function generateConstructor(definition) { - return function() { - return instantiate(definition); - }; - } - var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; - function createElementNS(namespace, tag, typeExtension) { - if (namespace === HTML_NAMESPACE) { - return createElement(tag, typeExtension); - } else { - return domCreateElementNS(namespace, tag); - } - } - function createElement(tag, typeExtension) { - if (tag) { - tag = tag.toLowerCase(); - } - if (typeExtension) { - typeExtension = typeExtension.toLowerCase(); - } - var definition = getRegisteredDefinition(typeExtension || tag); - if (definition) { - if (tag == definition.tag && typeExtension == definition.is) { - return new definition.ctor(); - } - if (!typeExtension && !definition.is) { - return new definition.ctor(); - } - } - var element; - if (typeExtension) { - element = createElement(tag); - element.setAttribute("is", typeExtension); - return element; - } - element = domCreateElement(tag); - if (tag.indexOf("-") >= 0) { - implementPrototype(element, HTMLElement); - } - return element; - } - var domCreateElement = document.createElement.bind(document); - var domCreateElementNS = document.createElementNS.bind(document); - var isInstance; - if (!Object.__proto__ && !useNative) { - isInstance = function(obj, ctor) { - if (obj instanceof ctor) { - return true; - } - var p = obj; - while (p) { - if (p === ctor.prototype) { - return true; - } - p = p.__proto__; - } - return false; - }; - } else { - isInstance = function(obj, base) { - return obj instanceof base; - }; - } - function wrapDomMethodToForceUpgrade(obj, methodName) { - var orig = obj[methodName]; - obj[methodName] = function() { - var n = orig.apply(this, arguments); - upgradeAll(n); - return n; - }; - } - wrapDomMethodToForceUpgrade(Node.prototype, "cloneNode"); - wrapDomMethodToForceUpgrade(document, "importNode"); - if (isIE) { - (function() { - var importNode = document.importNode; - document.importNode = function() { - var n = importNode.apply(document, arguments); - if (n.nodeType == n.DOCUMENT_FRAGMENT_NODE) { - var f = document.createDocumentFragment(); - f.appendChild(n); - return f; - } else { - return n; - } - }; - })(); - } - document.registerElement = register; - document.createElement = createElement; - document.createElementNS = createElementNS; - scope.registry = registry; - scope.instanceof = isInstance; - scope.reservedTagList = reservedTagList; - scope.getRegisteredDefinition = getRegisteredDefinition; - document.register = document.registerElement; -}); - -(function(scope) { - var useNative = scope.useNative; - var initializeModules = scope.initializeModules; - var isIE = scope.isIE; - if (useNative) { - var nop = function() {}; - scope.watchShadow = nop; - scope.upgrade = nop; - scope.upgradeAll = nop; - scope.upgradeDocumentTree = nop; - scope.upgradeSubtree = nop; - scope.takeRecords = nop; - scope.instanceof = function(obj, base) { - return obj instanceof base; - }; - } else { - initializeModules(); - } - var upgradeDocumentTree = scope.upgradeDocumentTree; - var upgradeDocument = scope.upgradeDocument; - if (!window.wrap) { - if (window.ShadowDOMPolyfill) { - window.wrap = window.ShadowDOMPolyfill.wrapIfNeeded; - window.unwrap = window.ShadowDOMPolyfill.unwrapIfNeeded; - } else { - window.wrap = window.unwrap = function(node) { - return node; - }; - } - } - if (window.HTMLImports) { - window.HTMLImports.__importsParsingHook = function(elt) { - if (elt.import) { - upgradeDocument(wrap(elt.import)); - } - }; - } - function bootstrap() { - upgradeDocumentTree(window.wrap(document)); - window.CustomElements.ready = true; - var requestAnimationFrame = window.requestAnimationFrame || function(f) { - setTimeout(f, 16); - }; - requestAnimationFrame(function() { - setTimeout(function() { - window.CustomElements.readyTime = Date.now(); - if (window.HTMLImports) { - window.CustomElements.elapsed = window.CustomElements.readyTime - window.HTMLImports.readyTime; - } - document.dispatchEvent(new CustomEvent("WebComponentsReady", { - bubbles: true - })); - }); - }); - } - if (document.readyState === "complete" || scope.flags.eager) { - bootstrap(); - } else if (document.readyState === "interactive" && !window.attachEvent && (!window.HTMLImports || window.HTMLImports.ready)) { - bootstrap(); - } else { - var loadEvent = window.HTMLImports && !window.HTMLImports.ready ? "HTMLImportsLoaded" : "DOMContentLoaded"; - window.addEventListener(loadEvent, bootstrap); - } -})(window.CustomElements); - -(function(scope) { - if (!Function.prototype.bind) { - Function.prototype.bind = function(scope) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - return function() { - var args2 = args.slice(); - args2.push.apply(args2, arguments); - return self.apply(scope, args2); - }; - }; - } -})(window.WebComponents); - -(function(scope) { - var style = document.createElement("style"); - style.textContent = "" + "body {" + "transition: opacity ease-in 0.2s;" + " } \n" + "body[unresolved] {" + "opacity: 0; display: block; overflow: hidden; position: relative;" + " } \n"; - var head = document.querySelector("head"); - head.insertBefore(style, head.firstChild); -})(window.WebComponents); - -(function(scope) { - window.Platform = scope; -})(window.WebComponents); \ No newline at end of file diff --git a/manifest.webapp b/manifest.webapp deleted file mode 100644 index 984ef3a..0000000 --- a/manifest.webapp +++ /dev/null @@ -1,13 +0,0 @@ -{ - "version": "0.1", - "name": "x-tag-core-tests", - "description": "FFOS Test", - "developer": { - "name": "Mozilla", - "url": "http://mozilla.org/" - }, - "launch_path": "test/index.html", - "icons": { - "128": "test/icon-128.png" - } -} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..319f5ea --- /dev/null +++ b/package-lock.json @@ -0,0 +1,5587 @@ +{ + "name": "x-tag", + "version": "2.0.9-alpha", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@webcomponents/custom-elements": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@webcomponents/custom-elements/-/custom-elements-1.0.9.tgz", + "integrity": "sha512-/r5HiDwOXTjucbBYkrTMpzWQAwil9MH7zSEfKH+RWWZv27r4vDiUd2FiBJItyQoPThLPxaf82IO6gCXyJR0ZnQ==" + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "archy": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/archy/-/archy-1.0.0.tgz", + "integrity": "sha1-+cjBN1fMHde8N5rHeyxipcKGjEA=", + "dev": true + }, + "arr-diff": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", + "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", + "dev": true, + "requires": { + "arr-flatten": "^1.0.1" + } + }, + "arr-flatten": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", + "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", + "dev": true + }, + "array-differ": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-1.0.0.tgz", + "integrity": "sha1-7/UuN1gknTO+QCuLuOVkuytdQDE=", + "dev": true + }, + "array-each": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/array-each/-/array-each-1.0.1.tgz", + "integrity": "sha1-p5SvDAWrF1KEbudTofIRoFugxE8=", + "dev": true + }, + "array-slice": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-1.0.0.tgz", + "integrity": "sha1-5zA08A3MH0CHYAj9IP6ud71LfC8=", + "dev": true + }, + "array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=", + "dev": true + }, + "array-unique": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", + "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "beeper": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/beeper/-/beeper-1.1.1.tgz", + "integrity": "sha1-5tXqjF2tABMEpwsiY4RH9pyy+Ak=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.8.tgz", + "integrity": "sha1-wHshHHyVLsH479Uad+8NHTmQopI=", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", + "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", + "dev": true, + "requires": { + "expand-range": "^1.8.1", + "preserve": "^0.2.0", + "repeat-element": "^1.1.2" + } + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + }, + "dependencies": { + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } + } + }, + "clone": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.2.tgz", + "integrity": "sha1-Jgt6meux7f4kdTgXX3gyQ8sZ0Uk=", + "dev": true + }, + "clone-buffer": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/clone-buffer/-/clone-buffer-1.0.0.tgz", + "integrity": "sha1-4+JbIHrE5wGvch4staFnksrD3Fg=", + "dev": true + }, + "clone-stats": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-0.0.1.tgz", + "integrity": "sha1-uI+UqCzzi4eR1YBG6kAprYjKmdE=", + "dev": true + }, + "cloneable-readable": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/cloneable-readable/-/cloneable-readable-1.0.0.tgz", + "integrity": "sha1-pikNQT8hemEjL5XkWP84QYz7ARc=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "process-nextick-args": "^1.0.6", + "through2": "^2.0.1" + } + }, + "commander": { + "version": "2.13.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.13.0.tgz", + "integrity": "sha512-MVuS359B+YzaWqjCL/c+22gfryv+mCBPHAv3zyVI2GN8EY6IRP8VwtasXn8jyyhvvq84R4ImN1OKRtcbIasjYA==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "concat-with-sourcemaps": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/concat-with-sourcemaps/-/concat-with-sourcemaps-1.0.4.tgz", + "integrity": "sha1-9Vs74q60dgGxCi1SWcz7cP0vHdY=", + "dev": true, + "requires": { + "source-map": "^0.5.1" + } + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "dev": true + }, + "dateformat": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-2.0.0.tgz", + "integrity": "sha1-J0Pjq7XD/CRi5SfcpEXgTp9N7hc=", + "dev": true + }, + "defaults": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.3.tgz", + "integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", + "dev": true, + "requires": { + "clone": "^1.0.2" + } + }, + "deprecated": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/deprecated/-/deprecated-0.0.1.tgz", + "integrity": "sha1-+cmvVGSvoeepcUWKi97yqpTVuxk=", + "dev": true + }, + "detect-file": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-0.1.0.tgz", + "integrity": "sha1-STXe39lIhkjgBrASlWbpOGcR6mM=", + "dev": true, + "requires": { + "fs-exists-sync": "^0.1.0" + } + }, + "duplexer2": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.0.2.tgz", + "integrity": "sha1-xhTc9n4vsUmVqRcR5aYX6KYKMds=", + "dev": true, + "requires": { + "readable-stream": "~1.1.9" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "readable-stream": { + "version": "1.1.14", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", + "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + } + } + }, + "end-of-stream": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-0.1.5.tgz", + "integrity": "sha1-jhdyBsPICDfYVjLouTWd/osvbq8=", + "dev": true, + "requires": { + "once": "~1.3.0" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "expand-brackets": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", + "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", + "dev": true, + "requires": { + "is-posix-bracket": "^0.1.0" + } + }, + "expand-range": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-1.8.2.tgz", + "integrity": "sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=", + "dev": true, + "requires": { + "fill-range": "^2.1.0" + } + }, + "expand-tilde": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-1.2.2.tgz", + "integrity": "sha1-C4HrqJflo9MdHD0QL48BRB5VlEk=", + "dev": true, + "requires": { + "os-homedir": "^1.0.1" + } + }, + "extend": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", + "integrity": "sha1-p1Xqe8Gt/MWjHOfnYtuq3F5jZEQ=", + "dev": true + }, + "extglob": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", + "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", + "dev": true, + "requires": { + "is-extglob": "^1.0.0" + } + }, + "fancy-log": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fancy-log/-/fancy-log-1.3.0.tgz", + "integrity": "sha1-Rb4X0Cu5kX1gzP/UmVyZnmyMmUg=", + "dev": true, + "requires": { + "chalk": "^1.1.1", + "time-stamp": "^1.0.0" + } + }, + "filename-regex": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/filename-regex/-/filename-regex-2.0.1.tgz", + "integrity": "sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY=", + "dev": true + }, + "fill-range": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-2.2.3.tgz", + "integrity": "sha1-ULd9/X5Gm8dJJHCWNpn+eoSFpyM=", + "dev": true, + "requires": { + "is-number": "^2.1.0", + "isobject": "^2.0.0", + "randomatic": "^1.1.3", + "repeat-element": "^1.1.2", + "repeat-string": "^1.5.2" + } + }, + "find-index": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/find-index/-/find-index-0.1.1.tgz", + "integrity": "sha1-Z101iyyjiS15Whq0cjL4tuLg3eQ=", + "dev": true + }, + "findup-sync": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-0.4.3.tgz", + "integrity": "sha1-QAQ5Kee8YK3wt/SCfExudaDeyhI=", + "dev": true, + "requires": { + "detect-file": "^0.1.0", + "is-glob": "^2.0.1", + "micromatch": "^2.3.7", + "resolve-dir": "^0.1.0" + } + }, + "fined": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fined/-/fined-1.1.0.tgz", + "integrity": "sha1-s33IRLdqL15wgeiE98CuNE8VNHY=", + "dev": true, + "requires": { + "expand-tilde": "^2.0.2", + "is-plain-object": "^2.0.3", + "object.defaults": "^1.1.0", + "object.pick": "^1.2.0", + "parse-filepath": "^1.0.1" + }, + "dependencies": { + "expand-tilde": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", + "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", + "dev": true, + "requires": { + "homedir-polyfill": "^1.0.1" + } + } + } + }, + "first-chunk-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/first-chunk-stream/-/first-chunk-stream-1.0.0.tgz", + "integrity": "sha1-Wb+1DNkF9g18OUzT2ayqtOatk04=", + "dev": true + }, + "flagged-respawn": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/flagged-respawn/-/flagged-respawn-0.3.2.tgz", + "integrity": "sha1-/xke3c1wiKZ1smEP/8l2vpuAdLU=", + "dev": true + }, + "for-in": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", + "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", + "dev": true + }, + "for-own": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-0.1.5.tgz", + "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=", + "dev": true, + "requires": { + "for-in": "^1.0.1" + } + }, + "fs-exists-sync": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/fs-exists-sync/-/fs-exists-sync-0.1.0.tgz", + "integrity": "sha1-mC1ok6+RjnLQjeyehnP/K1qNat0=", + "dev": true + }, + "gaze": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/gaze/-/gaze-0.5.2.tgz", + "integrity": "sha1-QLcJU30k0dRXZ9takIaJ3+aaxE8=", + "dev": true, + "requires": { + "globule": "~0.1.0" + } + }, + "glob": { + "version": "4.5.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-4.5.3.tgz", + "integrity": "sha1-xstz0yJsHv7wTePFbQEvAzd+4V8=", + "dev": true, + "requires": { + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^2.0.1", + "once": "^1.3.0" + }, + "dependencies": { + "minimatch": { + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.10.tgz", + "integrity": "sha1-jQh8OcazjAAbl/ynzm0OHoCvusc=", + "dev": true, + "requires": { + "brace-expansion": "^1.0.0" + } + } + } + }, + "glob-base": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/glob-base/-/glob-base-0.3.0.tgz", + "integrity": "sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q=", + "dev": true, + "requires": { + "glob-parent": "^2.0.0", + "is-glob": "^2.0.0" + } + }, + "glob-parent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-2.0.0.tgz", + "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", + "dev": true, + "requires": { + "is-glob": "^2.0.0" + } + }, + "glob-stream": { + "version": "3.1.18", + "resolved": "https://registry.npmjs.org/glob-stream/-/glob-stream-3.1.18.tgz", + "integrity": "sha1-kXCl8St5Awb9/lmPMT+PeVT9FDs=", + "dev": true, + "requires": { + "glob": "^4.3.1", + "glob2base": "^0.0.12", + "minimatch": "^2.0.1", + "ordered-read-streams": "^0.1.0", + "through2": "^0.6.1", + "unique-stream": "^1.0.0" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "minimatch": { + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.10.tgz", + "integrity": "sha1-jQh8OcazjAAbl/ynzm0OHoCvusc=", + "dev": true, + "requires": { + "brace-expansion": "^1.0.0" + } + }, + "readable-stream": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", + "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + }, + "through2": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-0.6.5.tgz", + "integrity": "sha1-QaucZ7KdVyCQcUEOHXp6lozTrUg=", + "dev": true, + "requires": { + "readable-stream": ">=1.0.33-1 <1.1.0-0", + "xtend": ">=4.0.0 <4.1.0-0" + } + } + } + }, + "glob-watcher": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/glob-watcher/-/glob-watcher-0.0.6.tgz", + "integrity": "sha1-uVtKjfdLOcgymLDAXJeLTZo7cQs=", + "dev": true, + "requires": { + "gaze": "^0.5.1" + } + }, + "glob2base": { + "version": "0.0.12", + "resolved": "https://registry.npmjs.org/glob2base/-/glob2base-0.0.12.tgz", + "integrity": "sha1-nUGbPijxLoOjYhZKJ3BVkiycDVY=", + "dev": true, + "requires": { + "find-index": "^0.1.1" + } + }, + "global-modules": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-0.2.3.tgz", + "integrity": "sha1-6lo77ULG1s6ZWk+KEmm12uIjgo0=", + "dev": true, + "requires": { + "global-prefix": "^0.1.4", + "is-windows": "^0.2.0" + } + }, + "global-prefix": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-0.1.5.tgz", + "integrity": "sha1-jTvGuNo8qBEqFg2NSW/wRiv+948=", + "dev": true, + "requires": { + "homedir-polyfill": "^1.0.0", + "ini": "^1.3.4", + "is-windows": "^0.2.0", + "which": "^1.2.12" + } + }, + "globule": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/globule/-/globule-0.1.0.tgz", + "integrity": "sha1-2cjt3h2nnRJaFRt5UzuXhnY0auU=", + "dev": true, + "requires": { + "glob": "~3.1.21", + "lodash": "~1.0.1", + "minimatch": "~0.2.11" + }, + "dependencies": { + "glob": { + "version": "3.1.21", + "resolved": "https://registry.npmjs.org/glob/-/glob-3.1.21.tgz", + "integrity": "sha1-0p4KBV3qUTj00H7UDomC6DwgZs0=", + "dev": true, + "requires": { + "graceful-fs": "~1.2.0", + "inherits": "1", + "minimatch": "~0.2.11" + } + }, + "graceful-fs": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-1.2.3.tgz", + "integrity": "sha1-FaSAaldUfLLS2/J/QuiajDRRs2Q=", + "dev": true + }, + "inherits": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-1.0.2.tgz", + "integrity": "sha1-ykMJ2t7mtUzAuNJH6NfHoJdb3Js=", + "dev": true + }, + "lodash": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-1.0.2.tgz", + "integrity": "sha1-j1dWDIO1n8JwvT1WG2kAQ0MOJVE=", + "dev": true + }, + "lru-cache": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.7.3.tgz", + "integrity": "sha1-bUUk6LlV+V1PW1iFHOId1y+06VI=", + "dev": true + }, + "minimatch": { + "version": "0.2.14", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-0.2.14.tgz", + "integrity": "sha1-x054BXT2PG+aCQ6Q775u9TpqdWo=", + "dev": true, + "requires": { + "lru-cache": "2", + "sigmund": "~1.0.0" + } + } + } + }, + "glogg": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/glogg/-/glogg-1.0.0.tgz", + "integrity": "sha1-f+DxmfV6yQbPUS/urY+Q7kooT8U=", + "dev": true, + "requires": { + "sparkles": "^1.0.0" + } + }, + "gulp": { + "version": "3.9.1", + "resolved": "https://registry.npmjs.org/gulp/-/gulp-3.9.1.tgz", + "integrity": "sha1-VxzkWSjdQK9lFPxAEYZgFsE4RbQ=", + "dev": true, + "requires": { + "archy": "^1.0.0", + "chalk": "^1.0.0", + "deprecated": "^0.0.1", + "gulp-util": "^3.0.0", + "interpret": "^1.0.0", + "liftoff": "^2.1.0", + "minimist": "^1.1.0", + "orchestrator": "^0.3.0", + "pretty-hrtime": "^1.0.0", + "semver": "^4.1.0", + "tildify": "^1.0.0", + "v8flags": "^2.0.2", + "vinyl-fs": "^0.3.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + }, + "semver": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-4.3.6.tgz", + "integrity": "sha1-MAvG4OhjdPe6YQaLWx7NV/xlMto=", + "dev": true + } + } + }, + "gulp-concat": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/gulp-concat/-/gulp-concat-2.6.1.tgz", + "integrity": "sha1-Yz0WyV2IUEYorQJmVmPO5aR5M1M=", + "dev": true, + "requires": { + "concat-with-sourcemaps": "^1.0.0", + "through2": "^2.0.0", + "vinyl": "^2.0.0" + }, + "dependencies": { + "clone": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", + "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", + "dev": true + }, + "clone-stats": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-1.0.0.tgz", + "integrity": "sha1-s3gt/4u1R04Yuba/D9/ngvh3doA=", + "dev": true + }, + "replace-ext": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-1.0.0.tgz", + "integrity": "sha1-3mMSg3P8v3w8z6TeWkgMRaZ5WOs=", + "dev": true + }, + "vinyl": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-2.1.0.tgz", + "integrity": "sha1-Ah+cLPlR1rk5lDyJ617lrdT9kkw=", + "dev": true, + "requires": { + "clone": "^2.1.1", + "clone-buffer": "^1.0.0", + "clone-stats": "^1.0.0", + "cloneable-readable": "^1.0.0", + "remove-trailing-separator": "^1.0.1", + "replace-ext": "^1.0.0" + } + } + } + }, + "gulp-uglify-es": { + "version": "0.1.11", + "resolved": "https://registry.npmjs.org/gulp-uglify-es/-/gulp-uglify-es-0.1.11.tgz", + "integrity": "sha512-bDy4hnDU1XRyyH+u0SkHBxXIOc6FCZRpA/3saGEyXUKU6KOzruVkt71JTmBy5M1mzHAsira2BSMxeQmAIXKlkw==", + "dev": true, + "requires": { + "gulp-util": "^3.0.8", + "o-stream": "^0.2.2", + "uglify-es": "^3.2.0", + "vinyl-sourcemaps-apply": "^0.2.1" + } + }, + "gulp-util": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/gulp-util/-/gulp-util-3.0.8.tgz", + "integrity": "sha1-AFTh50RQLifATBh8PsxQXdVLu08=", + "dev": true, + "requires": { + "array-differ": "^1.0.0", + "array-uniq": "^1.0.2", + "beeper": "^1.0.0", + "chalk": "^1.0.0", + "dateformat": "^2.0.0", + "fancy-log": "^1.1.0", + "gulplog": "^1.0.0", + "has-gulplog": "^0.1.0", + "lodash._reescape": "^3.0.0", + "lodash._reevaluate": "^3.0.0", + "lodash._reinterpolate": "^3.0.0", + "lodash.template": "^3.0.0", + "minimist": "^1.1.0", + "multipipe": "^0.1.2", + "object-assign": "^3.0.0", + "replace-ext": "0.0.1", + "through2": "^2.0.0", + "vinyl": "^0.5.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + }, + "object-assign": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz", + "integrity": "sha1-m+3VygiXlJvKR+f/QIBi1Un1h/I=", + "dev": true + } + } + }, + "gulplog": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gulplog/-/gulplog-1.0.0.tgz", + "integrity": "sha1-4oxNRdBey77YGDY86PnFkmIp/+U=", + "dev": true, + "requires": { + "glogg": "^1.0.0" + } + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "has-gulplog": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/has-gulplog/-/has-gulplog-0.1.0.tgz", + "integrity": "sha1-ZBTIKRNpfaUVkDl9r7EvIpZ4Ec4=", + "dev": true, + "requires": { + "sparkles": "^1.0.0" + } + }, + "homedir-polyfill": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.1.tgz", + "integrity": "sha1-TCu8inWJmP7r9e1oWA921GdotLw=", + "dev": true, + "requires": { + "parse-passwd": "^1.0.0" + } + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "ini": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.4.tgz", + "integrity": "sha1-BTfLedr1m1mhpRff9wbIbsA5Fi4=", + "dev": true + }, + "interpret": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.0.3.tgz", + "integrity": "sha1-y8NcYu7uc/Gat7EKgBURQBr8D5A=", + "dev": true + }, + "is-absolute": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/is-absolute/-/is-absolute-0.2.6.tgz", + "integrity": "sha1-IN5p89uULvLYe5wto28XIjWxtes=", + "dev": true, + "requires": { + "is-relative": "^0.2.1", + "is-windows": "^0.2.0" + } + }, + "is-buffer": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.5.tgz", + "integrity": "sha1-Hzsm72E7IUuIy8ojzGwB2Hlh7sw=", + "dev": true + }, + "is-dotfile": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/is-dotfile/-/is-dotfile-1.0.3.tgz", + "integrity": "sha1-pqLzL/0t+wT1yiXs0Pa4PPeYoeE=", + "dev": true + }, + "is-equal-shallow": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz", + "integrity": "sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ=", + "dev": true, + "requires": { + "is-primitive": "^2.0.0" + } + }, + "is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", + "dev": true + }, + "is-extglob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", + "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", + "dev": true + }, + "is-glob": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", + "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", + "dev": true, + "requires": { + "is-extglob": "^1.0.0" + } + }, + "is-number": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-2.1.0.tgz", + "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + } + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + }, + "dependencies": { + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } + } + }, + "is-posix-bracket": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz", + "integrity": "sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q=", + "dev": true + }, + "is-primitive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-primitive/-/is-primitive-2.0.0.tgz", + "integrity": "sha1-IHurkWOEmcB7Kt8kCkGochADRXU=", + "dev": true + }, + "is-relative": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-0.2.1.tgz", + "integrity": "sha1-0n9MfVFtF1+2ENuEu+7yPDvJeqU=", + "dev": true, + "requires": { + "is-unc-path": "^0.1.1" + } + }, + "is-unc-path": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/is-unc-path/-/is-unc-path-0.1.2.tgz", + "integrity": "sha1-arBTpyVzwQJQ/0FqOBTDUXivObk=", + "dev": true, + "requires": { + "unc-path-regex": "^0.1.0" + } + }, + "is-utf8": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", + "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=", + "dev": true + }, + "is-windows": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-0.2.0.tgz", + "integrity": "sha1-3hqm1j6indJIc3tp8f+LgALSEIw=", + "dev": true + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "requires": { + "isarray": "1.0.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + }, + "liftoff": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/liftoff/-/liftoff-2.3.0.tgz", + "integrity": "sha1-qY8v9nGD2Lp8+soQVIvX/wVQs4U=", + "dev": true, + "requires": { + "extend": "^3.0.0", + "findup-sync": "^0.4.2", + "fined": "^1.0.1", + "flagged-respawn": "^0.3.2", + "lodash.isplainobject": "^4.0.4", + "lodash.isstring": "^4.0.1", + "lodash.mapvalues": "^4.4.0", + "rechoir": "^0.6.2", + "resolve": "^1.1.7" + } + }, + "lodash._basecopy": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz", + "integrity": "sha1-jaDmqHbPNEwK2KVIghEd08XHyjY=", + "dev": true + }, + "lodash._basetostring": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/lodash._basetostring/-/lodash._basetostring-3.0.1.tgz", + "integrity": "sha1-0YYdh3+CSlL2aYMtyvPuFVZqB9U=", + "dev": true + }, + "lodash._basevalues": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lodash._basevalues/-/lodash._basevalues-3.0.0.tgz", + "integrity": "sha1-W3dXYoAr3j0yl1A+JjAIIP32Ybc=", + "dev": true + }, + "lodash._getnative": { + "version": "3.9.1", + "resolved": "https://registry.npmjs.org/lodash._getnative/-/lodash._getnative-3.9.1.tgz", + "integrity": "sha1-VwvH3t5G1hzc3mh9ZdPuy6o6r/U=", + "dev": true + }, + "lodash._isiterateecall": { + "version": "3.0.9", + "resolved": "https://registry.npmjs.org/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz", + "integrity": "sha1-UgOte6Ql+uhCRg5pbbnPPmqsBXw=", + "dev": true + }, + "lodash._reescape": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lodash._reescape/-/lodash._reescape-3.0.0.tgz", + "integrity": "sha1-Kx1vXf4HyKNVdT5fJ/rH8c3hYWo=", + "dev": true + }, + "lodash._reevaluate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lodash._reevaluate/-/lodash._reevaluate-3.0.0.tgz", + "integrity": "sha1-WLx0xAZklTrgsSTYBpltrKQx4u0=", + "dev": true + }, + "lodash._reinterpolate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz", + "integrity": "sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=", + "dev": true + }, + "lodash._root": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/lodash._root/-/lodash._root-3.0.1.tgz", + "integrity": "sha1-+6HEUkwZ7ppfgTa0YJ8BfPTe1pI=", + "dev": true + }, + "lodash.escape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/lodash.escape/-/lodash.escape-3.2.0.tgz", + "integrity": "sha1-mV7g3BjBtIzJLv+ucaEKq1tIdpg=", + "dev": true, + "requires": { + "lodash._root": "^3.0.0" + } + }, + "lodash.isarguments": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", + "integrity": "sha1-L1c9hcaiQon/AGY7SRwdM4/zRYo=", + "dev": true + }, + "lodash.isarray": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/lodash.isarray/-/lodash.isarray-3.0.4.tgz", + "integrity": "sha1-eeTriMNqgSKvhvhEqpvNhRtfu1U=", + "dev": true + }, + "lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=", + "dev": true + }, + "lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=", + "dev": true + }, + "lodash.keys": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-3.1.2.tgz", + "integrity": "sha1-TbwEcrFWvlCgsoaFXRvQsMZWCYo=", + "dev": true, + "requires": { + "lodash._getnative": "^3.0.0", + "lodash.isarguments": "^3.0.0", + "lodash.isarray": "^3.0.0" + } + }, + "lodash.mapvalues": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.mapvalues/-/lodash.mapvalues-4.6.0.tgz", + "integrity": "sha1-G6+lAF3p3W9PJmaMMMo3IwzJaJw=", + "dev": true + }, + "lodash.restparam": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/lodash.restparam/-/lodash.restparam-3.6.1.tgz", + "integrity": "sha1-k2pOMJ7zMKdkXtQUWYbIWuWyCAU=", + "dev": true + }, + "lodash.template": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-3.6.2.tgz", + "integrity": "sha1-+M3sxhaaJVvpCYrosMU9N4kx0U8=", + "dev": true, + "requires": { + "lodash._basecopy": "^3.0.0", + "lodash._basetostring": "^3.0.0", + "lodash._basevalues": "^3.0.0", + "lodash._isiterateecall": "^3.0.0", + "lodash._reinterpolate": "^3.0.0", + "lodash.escape": "^3.0.0", + "lodash.keys": "^3.0.0", + "lodash.restparam": "^3.0.0", + "lodash.templatesettings": "^3.0.0" + } + }, + "lodash.templatesettings": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/lodash.templatesettings/-/lodash.templatesettings-3.1.1.tgz", + "integrity": "sha1-+zB4RHU7Zrnxr6VOJix0UwfbqOU=", + "dev": true, + "requires": { + "lodash._reinterpolate": "^3.0.0", + "lodash.escape": "^3.0.0" + } + }, + "map-cache": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", + "dev": true + }, + "micromatch": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", + "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", + "dev": true, + "requires": { + "arr-diff": "^2.0.0", + "array-unique": "^0.2.1", + "braces": "^1.8.2", + "expand-brackets": "^0.1.4", + "extglob": "^0.3.1", + "filename-regex": "^2.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.1", + "kind-of": "^3.0.2", + "normalize-path": "^2.0.1", + "object.omit": "^2.0.0", + "parse-glob": "^3.0.4", + "regex-cache": "^0.4.2" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "multipipe": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/multipipe/-/multipipe-0.1.2.tgz", + "integrity": "sha1-Ko8t33Du1WTf8tV/HhoTfZ8FB4s=", + "dev": true, + "requires": { + "duplexer2": "0.0.2" + } + }, + "natives": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/natives/-/natives-1.1.6.tgz", + "integrity": "sha512-6+TDFewD4yxY14ptjKaS63GVdtKiES1pTPyxn9Jb0rBqPMZ7VcCiooEhPNsr+mqHtMGxa/5c/HhcC4uPEUw/nA==" + }, + "normalize-path": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "dev": true, + "requires": { + "remove-trailing-separator": "^1.0.1" + } + }, + "npm": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/npm/-/npm-5.8.0.tgz", + "integrity": "sha512-DowXzQwtSWDtbAjuWecuEiismR0VdNEYaL3VxNTYTdW6AGkYxfGk9LUZ/rt6etEyiH4IEk95HkJeGfXE5Rz9xQ==", + "requires": { + "JSONStream": "^1.3.2", + "abbrev": "~1.1.1", + "ansi-regex": "~3.0.0", + "ansicolors": "~0.3.2", + "ansistyles": "~0.1.3", + "aproba": "~1.2.0", + "archy": "~1.0.0", + "bin-links": "^1.1.0", + "bluebird": "~3.5.1", + "cacache": "^10.0.4", + "call-limit": "~1.1.0", + "chownr": "~1.0.1", + "cli-table2": "~0.2.0", + "cmd-shim": "~2.0.2", + "columnify": "~1.5.4", + "config-chain": "~1.1.11", + "debuglog": "*", + "detect-indent": "~5.0.0", + "detect-newline": "^2.1.0", + "dezalgo": "~1.0.3", + "editor": "~1.0.0", + "find-npm-prefix": "^1.0.2", + "fs-vacuum": "~1.2.10", + "fs-write-stream-atomic": "~1.0.10", + "gentle-fs": "^2.0.1", + "glob": "~7.1.2", + "graceful-fs": "~4.1.11", + "has-unicode": "~2.0.1", + "hosted-git-info": "^2.6.0", + "iferr": "~0.1.5", + "imurmurhash": "*", + "inflight": "~1.0.6", + "inherits": "~2.0.3", + "ini": "^1.3.5", + "init-package-json": "^1.10.3", + "is-cidr": "~1.0.0", + "json-parse-better-errors": "^1.0.1", + "lazy-property": "~1.0.0", + "libcipm": "^1.6.0", + "libnpx": "^10.0.1", + "lockfile": "~1.0.3", + "lodash._baseindexof": "*", + "lodash._baseuniq": "~4.6.0", + "lodash._bindcallback": "*", + "lodash._cacheindexof": "*", + "lodash._createcache": "*", + "lodash._getnative": "*", + "lodash.clonedeep": "~4.5.0", + "lodash.restparam": "*", + "lodash.union": "~4.6.0", + "lodash.uniq": "~4.5.0", + "lodash.without": "~4.4.0", + "lru-cache": "~4.1.1", + "meant": "~1.0.1", + "mississippi": "^3.0.0", + "mkdirp": "~0.5.1", + "move-concurrently": "^1.0.1", + "nopt": "~4.0.1", + "normalize-package-data": "~2.4.0", + "npm-cache-filename": "~1.0.2", + "npm-install-checks": "~3.0.0", + "npm-lifecycle": "^2.0.1", + "npm-package-arg": "~6.0.0", + "npm-packlist": "~1.1.10", + "npm-profile": "^3.0.1", + "npm-registry-client": "^8.5.1", + "npm-user-validate": "~1.0.0", + "npmlog": "~4.1.2", + "once": "~1.4.0", + "opener": "~1.4.3", + "osenv": "^0.1.5", + "pacote": "^7.6.1", + "path-is-inside": "~1.0.2", + "promise-inflight": "~1.0.1", + "qrcode-terminal": "~0.11.0", + "query-string": "^5.1.0", + "qw": "~1.0.1", + "read": "~1.0.7", + "read-cmd-shim": "~1.0.1", + "read-installed": "~4.0.3", + "read-package-json": "^2.0.13", + "read-package-tree": "~5.1.6", + "readable-stream": "^2.3.5", + "readdir-scoped-modules": "*", + "request": "~2.83.0", + "retry": "~0.10.1", + "rimraf": "~2.6.2", + "safe-buffer": "~5.1.1", + "semver": "^5.5.0", + "sha": "~2.0.1", + "slide": "~1.1.6", + "sorted-object": "~2.0.1", + "sorted-union-stream": "~2.1.3", + "ssri": "^5.2.4", + "strip-ansi": "~4.0.0", + "tar": "^4.4.0", + "text-table": "~0.2.0", + "uid-number": "0.0.6", + "umask": "~1.1.0", + "unique-filename": "~1.1.0", + "unpipe": "~1.0.0", + "update-notifier": "~2.3.0", + "uuid": "^3.2.1", + "validate-npm-package-license": "*", + "validate-npm-package-name": "~3.0.0", + "which": "~1.3.0", + "worker-farm": "^1.5.4", + "wrappy": "~1.0.2", + "write-file-atomic": "^2.3.0" + }, + "dependencies": { + "JSONStream": { + "version": "1.3.2", + "bundled": true, + "requires": { + "jsonparse": "^1.2.0", + "through": ">=2.2.7 <3" + }, + "dependencies": { + "jsonparse": { + "version": "1.3.1", + "bundled": true + }, + "through": { + "version": "2.3.8", + "bundled": true + } + } + }, + "abbrev": { + "version": "1.1.1", + "bundled": true + }, + "ansi-regex": { + "version": "3.0.0", + "bundled": true + }, + "ansicolors": { + "version": "0.3.2", + "bundled": true + }, + "ansistyles": { + "version": "0.1.3", + "bundled": true + }, + "aproba": { + "version": "1.2.0", + "bundled": true + }, + "archy": { + "version": "1.0.0", + "bundled": true + }, + "bin-links": { + "version": "1.1.0", + "bundled": true, + "requires": { + "bluebird": "^3.5.0", + "cmd-shim": "^2.0.2", + "fs-write-stream-atomic": "^1.0.10", + "gentle-fs": "^2.0.0", + "graceful-fs": "^4.1.11", + "slide": "^1.1.6" + } + }, + "bluebird": { + "version": "3.5.1", + "bundled": true + }, + "cacache": { + "version": "10.0.4", + "bundled": true, + "requires": { + "bluebird": "^3.5.1", + "chownr": "^1.0.1", + "glob": "^7.1.2", + "graceful-fs": "^4.1.11", + "lru-cache": "^4.1.1", + "mississippi": "^2.0.0", + "mkdirp": "^0.5.1", + "move-concurrently": "^1.0.1", + "promise-inflight": "^1.0.1", + "rimraf": "^2.6.2", + "ssri": "^5.2.4", + "unique-filename": "^1.1.0", + "y18n": "^4.0.0" + }, + "dependencies": { + "mississippi": { + "version": "2.0.0", + "bundled": true, + "requires": { + "concat-stream": "^1.5.0", + "duplexify": "^3.4.2", + "end-of-stream": "^1.1.0", + "flush-write-stream": "^1.0.0", + "from2": "^2.1.0", + "parallel-transform": "^1.1.0", + "pump": "^2.0.1", + "pumpify": "^1.3.3", + "stream-each": "^1.1.0", + "through2": "^2.0.0" + }, + "dependencies": { + "concat-stream": { + "version": "1.6.1", + "bundled": true, + "requires": { + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + }, + "dependencies": { + "typedarray": { + "version": "0.0.6", + "bundled": true + } + } + }, + "duplexify": { + "version": "3.5.4", + "bundled": true, + "requires": { + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" + }, + "dependencies": { + "stream-shift": { + "version": "1.0.0", + "bundled": true + } + } + }, + "end-of-stream": { + "version": "1.4.1", + "bundled": true, + "requires": { + "once": "^1.4.0" + } + }, + "flush-write-stream": { + "version": "1.0.2", + "bundled": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.4" + } + }, + "from2": { + "version": "2.3.0", + "bundled": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" + } + }, + "parallel-transform": { + "version": "1.1.0", + "bundled": true, + "requires": { + "cyclist": "~0.2.2", + "inherits": "^2.0.3", + "readable-stream": "^2.1.5" + }, + "dependencies": { + "cyclist": { + "version": "0.2.2", + "bundled": true + } + } + }, + "pump": { + "version": "2.0.1", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "pumpify": { + "version": "1.4.0", + "bundled": true, + "requires": { + "duplexify": "^3.5.3", + "inherits": "^2.0.3", + "pump": "^2.0.0" + } + }, + "stream-each": { + "version": "1.2.2", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "stream-shift": "^1.0.0" + }, + "dependencies": { + "stream-shift": { + "version": "1.0.0", + "bundled": true + } + } + }, + "through2": { + "version": "2.0.3", + "bundled": true, + "requires": { + "readable-stream": "^2.1.5", + "xtend": "~4.0.1" + }, + "dependencies": { + "xtend": { + "version": "4.0.1", + "bundled": true + } + } + } + } + }, + "y18n": { + "version": "4.0.0", + "bundled": true + } + } + }, + "call-limit": { + "version": "1.1.0", + "bundled": true + }, + "chownr": { + "version": "1.0.1", + "bundled": true + }, + "cli-table2": { + "version": "0.2.0", + "bundled": true, + "requires": { + "colors": "^1.1.2", + "lodash": "^3.10.1", + "string-width": "^1.0.1" + }, + "dependencies": { + "colors": { + "version": "1.1.2", + "bundled": true, + "optional": true + }, + "lodash": { + "version": "3.10.1", + "bundled": true + }, + "string-width": { + "version": "1.0.2", + "bundled": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + }, + "dependencies": { + "code-point-at": { + "version": "1.1.0", + "bundled": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "bundled": true, + "requires": { + "number-is-nan": "^1.0.0" + }, + "dependencies": { + "number-is-nan": { + "version": "1.0.1", + "bundled": true + } + } + }, + "strip-ansi": { + "version": "3.0.1", + "bundled": true, + "requires": { + "ansi-regex": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "bundled": true + } + } + } + } + } + } + }, + "cmd-shim": { + "version": "2.0.2", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.2", + "mkdirp": "~0.5.0" + } + }, + "columnify": { + "version": "1.5.4", + "bundled": true, + "requires": { + "strip-ansi": "^3.0.0", + "wcwidth": "^1.0.0" + }, + "dependencies": { + "strip-ansi": { + "version": "3.0.1", + "bundled": true, + "requires": { + "ansi-regex": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "bundled": true + } + } + }, + "wcwidth": { + "version": "1.0.1", + "bundled": true, + "requires": { + "defaults": "^1.0.3" + }, + "dependencies": { + "defaults": { + "version": "1.0.3", + "bundled": true, + "requires": { + "clone": "^1.0.2" + }, + "dependencies": { + "clone": { + "version": "1.0.2", + "bundled": true + } + } + } + } + } + } + }, + "config-chain": { + "version": "1.1.11", + "bundled": true, + "requires": { + "ini": "^1.3.4", + "proto-list": "~1.2.1" + }, + "dependencies": { + "proto-list": { + "version": "1.2.4", + "bundled": true + } + } + }, + "debuglog": { + "version": "1.0.1", + "bundled": true + }, + "detect-indent": { + "version": "5.0.0", + "bundled": true + }, + "detect-newline": { + "version": "2.1.0", + "bundled": true + }, + "dezalgo": { + "version": "1.0.3", + "bundled": true, + "requires": { + "asap": "^2.0.0", + "wrappy": "1" + }, + "dependencies": { + "asap": { + "version": "2.0.5", + "bundled": true + } + } + }, + "editor": { + "version": "1.0.0", + "bundled": true + }, + "find-npm-prefix": { + "version": "1.0.2", + "bundled": true + }, + "fs-vacuum": { + "version": "1.2.10", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.2", + "path-is-inside": "^1.0.1", + "rimraf": "^2.5.2" + } + }, + "fs-write-stream-atomic": { + "version": "1.0.10", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.2", + "iferr": "^0.1.5", + "imurmurhash": "^0.1.4", + "readable-stream": "1 || 2" + } + }, + "gentle-fs": { + "version": "2.0.1", + "bundled": true, + "requires": { + "aproba": "^1.1.2", + "fs-vacuum": "^1.2.10", + "graceful-fs": "^4.1.11", + "iferr": "^0.1.5", + "mkdirp": "^0.5.1", + "path-is-inside": "^1.0.2", + "read-cmd-shim": "^1.0.1", + "slide": "^1.1.6" + } + }, + "glob": { + "version": "7.1.2", + "bundled": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "dependencies": { + "fs.realpath": { + "version": "1.0.0", + "bundled": true + }, + "minimatch": { + "version": "3.0.4", + "bundled": true, + "requires": { + "brace-expansion": "^1.1.7" + }, + "dependencies": { + "brace-expansion": { + "version": "1.1.8", + "bundled": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "dependencies": { + "balanced-match": { + "version": "1.0.0", + "bundled": true + }, + "concat-map": { + "version": "0.0.1", + "bundled": true + } + } + } + } + }, + "path-is-absolute": { + "version": "1.0.1", + "bundled": true + } + } + }, + "graceful-fs": { + "version": "4.1.11", + "bundled": true + }, + "has-unicode": { + "version": "2.0.1", + "bundled": true + }, + "hosted-git-info": { + "version": "2.6.0", + "bundled": true + }, + "iferr": { + "version": "0.1.5", + "bundled": true + }, + "imurmurhash": { + "version": "0.1.4", + "bundled": true + }, + "inflight": { + "version": "1.0.6", + "bundled": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "bundled": true + }, + "ini": { + "version": "1.3.5", + "bundled": true + }, + "init-package-json": { + "version": "1.10.3", + "bundled": true, + "requires": { + "glob": "^7.1.1", + "npm-package-arg": "^4.0.0 || ^5.0.0 || ^6.0.0", + "promzard": "^0.3.0", + "read": "~1.0.1", + "read-package-json": "1 || 2", + "semver": "2.x || 3.x || 4 || 5", + "validate-npm-package-license": "^3.0.1", + "validate-npm-package-name": "^3.0.0" + }, + "dependencies": { + "promzard": { + "version": "0.3.0", + "bundled": true, + "requires": { + "read": "1" + } + } + } + }, + "is-cidr": { + "version": "1.0.0", + "bundled": true, + "requires": { + "cidr-regex": "1.0.6" + }, + "dependencies": { + "cidr-regex": { + "version": "1.0.6", + "bundled": true + } + } + }, + "json-parse-better-errors": { + "version": "1.0.1", + "bundled": true + }, + "lazy-property": { + "version": "1.0.0", + "bundled": true + }, + "libcipm": { + "version": "1.6.0", + "bundled": true, + "requires": { + "bin-links": "^1.1.0", + "bluebird": "^3.5.1", + "find-npm-prefix": "^1.0.2", + "graceful-fs": "^4.1.11", + "lock-verify": "^2.0.0", + "npm-lifecycle": "^2.0.0", + "npm-logical-tree": "^1.2.1", + "npm-package-arg": "^6.0.0", + "pacote": "^7.5.1", + "protoduck": "^5.0.0", + "read-package-json": "^2.0.12", + "rimraf": "^2.6.2", + "worker-farm": "^1.5.4" + }, + "dependencies": { + "lock-verify": { + "version": "2.0.0", + "bundled": true, + "requires": { + "npm-package-arg": "^5.1.2", + "semver": "^5.4.1" + }, + "dependencies": { + "npm-package-arg": { + "version": "5.1.2", + "bundled": true, + "requires": { + "hosted-git-info": "^2.4.2", + "osenv": "^0.1.4", + "semver": "^5.1.0", + "validate-npm-package-name": "^3.0.0" + } + } + } + }, + "npm-logical-tree": { + "version": "1.2.1", + "bundled": true + }, + "protoduck": { + "version": "5.0.0", + "bundled": true, + "requires": { + "genfun": "^4.0.1" + }, + "dependencies": { + "genfun": { + "version": "4.0.1", + "bundled": true + } + } + }, + "worker-farm": { + "version": "1.5.4", + "bundled": true, + "requires": { + "errno": "~0.1.7", + "xtend": "~4.0.1" + }, + "dependencies": { + "errno": { + "version": "0.1.7", + "bundled": true, + "requires": { + "prr": "~1.0.1" + }, + "dependencies": { + "prr": { + "version": "1.0.1", + "bundled": true + } + } + }, + "xtend": { + "version": "4.0.1", + "bundled": true + } + } + } + } + }, + "libnpx": { + "version": "10.0.1", + "bundled": true, + "requires": { + "dotenv": "^5.0.1", + "npm-package-arg": "^6.0.0", + "rimraf": "^2.6.2", + "safe-buffer": "^5.1.0", + "update-notifier": "^2.3.0", + "which": "^1.3.0", + "y18n": "^4.0.0", + "yargs": "^11.0.0" + }, + "dependencies": { + "dotenv": { + "version": "5.0.1", + "bundled": true + }, + "y18n": { + "version": "4.0.0", + "bundled": true + }, + "yargs": { + "version": "11.0.0", + "bundled": true, + "requires": { + "cliui": "^4.0.0", + "decamelize": "^1.1.1", + "find-up": "^2.1.0", + "get-caller-file": "^1.0.1", + "os-locale": "^2.0.0", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^2.0.0", + "which-module": "^2.0.0", + "y18n": "^3.2.1", + "yargs-parser": "^9.0.2" + }, + "dependencies": { + "cliui": { + "version": "4.0.0", + "bundled": true, + "requires": { + "string-width": "^2.1.1", + "strip-ansi": "^4.0.0", + "wrap-ansi": "^2.0.0" + }, + "dependencies": { + "wrap-ansi": { + "version": "2.1.0", + "bundled": true, + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1" + }, + "dependencies": { + "string-width": { + "version": "1.0.2", + "bundled": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + }, + "dependencies": { + "code-point-at": { + "version": "1.1.0", + "bundled": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "bundled": true, + "requires": { + "number-is-nan": "^1.0.0" + }, + "dependencies": { + "number-is-nan": { + "version": "1.0.1", + "bundled": true + } + } + } + } + }, + "strip-ansi": { + "version": "3.0.1", + "bundled": true, + "requires": { + "ansi-regex": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "bundled": true + } + } + } + } + } + } + }, + "decamelize": { + "version": "1.2.0", + "bundled": true + }, + "find-up": { + "version": "2.1.0", + "bundled": true, + "requires": { + "locate-path": "^2.0.0" + }, + "dependencies": { + "locate-path": { + "version": "2.0.0", + "bundled": true, + "requires": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + }, + "dependencies": { + "p-locate": { + "version": "2.0.0", + "bundled": true, + "requires": { + "p-limit": "^1.1.0" + }, + "dependencies": { + "p-limit": { + "version": "1.2.0", + "bundled": true, + "requires": { + "p-try": "^1.0.0" + }, + "dependencies": { + "p-try": { + "version": "1.0.0", + "bundled": true + } + } + } + } + }, + "path-exists": { + "version": "3.0.0", + "bundled": true + } + } + } + } + }, + "get-caller-file": { + "version": "1.0.2", + "bundled": true + }, + "os-locale": { + "version": "2.1.0", + "bundled": true, + "requires": { + "execa": "^0.7.0", + "lcid": "^1.0.0", + "mem": "^1.1.0" + }, + "dependencies": { + "execa": { + "version": "0.7.0", + "bundled": true, + "requires": { + "cross-spawn": "^5.0.1", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + }, + "dependencies": { + "cross-spawn": { + "version": "5.1.0", + "bundled": true, + "requires": { + "lru-cache": "^4.0.1", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + }, + "dependencies": { + "shebang-command": { + "version": "1.2.0", + "bundled": true, + "requires": { + "shebang-regex": "^1.0.0" + }, + "dependencies": { + "shebang-regex": { + "version": "1.0.0", + "bundled": true + } + } + } + } + }, + "get-stream": { + "version": "3.0.0", + "bundled": true + }, + "is-stream": { + "version": "1.1.0", + "bundled": true + }, + "npm-run-path": { + "version": "2.0.2", + "bundled": true, + "requires": { + "path-key": "^2.0.0" + }, + "dependencies": { + "path-key": { + "version": "2.0.1", + "bundled": true + } + } + }, + "p-finally": { + "version": "1.0.0", + "bundled": true + }, + "signal-exit": { + "version": "3.0.2", + "bundled": true + }, + "strip-eof": { + "version": "1.0.0", + "bundled": true + } + } + }, + "lcid": { + "version": "1.0.0", + "bundled": true, + "requires": { + "invert-kv": "^1.0.0" + }, + "dependencies": { + "invert-kv": { + "version": "1.0.0", + "bundled": true + } + } + }, + "mem": { + "version": "1.1.0", + "bundled": true, + "requires": { + "mimic-fn": "^1.0.0" + }, + "dependencies": { + "mimic-fn": { + "version": "1.2.0", + "bundled": true + } + } + } + } + }, + "require-directory": { + "version": "2.1.1", + "bundled": true + }, + "require-main-filename": { + "version": "1.0.1", + "bundled": true + }, + "set-blocking": { + "version": "2.0.0", + "bundled": true + }, + "string-width": { + "version": "2.1.1", + "bundled": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + }, + "dependencies": { + "is-fullwidth-code-point": { + "version": "2.0.0", + "bundled": true + } + } + }, + "which-module": { + "version": "2.0.0", + "bundled": true + }, + "y18n": { + "version": "3.2.1", + "bundled": true + }, + "yargs-parser": { + "version": "9.0.2", + "bundled": true, + "requires": { + "camelcase": "^4.1.0" + }, + "dependencies": { + "camelcase": { + "version": "4.1.0", + "bundled": true + } + } + } + } + } + } + }, + "lockfile": { + "version": "1.0.3", + "bundled": true + }, + "lodash._baseindexof": { + "version": "3.1.0", + "bundled": true + }, + "lodash._baseuniq": { + "version": "4.6.0", + "bundled": true, + "requires": { + "lodash._createset": "~4.0.0", + "lodash._root": "~3.0.0" + }, + "dependencies": { + "lodash._createset": { + "version": "4.0.3", + "bundled": true + }, + "lodash._root": { + "version": "3.0.1", + "bundled": true + } + } + }, + "lodash._bindcallback": { + "version": "3.0.1", + "bundled": true + }, + "lodash._cacheindexof": { + "version": "3.0.2", + "bundled": true + }, + "lodash._createcache": { + "version": "3.1.2", + "bundled": true, + "requires": { + "lodash._getnative": "^3.0.0" + } + }, + "lodash._getnative": { + "version": "3.9.1", + "bundled": true + }, + "lodash.clonedeep": { + "version": "4.5.0", + "bundled": true + }, + "lodash.restparam": { + "version": "3.6.1", + "bundled": true + }, + "lodash.union": { + "version": "4.6.0", + "bundled": true + }, + "lodash.uniq": { + "version": "4.5.0", + "bundled": true + }, + "lodash.without": { + "version": "4.4.0", + "bundled": true + }, + "lru-cache": { + "version": "4.1.1", + "bundled": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + }, + "dependencies": { + "pseudomap": { + "version": "1.0.2", + "bundled": true + }, + "yallist": { + "version": "2.1.2", + "bundled": true + } + } + }, + "meant": { + "version": "1.0.1", + "bundled": true + }, + "mississippi": { + "version": "3.0.0", + "bundled": true, + "requires": { + "concat-stream": "^1.5.0", + "duplexify": "^3.4.2", + "end-of-stream": "^1.1.0", + "flush-write-stream": "^1.0.0", + "from2": "^2.1.0", + "parallel-transform": "^1.1.0", + "pump": "^3.0.0", + "pumpify": "^1.3.3", + "stream-each": "^1.1.0", + "through2": "^2.0.0" + }, + "dependencies": { + "concat-stream": { + "version": "1.6.1", + "bundled": true, + "requires": { + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + }, + "dependencies": { + "typedarray": { + "version": "0.0.6", + "bundled": true + } + } + }, + "duplexify": { + "version": "3.5.4", + "bundled": true, + "requires": { + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" + }, + "dependencies": { + "stream-shift": { + "version": "1.0.0", + "bundled": true + } + } + }, + "end-of-stream": { + "version": "1.4.1", + "bundled": true, + "requires": { + "once": "^1.4.0" + } + }, + "flush-write-stream": { + "version": "1.0.2", + "bundled": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.4" + } + }, + "from2": { + "version": "2.3.0", + "bundled": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" + } + }, + "parallel-transform": { + "version": "1.1.0", + "bundled": true, + "requires": { + "cyclist": "~0.2.2", + "inherits": "^2.0.3", + "readable-stream": "^2.1.5" + }, + "dependencies": { + "cyclist": { + "version": "0.2.2", + "bundled": true + } + } + }, + "pump": { + "version": "3.0.0", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "pumpify": { + "version": "1.4.0", + "bundled": true, + "requires": { + "duplexify": "^3.5.3", + "inherits": "^2.0.3", + "pump": "^2.0.0" + }, + "dependencies": { + "pump": { + "version": "2.0.1", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + } + } + }, + "stream-each": { + "version": "1.2.2", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "stream-shift": "^1.0.0" + }, + "dependencies": { + "stream-shift": { + "version": "1.0.0", + "bundled": true + } + } + }, + "through2": { + "version": "2.0.3", + "bundled": true, + "requires": { + "readable-stream": "^2.1.5", + "xtend": "~4.0.1" + }, + "dependencies": { + "xtend": { + "version": "4.0.1", + "bundled": true + } + } + } + } + }, + "mkdirp": { + "version": "0.5.1", + "bundled": true, + "requires": { + "minimist": "0.0.8" + }, + "dependencies": { + "minimist": { + "version": "0.0.8", + "bundled": true + } + } + }, + "move-concurrently": { + "version": "1.0.1", + "bundled": true, + "requires": { + "aproba": "^1.1.1", + "copy-concurrently": "^1.0.0", + "fs-write-stream-atomic": "^1.0.8", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.3" + }, + "dependencies": { + "copy-concurrently": { + "version": "1.0.5", + "bundled": true, + "requires": { + "aproba": "^1.1.1", + "fs-write-stream-atomic": "^1.0.8", + "iferr": "^0.1.5", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.0" + } + }, + "run-queue": { + "version": "1.0.3", + "bundled": true, + "requires": { + "aproba": "^1.1.1" + } + } + } + }, + "nopt": { + "version": "4.0.1", + "bundled": true, + "requires": { + "abbrev": "1", + "osenv": "^0.1.4" + } + }, + "normalize-package-data": { + "version": "2.4.0", + "bundled": true, + "requires": { + "hosted-git-info": "^2.1.4", + "is-builtin-module": "^1.0.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + }, + "dependencies": { + "is-builtin-module": { + "version": "1.0.0", + "bundled": true, + "requires": { + "builtin-modules": "^1.0.0" + }, + "dependencies": { + "builtin-modules": { + "version": "1.1.1", + "bundled": true + } + } + } + } + }, + "npm-cache-filename": { + "version": "1.0.2", + "bundled": true + }, + "npm-install-checks": { + "version": "3.0.0", + "bundled": true, + "requires": { + "semver": "^2.3.0 || 3.x || 4 || 5" + } + }, + "npm-lifecycle": { + "version": "2.0.1", + "bundled": true, + "requires": { + "byline": "^5.0.0", + "graceful-fs": "^4.1.11", + "node-gyp": "^3.6.2", + "resolve-from": "^4.0.0", + "slide": "^1.1.6", + "uid-number": "0.0.6", + "umask": "^1.1.0", + "which": "^1.3.0" + }, + "dependencies": { + "byline": { + "version": "5.0.0", + "bundled": true + }, + "node-gyp": { + "version": "3.6.2", + "bundled": true, + "requires": { + "fstream": "^1.0.0", + "glob": "^7.0.3", + "graceful-fs": "^4.1.2", + "minimatch": "^3.0.2", + "mkdirp": "^0.5.0", + "nopt": "2 || 3", + "npmlog": "0 || 1 || 2 || 3 || 4", + "osenv": "0", + "request": "2", + "rimraf": "2", + "semver": "~5.3.0", + "tar": "^2.0.0", + "which": "1" + }, + "dependencies": { + "fstream": { + "version": "1.0.11", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.2", + "inherits": "~2.0.0", + "mkdirp": ">=0.5 0", + "rimraf": "2" + } + }, + "minimatch": { + "version": "3.0.4", + "bundled": true, + "requires": { + "brace-expansion": "^1.1.7" + }, + "dependencies": { + "brace-expansion": { + "version": "1.1.11", + "bundled": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "dependencies": { + "balanced-match": { + "version": "1.0.0", + "bundled": true + }, + "concat-map": { + "version": "0.0.1", + "bundled": true + } + } + } + } + }, + "nopt": { + "version": "3.0.6", + "bundled": true, + "requires": { + "abbrev": "1" + } + }, + "semver": { + "version": "5.3.0", + "bundled": true + }, + "tar": { + "version": "2.2.1", + "bundled": true, + "requires": { + "block-stream": "*", + "fstream": "^1.0.2", + "inherits": "2" + }, + "dependencies": { + "block-stream": { + "version": "0.0.9", + "bundled": true, + "requires": { + "inherits": "~2.0.0" + } + } + } + } + } + }, + "resolve-from": { + "version": "4.0.0", + "bundled": true + } + } + }, + "npm-package-arg": { + "version": "6.0.0", + "bundled": true, + "requires": { + "hosted-git-info": "^2.5.0", + "osenv": "^0.1.4", + "semver": "^5.4.1", + "validate-npm-package-name": "^3.0.0" + } + }, + "npm-packlist": { + "version": "1.1.10", + "bundled": true, + "requires": { + "ignore-walk": "^3.0.1", + "npm-bundled": "^1.0.1" + }, + "dependencies": { + "ignore-walk": { + "version": "3.0.1", + "bundled": true, + "requires": { + "minimatch": "^3.0.4" + }, + "dependencies": { + "minimatch": { + "version": "3.0.4", + "bundled": true, + "requires": { + "brace-expansion": "^1.1.7" + }, + "dependencies": { + "brace-expansion": { + "version": "1.1.8", + "bundled": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "dependencies": { + "balanced-match": { + "version": "1.0.0", + "bundled": true + }, + "concat-map": { + "version": "0.0.1", + "bundled": true + } + } + } + } + } + } + }, + "npm-bundled": { + "version": "1.0.3", + "bundled": true + } + } + }, + "npm-profile": { + "version": "3.0.1", + "bundled": true, + "requires": { + "aproba": "^1.1.2", + "make-fetch-happen": "^2.5.0" + }, + "dependencies": { + "make-fetch-happen": { + "version": "2.6.0", + "bundled": true, + "requires": { + "agentkeepalive": "^3.3.0", + "cacache": "^10.0.0", + "http-cache-semantics": "^3.8.0", + "http-proxy-agent": "^2.0.0", + "https-proxy-agent": "^2.1.0", + "lru-cache": "^4.1.1", + "mississippi": "^1.2.0", + "node-fetch-npm": "^2.0.2", + "promise-retry": "^1.1.1", + "socks-proxy-agent": "^3.0.1", + "ssri": "^5.0.0" + }, + "dependencies": { + "agentkeepalive": { + "version": "3.3.0", + "bundled": true, + "requires": { + "humanize-ms": "^1.2.1" + }, + "dependencies": { + "humanize-ms": { + "version": "1.2.1", + "bundled": true, + "requires": { + "ms": "^2.0.0" + }, + "dependencies": { + "ms": { + "version": "2.1.1", + "bundled": true + } + } + } + } + }, + "http-cache-semantics": { + "version": "3.8.1", + "bundled": true + }, + "http-proxy-agent": { + "version": "2.0.0", + "bundled": true, + "requires": { + "agent-base": "4", + "debug": "2" + }, + "dependencies": { + "agent-base": { + "version": "4.2.0", + "bundled": true, + "requires": { + "es6-promisify": "^5.0.0" + }, + "dependencies": { + "es6-promisify": { + "version": "5.0.0", + "bundled": true, + "requires": { + "es6-promise": "^4.0.3" + }, + "dependencies": { + "es6-promise": { + "version": "4.2.4", + "bundled": true + } + } + } + } + }, + "debug": { + "version": "2.6.9", + "bundled": true, + "requires": { + "ms": "2.0.0" + }, + "dependencies": { + "ms": { + "version": "2.0.0", + "bundled": true + } + } + } + } + }, + "https-proxy-agent": { + "version": "2.1.1", + "bundled": true, + "requires": { + "agent-base": "^4.1.0", + "debug": "^3.1.0" + }, + "dependencies": { + "agent-base": { + "version": "4.2.0", + "bundled": true, + "requires": { + "es6-promisify": "^5.0.0" + }, + "dependencies": { + "es6-promisify": { + "version": "5.0.0", + "bundled": true, + "requires": { + "es6-promise": "^4.0.3" + }, + "dependencies": { + "es6-promise": { + "version": "4.2.4", + "bundled": true + } + } + } + } + }, + "debug": { + "version": "3.1.0", + "bundled": true, + "requires": { + "ms": "2.0.0" + }, + "dependencies": { + "ms": { + "version": "2.0.0", + "bundled": true + } + } + } + } + }, + "mississippi": { + "version": "1.3.1", + "bundled": true, + "requires": { + "concat-stream": "^1.5.0", + "duplexify": "^3.4.2", + "end-of-stream": "^1.1.0", + "flush-write-stream": "^1.0.0", + "from2": "^2.1.0", + "parallel-transform": "^1.1.0", + "pump": "^1.0.0", + "pumpify": "^1.3.3", + "stream-each": "^1.1.0", + "through2": "^2.0.0" + }, + "dependencies": { + "concat-stream": { + "version": "1.6.0", + "bundled": true, + "requires": { + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + }, + "dependencies": { + "typedarray": { + "version": "0.0.6", + "bundled": true + } + } + }, + "duplexify": { + "version": "3.5.3", + "bundled": true, + "requires": { + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" + }, + "dependencies": { + "stream-shift": { + "version": "1.0.0", + "bundled": true + } + } + }, + "end-of-stream": { + "version": "1.4.1", + "bundled": true, + "requires": { + "once": "^1.4.0" + } + }, + "flush-write-stream": { + "version": "1.0.2", + "bundled": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.4" + } + }, + "from2": { + "version": "2.3.0", + "bundled": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" + } + }, + "parallel-transform": { + "version": "1.1.0", + "bundled": true, + "requires": { + "cyclist": "~0.2.2", + "inherits": "^2.0.3", + "readable-stream": "^2.1.5" + }, + "dependencies": { + "cyclist": { + "version": "0.2.2", + "bundled": true + } + } + }, + "pump": { + "version": "1.0.3", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "pumpify": { + "version": "1.4.0", + "bundled": true, + "requires": { + "duplexify": "^3.5.3", + "inherits": "^2.0.3", + "pump": "^2.0.0" + }, + "dependencies": { + "pump": { + "version": "2.0.1", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + } + } + }, + "stream-each": { + "version": "1.2.2", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "stream-shift": "^1.0.0" + }, + "dependencies": { + "stream-shift": { + "version": "1.0.0", + "bundled": true + } + } + }, + "through2": { + "version": "2.0.3", + "bundled": true, + "requires": { + "readable-stream": "^2.1.5", + "xtend": "~4.0.1" + }, + "dependencies": { + "xtend": { + "version": "4.0.1", + "bundled": true + } + } + } + } + }, + "node-fetch-npm": { + "version": "2.0.2", + "bundled": true, + "requires": { + "encoding": "^0.1.11", + "json-parse-better-errors": "^1.0.0", + "safe-buffer": "^5.1.1" + }, + "dependencies": { + "encoding": { + "version": "0.1.12", + "bundled": true, + "requires": { + "iconv-lite": "~0.4.13" + }, + "dependencies": { + "iconv-lite": { + "version": "0.4.19", + "bundled": true + } + } + }, + "json-parse-better-errors": { + "version": "1.0.1", + "bundled": true + } + } + }, + "promise-retry": { + "version": "1.1.1", + "bundled": true, + "requires": { + "err-code": "^1.0.0", + "retry": "^0.10.0" + }, + "dependencies": { + "err-code": { + "version": "1.1.2", + "bundled": true + } + } + }, + "socks-proxy-agent": { + "version": "3.0.1", + "bundled": true, + "requires": { + "agent-base": "^4.1.0", + "socks": "^1.1.10" + }, + "dependencies": { + "agent-base": { + "version": "4.2.0", + "bundled": true, + "requires": { + "es6-promisify": "^5.0.0" + }, + "dependencies": { + "es6-promisify": { + "version": "5.0.0", + "bundled": true, + "requires": { + "es6-promise": "^4.0.3" + }, + "dependencies": { + "es6-promise": { + "version": "4.2.4", + "bundled": true + } + } + } + } + }, + "socks": { + "version": "1.1.10", + "bundled": true, + "requires": { + "ip": "^1.1.4", + "smart-buffer": "^1.0.13" + }, + "dependencies": { + "ip": { + "version": "1.1.5", + "bundled": true + }, + "smart-buffer": { + "version": "1.1.15", + "bundled": true + } + } + } + } + } + } + } + } + }, + "npm-registry-client": { + "version": "8.5.1", + "bundled": true, + "requires": { + "concat-stream": "^1.5.2", + "graceful-fs": "^4.1.6", + "normalize-package-data": "~1.0.1 || ^2.0.0", + "npm-package-arg": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0", + "npmlog": "2 || ^3.1.0 || ^4.0.0", + "once": "^1.3.3", + "request": "^2.74.0", + "retry": "^0.10.0", + "safe-buffer": "^5.1.1", + "semver": "2 >=2.2.1 || 3.x || 4 || 5", + "slide": "^1.1.3", + "ssri": "^5.2.4" + }, + "dependencies": { + "concat-stream": { + "version": "1.6.1", + "bundled": true, + "requires": { + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + }, + "dependencies": { + "typedarray": { + "version": "0.0.6", + "bundled": true + } + } + } + } + }, + "npm-user-validate": { + "version": "1.0.0", + "bundled": true + }, + "npmlog": { + "version": "4.1.2", + "bundled": true, + "requires": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + }, + "dependencies": { + "are-we-there-yet": { + "version": "1.1.4", + "bundled": true, + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" + }, + "dependencies": { + "delegates": { + "version": "1.0.0", + "bundled": true + } + } + }, + "console-control-strings": { + "version": "1.1.0", + "bundled": true + }, + "gauge": { + "version": "2.7.4", + "bundled": true, + "requires": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + }, + "dependencies": { + "object-assign": { + "version": "4.1.1", + "bundled": true + }, + "signal-exit": { + "version": "3.0.2", + "bundled": true + }, + "string-width": { + "version": "1.0.2", + "bundled": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + }, + "dependencies": { + "code-point-at": { + "version": "1.1.0", + "bundled": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "bundled": true, + "requires": { + "number-is-nan": "^1.0.0" + }, + "dependencies": { + "number-is-nan": { + "version": "1.0.1", + "bundled": true + } + } + } + } + }, + "strip-ansi": { + "version": "3.0.1", + "bundled": true, + "requires": { + "ansi-regex": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "bundled": true + } + } + }, + "wide-align": { + "version": "1.1.2", + "bundled": true, + "requires": { + "string-width": "^1.0.2" + } + } + } + }, + "set-blocking": { + "version": "2.0.0", + "bundled": true + } + } + }, + "once": { + "version": "1.4.0", + "bundled": true, + "requires": { + "wrappy": "1" + } + }, + "opener": { + "version": "1.4.3", + "bundled": true + }, + "osenv": { + "version": "0.1.5", + "bundled": true, + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + }, + "dependencies": { + "os-homedir": { + "version": "1.0.2", + "bundled": true + }, + "os-tmpdir": { + "version": "1.0.2", + "bundled": true + } + } + }, + "pacote": { + "version": "7.6.1", + "bundled": true, + "requires": { + "bluebird": "^3.5.1", + "cacache": "^10.0.4", + "get-stream": "^3.0.0", + "glob": "^7.1.2", + "lru-cache": "^4.1.1", + "make-fetch-happen": "^2.6.0", + "minimatch": "^3.0.4", + "mississippi": "^3.0.0", + "mkdirp": "^0.5.1", + "normalize-package-data": "^2.4.0", + "npm-package-arg": "^6.0.0", + "npm-packlist": "^1.1.10", + "npm-pick-manifest": "^2.1.0", + "osenv": "^0.1.5", + "promise-inflight": "^1.0.1", + "promise-retry": "^1.1.1", + "protoduck": "^5.0.0", + "rimraf": "^2.6.2", + "safe-buffer": "^5.1.1", + "semver": "^5.5.0", + "ssri": "^5.2.4", + "tar": "^4.4.0", + "unique-filename": "^1.1.0", + "which": "^1.3.0" + }, + "dependencies": { + "get-stream": { + "version": "3.0.0", + "bundled": true + }, + "make-fetch-happen": { + "version": "2.6.0", + "bundled": true, + "requires": { + "agentkeepalive": "^3.3.0", + "cacache": "^10.0.0", + "http-cache-semantics": "^3.8.0", + "http-proxy-agent": "^2.0.0", + "https-proxy-agent": "^2.1.0", + "lru-cache": "^4.1.1", + "mississippi": "^1.2.0", + "node-fetch-npm": "^2.0.2", + "promise-retry": "^1.1.1", + "socks-proxy-agent": "^3.0.1", + "ssri": "^5.0.0" + }, + "dependencies": { + "agentkeepalive": { + "version": "3.4.0", + "bundled": true, + "requires": { + "humanize-ms": "^1.2.1" + }, + "dependencies": { + "humanize-ms": { + "version": "1.2.1", + "bundled": true, + "requires": { + "ms": "^2.0.0" + }, + "dependencies": { + "ms": { + "version": "2.1.1", + "bundled": true + } + } + } + } + }, + "http-cache-semantics": { + "version": "3.8.1", + "bundled": true + }, + "http-proxy-agent": { + "version": "2.1.0", + "bundled": true, + "requires": { + "agent-base": "4", + "debug": "3.1.0" + }, + "dependencies": { + "agent-base": { + "version": "4.2.0", + "bundled": true, + "requires": { + "es6-promisify": "^5.0.0" + }, + "dependencies": { + "es6-promisify": { + "version": "5.0.0", + "bundled": true, + "requires": { + "es6-promise": "^4.0.3" + }, + "dependencies": { + "es6-promise": { + "version": "4.2.4", + "bundled": true + } + } + } + } + }, + "debug": { + "version": "3.1.0", + "bundled": true, + "requires": { + "ms": "2.0.0" + }, + "dependencies": { + "ms": { + "version": "2.0.0", + "bundled": true + } + } + } + } + }, + "https-proxy-agent": { + "version": "2.2.0", + "bundled": true, + "requires": { + "agent-base": "^4.1.0", + "debug": "^3.1.0" + }, + "dependencies": { + "agent-base": { + "version": "4.2.0", + "bundled": true, + "requires": { + "es6-promisify": "^5.0.0" + }, + "dependencies": { + "es6-promisify": { + "version": "5.0.0", + "bundled": true, + "requires": { + "es6-promise": "^4.0.3" + }, + "dependencies": { + "es6-promise": { + "version": "4.2.4", + "bundled": true + } + } + } + } + }, + "debug": { + "version": "3.1.0", + "bundled": true, + "requires": { + "ms": "2.0.0" + }, + "dependencies": { + "ms": { + "version": "2.0.0", + "bundled": true + } + } + } + } + }, + "mississippi": { + "version": "1.3.1", + "bundled": true, + "requires": { + "concat-stream": "^1.5.0", + "duplexify": "^3.4.2", + "end-of-stream": "^1.1.0", + "flush-write-stream": "^1.0.0", + "from2": "^2.1.0", + "parallel-transform": "^1.1.0", + "pump": "^1.0.0", + "pumpify": "^1.3.3", + "stream-each": "^1.1.0", + "through2": "^2.0.0" + }, + "dependencies": { + "concat-stream": { + "version": "1.6.1", + "bundled": true, + "requires": { + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + }, + "dependencies": { + "typedarray": { + "version": "0.0.6", + "bundled": true + } + } + }, + "duplexify": { + "version": "3.5.4", + "bundled": true, + "requires": { + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" + }, + "dependencies": { + "stream-shift": { + "version": "1.0.0", + "bundled": true + } + } + }, + "end-of-stream": { + "version": "1.4.1", + "bundled": true, + "requires": { + "once": "^1.4.0" + } + }, + "flush-write-stream": { + "version": "1.0.2", + "bundled": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.4" + } + }, + "from2": { + "version": "2.3.0", + "bundled": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" + } + }, + "parallel-transform": { + "version": "1.1.0", + "bundled": true, + "requires": { + "cyclist": "~0.2.2", + "inherits": "^2.0.3", + "readable-stream": "^2.1.5" + }, + "dependencies": { + "cyclist": { + "version": "0.2.2", + "bundled": true + } + } + }, + "pump": { + "version": "1.0.3", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "pumpify": { + "version": "1.4.0", + "bundled": true, + "requires": { + "duplexify": "^3.5.3", + "inherits": "^2.0.3", + "pump": "^2.0.0" + }, + "dependencies": { + "pump": { + "version": "2.0.1", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + } + } + }, + "stream-each": { + "version": "1.2.2", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "stream-shift": "^1.0.0" + }, + "dependencies": { + "stream-shift": { + "version": "1.0.0", + "bundled": true + } + } + }, + "through2": { + "version": "2.0.3", + "bundled": true, + "requires": { + "readable-stream": "^2.1.5", + "xtend": "~4.0.1" + }, + "dependencies": { + "xtend": { + "version": "4.0.1", + "bundled": true + } + } + } + } + }, + "node-fetch-npm": { + "version": "2.0.2", + "bundled": true, + "requires": { + "encoding": "^0.1.11", + "json-parse-better-errors": "^1.0.0", + "safe-buffer": "^5.1.1" + }, + "dependencies": { + "encoding": { + "version": "0.1.12", + "bundled": true, + "requires": { + "iconv-lite": "~0.4.13" + }, + "dependencies": { + "iconv-lite": { + "version": "0.4.19", + "bundled": true + } + } + }, + "json-parse-better-errors": { + "version": "1.0.1", + "bundled": true + } + } + }, + "socks-proxy-agent": { + "version": "3.0.1", + "bundled": true, + "requires": { + "agent-base": "^4.1.0", + "socks": "^1.1.10" + }, + "dependencies": { + "agent-base": { + "version": "4.2.0", + "bundled": true, + "requires": { + "es6-promisify": "^5.0.0" + }, + "dependencies": { + "es6-promisify": { + "version": "5.0.0", + "bundled": true, + "requires": { + "es6-promise": "^4.0.3" + }, + "dependencies": { + "es6-promise": { + "version": "4.2.4", + "bundled": true + } + } + } + } + }, + "socks": { + "version": "1.1.10", + "bundled": true, + "requires": { + "ip": "^1.1.4", + "smart-buffer": "^1.0.13" + }, + "dependencies": { + "ip": { + "version": "1.1.5", + "bundled": true + }, + "smart-buffer": { + "version": "1.1.15", + "bundled": true + } + } + } + } + } + } + }, + "minimatch": { + "version": "3.0.4", + "bundled": true, + "requires": { + "brace-expansion": "^1.1.7" + }, + "dependencies": { + "brace-expansion": { + "version": "1.1.11", + "bundled": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "dependencies": { + "balanced-match": { + "version": "1.0.0", + "bundled": true + }, + "concat-map": { + "version": "0.0.1", + "bundled": true + } + } + } + } + }, + "npm-pick-manifest": { + "version": "2.1.0", + "bundled": true, + "requires": { + "npm-package-arg": "^6.0.0", + "semver": "^5.4.1" + } + }, + "promise-retry": { + "version": "1.1.1", + "bundled": true, + "requires": { + "err-code": "^1.0.0", + "retry": "^0.10.0" + }, + "dependencies": { + "err-code": { + "version": "1.1.2", + "bundled": true + } + } + }, + "protoduck": { + "version": "5.0.0", + "bundled": true, + "requires": { + "genfun": "^4.0.1" + }, + "dependencies": { + "genfun": { + "version": "4.0.1", + "bundled": true + } + } + } + } + }, + "path-is-inside": { + "version": "1.0.2", + "bundled": true + }, + "promise-inflight": { + "version": "1.0.1", + "bundled": true + }, + "qrcode-terminal": { + "version": "0.11.0", + "bundled": true + }, + "query-string": { + "version": "5.1.0", + "bundled": true, + "requires": { + "decode-uri-component": "^0.2.0", + "object-assign": "^4.1.0", + "strict-uri-encode": "^1.0.0" + }, + "dependencies": { + "decode-uri-component": { + "version": "0.2.0", + "bundled": true + }, + "object-assign": { + "version": "4.1.1", + "bundled": true + }, + "strict-uri-encode": { + "version": "1.1.0", + "bundled": true + } + } + }, + "qw": { + "version": "1.0.1", + "bundled": true + }, + "read": { + "version": "1.0.7", + "bundled": true, + "requires": { + "mute-stream": "~0.0.4" + }, + "dependencies": { + "mute-stream": { + "version": "0.0.7", + "bundled": true + } + } + }, + "read-cmd-shim": { + "version": "1.0.1", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.2" + } + }, + "read-installed": { + "version": "4.0.3", + "bundled": true, + "requires": { + "debuglog": "^1.0.1", + "graceful-fs": "^4.1.2", + "read-package-json": "^2.0.0", + "readdir-scoped-modules": "^1.0.0", + "semver": "2 || 3 || 4 || 5", + "slide": "~1.1.3", + "util-extend": "^1.0.1" + }, + "dependencies": { + "util-extend": { + "version": "1.0.3", + "bundled": true + } + } + }, + "read-package-json": { + "version": "2.0.13", + "bundled": true, + "requires": { + "glob": "^7.1.1", + "graceful-fs": "^4.1.2", + "json-parse-better-errors": "^1.0.1", + "normalize-package-data": "^2.0.0", + "slash": "^1.0.0" + }, + "dependencies": { + "json-parse-better-errors": { + "version": "1.0.1", + "bundled": true + }, + "slash": { + "version": "1.0.0", + "bundled": true + } + } + }, + "read-package-tree": { + "version": "5.1.6", + "bundled": true, + "requires": { + "debuglog": "^1.0.1", + "dezalgo": "^1.0.0", + "once": "^1.3.0", + "read-package-json": "^2.0.0", + "readdir-scoped-modules": "^1.0.0" + } + }, + "readable-stream": { + "version": "2.3.5", + "bundled": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.0.3", + "util-deprecate": "~1.0.1" + }, + "dependencies": { + "core-util-is": { + "version": "1.0.2", + "bundled": true + }, + "isarray": { + "version": "1.0.0", + "bundled": true + }, + "process-nextick-args": { + "version": "2.0.0", + "bundled": true + }, + "string_decoder": { + "version": "1.0.3", + "bundled": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "util-deprecate": { + "version": "1.0.2", + "bundled": true + } + } + }, + "readdir-scoped-modules": { + "version": "1.0.2", + "bundled": true, + "requires": { + "debuglog": "^1.0.1", + "dezalgo": "^1.0.0", + "graceful-fs": "^4.1.2", + "once": "^1.3.0" + } + }, + "request": { + "version": "2.83.0", + "bundled": true, + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.6.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.5", + "extend": "~3.0.1", + "forever-agent": "~0.6.1", + "form-data": "~2.3.1", + "har-validator": "~5.0.3", + "hawk": "~6.0.2", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.17", + "oauth-sign": "~0.8.2", + "performance-now": "^2.1.0", + "qs": "~6.5.1", + "safe-buffer": "^5.1.1", + "stringstream": "~0.0.5", + "tough-cookie": "~2.3.3", + "tunnel-agent": "^0.6.0", + "uuid": "^3.1.0" + }, + "dependencies": { + "aws-sign2": { + "version": "0.7.0", + "bundled": true + }, + "aws4": { + "version": "1.6.0", + "bundled": true + }, + "caseless": { + "version": "0.12.0", + "bundled": true + }, + "combined-stream": { + "version": "1.0.5", + "bundled": true, + "requires": { + "delayed-stream": "~1.0.0" + }, + "dependencies": { + "delayed-stream": { + "version": "1.0.0", + "bundled": true + } + } + }, + "extend": { + "version": "3.0.1", + "bundled": true + }, + "forever-agent": { + "version": "0.6.1", + "bundled": true + }, + "form-data": { + "version": "2.3.1", + "bundled": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.5", + "mime-types": "^2.1.12" + }, + "dependencies": { + "asynckit": { + "version": "0.4.0", + "bundled": true + } + } + }, + "har-validator": { + "version": "5.0.3", + "bundled": true, + "requires": { + "ajv": "^5.1.0", + "har-schema": "^2.0.0" + }, + "dependencies": { + "ajv": { + "version": "5.2.3", + "bundled": true, + "requires": { + "co": "^4.6.0", + "fast-deep-equal": "^1.0.0", + "json-schema-traverse": "^0.3.0", + "json-stable-stringify": "^1.0.1" + }, + "dependencies": { + "co": { + "version": "4.6.0", + "bundled": true + }, + "fast-deep-equal": { + "version": "1.0.0", + "bundled": true + }, + "json-schema-traverse": { + "version": "0.3.1", + "bundled": true + }, + "json-stable-stringify": { + "version": "1.0.1", + "bundled": true, + "requires": { + "jsonify": "~0.0.0" + }, + "dependencies": { + "jsonify": { + "version": "0.0.0", + "bundled": true + } + } + } + } + }, + "har-schema": { + "version": "2.0.0", + "bundled": true + } + } + }, + "hawk": { + "version": "6.0.2", + "bundled": true, + "requires": { + "boom": "4.x.x", + "cryptiles": "3.x.x", + "hoek": "4.x.x", + "sntp": "2.x.x" + }, + "dependencies": { + "boom": { + "version": "4.3.1", + "bundled": true, + "requires": { + "hoek": "4.x.x" + } + }, + "cryptiles": { + "version": "3.1.2", + "bundled": true, + "requires": { + "boom": "5.x.x" + }, + "dependencies": { + "boom": { + "version": "5.2.0", + "bundled": true, + "requires": { + "hoek": "4.x.x" + } + } + } + }, + "hoek": { + "version": "4.2.0", + "bundled": true + }, + "sntp": { + "version": "2.0.2", + "bundled": true, + "requires": { + "hoek": "4.x.x" + } + } + } + }, + "http-signature": { + "version": "1.2.0", + "bundled": true, + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + }, + "dependencies": { + "assert-plus": { + "version": "1.0.0", + "bundled": true + }, + "jsprim": { + "version": "1.4.1", + "bundled": true, + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.2.3", + "verror": "1.10.0" + }, + "dependencies": { + "extsprintf": { + "version": "1.3.0", + "bundled": true + }, + "json-schema": { + "version": "0.2.3", + "bundled": true + }, + "verror": { + "version": "1.10.0", + "bundled": true, + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + }, + "dependencies": { + "core-util-is": { + "version": "1.0.2", + "bundled": true + } + } + } + } + }, + "sshpk": { + "version": "1.13.1", + "bundled": true, + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "tweetnacl": "~0.14.0" + }, + "dependencies": { + "asn1": { + "version": "0.2.3", + "bundled": true + }, + "bcrypt-pbkdf": { + "version": "1.0.1", + "bundled": true, + "optional": true, + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "dashdash": { + "version": "1.14.1", + "bundled": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "ecc-jsbn": { + "version": "0.1.1", + "bundled": true, + "optional": true, + "requires": { + "jsbn": "~0.1.0" + } + }, + "getpass": { + "version": "0.1.7", + "bundled": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "jsbn": { + "version": "0.1.1", + "bundled": true, + "optional": true + }, + "tweetnacl": { + "version": "0.14.5", + "bundled": true, + "optional": true + } + } + } + } + }, + "is-typedarray": { + "version": "1.0.0", + "bundled": true + }, + "isstream": { + "version": "0.1.2", + "bundled": true + }, + "json-stringify-safe": { + "version": "5.0.1", + "bundled": true + }, + "mime-types": { + "version": "2.1.17", + "bundled": true, + "requires": { + "mime-db": "~1.30.0" + }, + "dependencies": { + "mime-db": { + "version": "1.30.0", + "bundled": true + } + } + }, + "oauth-sign": { + "version": "0.8.2", + "bundled": true + }, + "performance-now": { + "version": "2.1.0", + "bundled": true + }, + "qs": { + "version": "6.5.1", + "bundled": true + }, + "stringstream": { + "version": "0.0.5", + "bundled": true + }, + "tough-cookie": { + "version": "2.3.3", + "bundled": true, + "requires": { + "punycode": "^1.4.1" + }, + "dependencies": { + "punycode": { + "version": "1.4.1", + "bundled": true + } + } + }, + "tunnel-agent": { + "version": "0.6.0", + "bundled": true, + "requires": { + "safe-buffer": "^5.0.1" + } + } + } + }, + "retry": { + "version": "0.10.1", + "bundled": true + }, + "rimraf": { + "version": "2.6.2", + "bundled": true, + "requires": { + "glob": "^7.0.5" + } + }, + "safe-buffer": { + "version": "5.1.1", + "bundled": true + }, + "semver": { + "version": "5.5.0", + "bundled": true + }, + "sha": { + "version": "2.0.1", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.2", + "readable-stream": "^2.0.2" + } + }, + "slide": { + "version": "1.1.6", + "bundled": true + }, + "sorted-object": { + "version": "2.0.1", + "bundled": true + }, + "sorted-union-stream": { + "version": "2.1.3", + "bundled": true, + "requires": { + "from2": "^1.3.0", + "stream-iterate": "^1.1.0" + }, + "dependencies": { + "from2": { + "version": "1.3.0", + "bundled": true, + "requires": { + "inherits": "~2.0.1", + "readable-stream": "~1.1.10" + }, + "dependencies": { + "readable-stream": { + "version": "1.1.14", + "bundled": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + }, + "dependencies": { + "core-util-is": { + "version": "1.0.2", + "bundled": true + }, + "isarray": { + "version": "0.0.1", + "bundled": true + }, + "string_decoder": { + "version": "0.10.31", + "bundled": true + } + } + } + } + }, + "stream-iterate": { + "version": "1.2.0", + "bundled": true, + "requires": { + "readable-stream": "^2.1.5", + "stream-shift": "^1.0.0" + }, + "dependencies": { + "stream-shift": { + "version": "1.0.0", + "bundled": true + } + } + } + } + }, + "ssri": { + "version": "5.2.4", + "bundled": true, + "requires": { + "safe-buffer": "^5.1.1" + } + }, + "strip-ansi": { + "version": "4.0.0", + "bundled": true, + "requires": { + "ansi-regex": "^3.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "bundled": true + } + } + }, + "tar": { + "version": "4.4.0", + "bundled": true, + "requires": { + "chownr": "^1.0.1", + "fs-minipass": "^1.2.3", + "minipass": "^2.2.1", + "minizlib": "^1.1.0", + "mkdirp": "^0.5.0", + "yallist": "^3.0.2" + }, + "dependencies": { + "fs-minipass": { + "version": "1.2.5", + "bundled": true, + "requires": { + "minipass": "^2.2.1" + } + }, + "minipass": { + "version": "2.2.1", + "bundled": true, + "requires": { + "yallist": "^3.0.0" + } + }, + "minizlib": { + "version": "1.1.0", + "bundled": true, + "requires": { + "minipass": "^2.2.1" + } + }, + "yallist": { + "version": "3.0.2", + "bundled": true + } + } + }, + "text-table": { + "version": "0.2.0", + "bundled": true + }, + "uid-number": { + "version": "0.0.6", + "bundled": true + }, + "umask": { + "version": "1.1.0", + "bundled": true + }, + "unique-filename": { + "version": "1.1.0", + "bundled": true, + "requires": { + "unique-slug": "^2.0.0" + }, + "dependencies": { + "unique-slug": { + "version": "2.0.0", + "bundled": true, + "requires": { + "imurmurhash": "^0.1.4" + } + } + } + }, + "unpipe": { + "version": "1.0.0", + "bundled": true + }, + "update-notifier": { + "version": "2.3.0", + "bundled": true, + "requires": { + "boxen": "^1.2.1", + "chalk": "^2.0.1", + "configstore": "^3.0.0", + "import-lazy": "^2.1.0", + "is-installed-globally": "^0.1.0", + "is-npm": "^1.0.0", + "latest-version": "^3.0.0", + "semver-diff": "^2.0.0", + "xdg-basedir": "^3.0.0" + }, + "dependencies": { + "boxen": { + "version": "1.2.1", + "bundled": true, + "requires": { + "ansi-align": "^2.0.0", + "camelcase": "^4.0.0", + "chalk": "^2.0.1", + "cli-boxes": "^1.0.0", + "string-width": "^2.0.0", + "term-size": "^1.2.0", + "widest-line": "^1.0.0" + }, + "dependencies": { + "ansi-align": { + "version": "2.0.0", + "bundled": true, + "requires": { + "string-width": "^2.0.0" + } + }, + "camelcase": { + "version": "4.1.0", + "bundled": true + }, + "cli-boxes": { + "version": "1.0.0", + "bundled": true + }, + "string-width": { + "version": "2.1.1", + "bundled": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + }, + "dependencies": { + "is-fullwidth-code-point": { + "version": "2.0.0", + "bundled": true + } + } + }, + "term-size": { + "version": "1.2.0", + "bundled": true, + "requires": { + "execa": "^0.7.0" + }, + "dependencies": { + "execa": { + "version": "0.7.0", + "bundled": true, + "requires": { + "cross-spawn": "^5.0.1", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + }, + "dependencies": { + "cross-spawn": { + "version": "5.1.0", + "bundled": true, + "requires": { + "lru-cache": "^4.0.1", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + }, + "dependencies": { + "shebang-command": { + "version": "1.2.0", + "bundled": true, + "requires": { + "shebang-regex": "^1.0.0" + }, + "dependencies": { + "shebang-regex": { + "version": "1.0.0", + "bundled": true + } + } + } + } + }, + "get-stream": { + "version": "3.0.0", + "bundled": true + }, + "is-stream": { + "version": "1.1.0", + "bundled": true + }, + "npm-run-path": { + "version": "2.0.2", + "bundled": true, + "requires": { + "path-key": "^2.0.0" + }, + "dependencies": { + "path-key": { + "version": "2.0.1", + "bundled": true + } + } + }, + "p-finally": { + "version": "1.0.0", + "bundled": true + }, + "signal-exit": { + "version": "3.0.2", + "bundled": true + }, + "strip-eof": { + "version": "1.0.0", + "bundled": true + } + } + } + } + }, + "widest-line": { + "version": "1.0.0", + "bundled": true, + "requires": { + "string-width": "^1.0.1" + }, + "dependencies": { + "string-width": { + "version": "1.0.2", + "bundled": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + }, + "dependencies": { + "code-point-at": { + "version": "1.1.0", + "bundled": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "bundled": true, + "requires": { + "number-is-nan": "^1.0.0" + }, + "dependencies": { + "number-is-nan": { + "version": "1.0.1", + "bundled": true + } + } + }, + "strip-ansi": { + "version": "3.0.1", + "bundled": true, + "requires": { + "ansi-regex": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "bundled": true + } + } + } + } + } + } + } + } + }, + "chalk": { + "version": "2.1.0", + "bundled": true, + "requires": { + "ansi-styles": "^3.1.0", + "escape-string-regexp": "^1.0.5", + "supports-color": "^4.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.0", + "bundled": true, + "requires": { + "color-convert": "^1.9.0" + }, + "dependencies": { + "color-convert": { + "version": "1.9.0", + "bundled": true, + "requires": { + "color-name": "^1.1.1" + }, + "dependencies": { + "color-name": { + "version": "1.1.3", + "bundled": true + } + } + } + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "bundled": true + }, + "supports-color": { + "version": "4.4.0", + "bundled": true, + "requires": { + "has-flag": "^2.0.0" + }, + "dependencies": { + "has-flag": { + "version": "2.0.0", + "bundled": true + } + } + } + } + }, + "configstore": { + "version": "3.1.1", + "bundled": true, + "requires": { + "dot-prop": "^4.1.0", + "graceful-fs": "^4.1.2", + "make-dir": "^1.0.0", + "unique-string": "^1.0.0", + "write-file-atomic": "^2.0.0", + "xdg-basedir": "^3.0.0" + }, + "dependencies": { + "dot-prop": { + "version": "4.2.0", + "bundled": true, + "requires": { + "is-obj": "^1.0.0" + }, + "dependencies": { + "is-obj": { + "version": "1.0.1", + "bundled": true + } + } + }, + "make-dir": { + "version": "1.0.0", + "bundled": true, + "requires": { + "pify": "^2.3.0" + }, + "dependencies": { + "pify": { + "version": "2.3.0", + "bundled": true + } + } + }, + "unique-string": { + "version": "1.0.0", + "bundled": true, + "requires": { + "crypto-random-string": "^1.0.0" + }, + "dependencies": { + "crypto-random-string": { + "version": "1.0.0", + "bundled": true + } + } + } + } + }, + "import-lazy": { + "version": "2.1.0", + "bundled": true + }, + "is-installed-globally": { + "version": "0.1.0", + "bundled": true, + "requires": { + "global-dirs": "^0.1.0", + "is-path-inside": "^1.0.0" + }, + "dependencies": { + "global-dirs": { + "version": "0.1.0", + "bundled": true, + "requires": { + "ini": "^1.3.4" + } + }, + "is-path-inside": { + "version": "1.0.0", + "bundled": true, + "requires": { + "path-is-inside": "^1.0.1" + } + } + } + }, + "is-npm": { + "version": "1.0.0", + "bundled": true + }, + "latest-version": { + "version": "3.1.0", + "bundled": true, + "requires": { + "package-json": "^4.0.0" + }, + "dependencies": { + "package-json": { + "version": "4.0.1", + "bundled": true, + "requires": { + "got": "^6.7.1", + "registry-auth-token": "^3.0.1", + "registry-url": "^3.0.3", + "semver": "^5.1.0" + }, + "dependencies": { + "got": { + "version": "6.7.1", + "bundled": true, + "requires": { + "create-error-class": "^3.0.0", + "duplexer3": "^0.1.4", + "get-stream": "^3.0.0", + "is-redirect": "^1.0.0", + "is-retry-allowed": "^1.0.0", + "is-stream": "^1.0.0", + "lowercase-keys": "^1.0.0", + "safe-buffer": "^5.0.1", + "timed-out": "^4.0.0", + "unzip-response": "^2.0.1", + "url-parse-lax": "^1.0.0" + }, + "dependencies": { + "create-error-class": { + "version": "3.0.2", + "bundled": true, + "requires": { + "capture-stack-trace": "^1.0.0" + }, + "dependencies": { + "capture-stack-trace": { + "version": "1.0.0", + "bundled": true + } + } + }, + "duplexer3": { + "version": "0.1.4", + "bundled": true + }, + "get-stream": { + "version": "3.0.0", + "bundled": true + }, + "is-redirect": { + "version": "1.0.0", + "bundled": true + }, + "is-retry-allowed": { + "version": "1.1.0", + "bundled": true + }, + "is-stream": { + "version": "1.1.0", + "bundled": true + }, + "lowercase-keys": { + "version": "1.0.0", + "bundled": true + }, + "timed-out": { + "version": "4.0.1", + "bundled": true + }, + "unzip-response": { + "version": "2.0.1", + "bundled": true + }, + "url-parse-lax": { + "version": "1.0.0", + "bundled": true, + "requires": { + "prepend-http": "^1.0.1" + }, + "dependencies": { + "prepend-http": { + "version": "1.0.4", + "bundled": true + } + } + } + } + }, + "registry-auth-token": { + "version": "3.3.1", + "bundled": true, + "requires": { + "rc": "^1.1.6", + "safe-buffer": "^5.0.1" + }, + "dependencies": { + "rc": { + "version": "1.2.1", + "bundled": true, + "requires": { + "deep-extend": "~0.4.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "dependencies": { + "deep-extend": { + "version": "0.4.2", + "bundled": true + }, + "minimist": { + "version": "1.2.0", + "bundled": true + }, + "strip-json-comments": { + "version": "2.0.1", + "bundled": true + } + } + } + } + }, + "registry-url": { + "version": "3.1.0", + "bundled": true, + "requires": { + "rc": "^1.0.1" + }, + "dependencies": { + "rc": { + "version": "1.2.1", + "bundled": true, + "requires": { + "deep-extend": "~0.4.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "dependencies": { + "deep-extend": { + "version": "0.4.2", + "bundled": true + }, + "minimist": { + "version": "1.2.0", + "bundled": true + }, + "strip-json-comments": { + "version": "2.0.1", + "bundled": true + } + } + } + } + } + } + } + } + }, + "semver-diff": { + "version": "2.1.0", + "bundled": true, + "requires": { + "semver": "^5.0.3" + } + }, + "xdg-basedir": { + "version": "3.0.0", + "bundled": true + } + } + }, + "uuid": { + "version": "3.2.1", + "bundled": true + }, + "validate-npm-package-license": { + "version": "3.0.1", + "bundled": true, + "requires": { + "spdx-correct": "~1.0.0", + "spdx-expression-parse": "~1.0.0" + }, + "dependencies": { + "spdx-correct": { + "version": "1.0.2", + "bundled": true, + "requires": { + "spdx-license-ids": "^1.0.2" + }, + "dependencies": { + "spdx-license-ids": { + "version": "1.2.2", + "bundled": true + } + } + }, + "spdx-expression-parse": { + "version": "1.0.4", + "bundled": true + } + } + }, + "validate-npm-package-name": { + "version": "3.0.0", + "bundled": true, + "requires": { + "builtins": "^1.0.3" + }, + "dependencies": { + "builtins": { + "version": "1.0.3", + "bundled": true + } + } + }, + "which": { + "version": "1.3.0", + "bundled": true, + "requires": { + "isexe": "^2.0.0" + }, + "dependencies": { + "isexe": { + "version": "2.0.0", + "bundled": true + } + } + }, + "worker-farm": { + "version": "1.5.4", + "bundled": true, + "requires": { + "errno": "~0.1.7", + "xtend": "~4.0.1" + }, + "dependencies": { + "errno": { + "version": "0.1.7", + "bundled": true, + "requires": { + "prr": "~1.0.1" + }, + "dependencies": { + "prr": { + "version": "1.0.1", + "bundled": true + } + } + }, + "xtend": { + "version": "4.0.1", + "bundled": true + } + } + }, + "wrappy": { + "version": "1.0.2", + "bundled": true + }, + "write-file-atomic": { + "version": "2.3.0", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.11", + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.2" + }, + "dependencies": { + "signal-exit": { + "version": "3.0.2", + "bundled": true + } + } + } + } + }, + "o-stream": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/o-stream/-/o-stream-0.2.2.tgz", + "integrity": "sha512-V3j76KU3g/Gyl8rpdi2z72rn5zguMvTCQgAXfBe3pxEefKqXmOUOD7mvx/mNjykdxGqDVfpSoo8r+WdrkWg/1Q==", + "dev": true + }, + "object.defaults": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/object.defaults/-/object.defaults-1.1.0.tgz", + "integrity": "sha1-On+GgzS0B96gbaFtiNXNKeQ1/s8=", + "dev": true, + "requires": { + "array-each": "^1.0.1", + "array-slice": "^1.0.0", + "for-own": "^1.0.0", + "isobject": "^3.0.0" + }, + "dependencies": { + "for-own": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-1.0.0.tgz", + "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", + "dev": true, + "requires": { + "for-in": "^1.0.1" + } + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } + } + }, + "object.omit": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/object.omit/-/object.omit-2.0.1.tgz", + "integrity": "sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo=", + "dev": true, + "requires": { + "for-own": "^0.1.4", + "is-extendable": "^0.1.1" + } + }, + "object.pick": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "dev": true, + "requires": { + "isobject": "^3.0.1" + }, + "dependencies": { + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } + } + }, + "once": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/once/-/once-1.3.3.tgz", + "integrity": "sha1-suJhVXzkwxTsgwTz+oJmPkKXyiA=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "orchestrator": { + "version": "0.3.8", + "resolved": "https://registry.npmjs.org/orchestrator/-/orchestrator-0.3.8.tgz", + "integrity": "sha1-FOfp4nZPcxX7rBhOUGx6pt+UrX4=", + "dev": true, + "requires": { + "end-of-stream": "~0.1.5", + "sequencify": "~0.0.7", + "stream-consume": "~0.1.0" + } + }, + "ordered-read-streams": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/ordered-read-streams/-/ordered-read-streams-0.1.0.tgz", + "integrity": "sha1-/VZamvjrRHO6abbtijQ1LLVS8SY=", + "dev": true + }, + "os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=", + "dev": true + }, + "parse-filepath": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parse-filepath/-/parse-filepath-1.0.1.tgz", + "integrity": "sha1-FZ1hVdQ5BNFsEO9piRHaHpGWm3M=", + "dev": true, + "requires": { + "is-absolute": "^0.2.3", + "map-cache": "^0.2.0", + "path-root": "^0.1.1" + } + }, + "parse-glob": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/parse-glob/-/parse-glob-3.0.4.tgz", + "integrity": "sha1-ssN2z7EfNVE7rdFz7wu246OIORw=", + "dev": true, + "requires": { + "glob-base": "^0.3.0", + "is-dotfile": "^1.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.0" + } + }, + "parse-passwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", + "integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=", + "dev": true + }, + "path-parse": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.5.tgz", + "integrity": "sha1-PBrfhx6pzWyUMbbqK9dKD/BVxME=", + "dev": true + }, + "path-root": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/path-root/-/path-root-0.1.1.tgz", + "integrity": "sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc=", + "dev": true, + "requires": { + "path-root-regex": "^0.1.0" + } + }, + "path-root-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/path-root-regex/-/path-root-regex-0.1.2.tgz", + "integrity": "sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0=", + "dev": true + }, + "preserve": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/preserve/-/preserve-0.2.0.tgz", + "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=", + "dev": true + }, + "pretty-hrtime": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/pretty-hrtime/-/pretty-hrtime-1.0.3.tgz", + "integrity": "sha1-t+PqQkNaTJsnWdmeDyAesZWALuE=", + "dev": true + }, + "process-nextick-args": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", + "integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M=", + "dev": true + }, + "randomatic": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/randomatic/-/randomatic-1.1.7.tgz", + "integrity": "sha512-D5JUjPyJbaJDkuAazpVnSfVkLlpeO3wDlPROTMLGKG1zMFNFRgrciKo1ltz/AzNTkqE0HzDx655QOL51N06how==", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "kind-of": "^4.0.0" + }, + "dependencies": { + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "kind-of": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", + "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "readable-stream": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.3.tgz", + "integrity": "sha512-m+qzzcn7KUxEmd1gMbchF+Y2eIUbieUaxkWtptyHywrX0rE8QEYqPC07Vuy4Wm32/xE16NcdBctb8S0Xe/5IeQ==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~1.0.6", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.0.3", + "util-deprecate": "~1.0.1" + } + }, + "rechoir": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz", + "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", + "dev": true, + "requires": { + "resolve": "^1.1.6" + } + }, + "regex-cache": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/regex-cache/-/regex-cache-0.4.3.tgz", + "integrity": "sha1-mxpsNdTQ3871cRrmUejp09cRQUU=", + "dev": true, + "requires": { + "is-equal-shallow": "^0.1.3", + "is-primitive": "^2.0.0" + } + }, + "remove-trailing-separator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", + "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", + "dev": true + }, + "repeat-element": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.2.tgz", + "integrity": "sha1-7wiaF40Ug7quTZPrmLT55OEdmQo=", + "dev": true + }, + "repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", + "dev": true + }, + "replace-ext": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-0.0.1.tgz", + "integrity": "sha1-KbvZIHinOfC8zitO5B6DeVNSKSQ=", + "dev": true + }, + "resolve": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.4.0.tgz", + "integrity": "sha512-aW7sVKPufyHqOmyyLzg/J+8606v5nevBgaliIlV7nUpVMsDnoBGV/cbSLNjZAg9q0Cfd/+easKVKQ8vOu8fn1Q==", + "dev": true, + "requires": { + "path-parse": "^1.0.5" + } + }, + "resolve-dir": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-0.1.1.tgz", + "integrity": "sha1-shklmlYC+sXFxJatiUpujMQwJh4=", + "dev": true, + "requires": { + "expand-tilde": "^1.2.2", + "global-modules": "^0.2.3" + } + }, + "safe-buffer": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", + "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==", + "dev": true + }, + "sequencify": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/sequencify/-/sequencify-0.0.7.tgz", + "integrity": "sha1-kM/xnQLgcCf9dn9erT57ldHnOAw=", + "dev": true + }, + "sigmund": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/sigmund/-/sigmund-1.0.1.tgz", + "integrity": "sha1-P/IfGYytIXX587eBhT/ZTQ0ZtZA=", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "sparkles": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/sparkles/-/sparkles-1.0.0.tgz", + "integrity": "sha1-Gsu/tZJDbRC76PeFt8xvgoFQEsM=", + "dev": true + }, + "stream-consume": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/stream-consume/-/stream-consume-0.1.0.tgz", + "integrity": "sha1-pB6tGm1ggc63n2WwYZAbbY89HQ8=", + "dev": true + }, + "string_decoder": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", + "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "through2": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.3.tgz", + "integrity": "sha1-AARWmzfHx0ujnEPzzteNGtlBQL4=", + "dev": true, + "requires": { + "readable-stream": "^2.1.5", + "xtend": "~4.0.1" + } + }, + "tildify": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/tildify/-/tildify-1.2.0.tgz", + "integrity": "sha1-3OwD9V3Km3qj5bBPIYF+tW5jWIo=", + "dev": true, + "requires": { + "os-homedir": "^1.0.0" + } + }, + "time-stamp": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/time-stamp/-/time-stamp-1.1.0.tgz", + "integrity": "sha1-dkpaEa9QVhkhsTPztE5hhofg9cM=", + "dev": true + }, + "uglify-es": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/uglify-es/-/uglify-es-3.3.9.tgz", + "integrity": "sha512-r+MU0rfv4L/0eeW3xZrd16t4NZfK8Ld4SWVglYBb7ez5uXFWHuVRs6xCTrf1yirs9a4j4Y27nn7SRfO6v67XsQ==", + "dev": true, + "requires": { + "commander": "~2.13.0", + "source-map": "~0.6.1" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "unc-path-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/unc-path-regex/-/unc-path-regex-0.1.2.tgz", + "integrity": "sha1-5z3T17DXxe2G+6xrCufYxqadUPo=", + "dev": true + }, + "unique-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unique-stream/-/unique-stream-1.0.0.tgz", + "integrity": "sha1-1ZpKdUJ0R9mqbJHnAmP40mpLEEs=", + "dev": true + }, + "user-home": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/user-home/-/user-home-1.1.1.tgz", + "integrity": "sha1-K1viOjK2Onyd640PKNSFcko98ZA=", + "dev": true + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true + }, + "v8flags": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/v8flags/-/v8flags-2.1.1.tgz", + "integrity": "sha1-qrGh+jDUX4jdMhFIh1rALAtV5bQ=", + "dev": true, + "requires": { + "user-home": "^1.1.1" + } + }, + "vinyl": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-0.5.3.tgz", + "integrity": "sha1-sEVbOPxeDPMNQyUTLkYZcMIJHN4=", + "dev": true, + "requires": { + "clone": "^1.0.0", + "clone-stats": "^0.0.1", + "replace-ext": "0.0.1" + } + }, + "vinyl-fs": { + "version": "0.3.14", + "resolved": "https://registry.npmjs.org/vinyl-fs/-/vinyl-fs-0.3.14.tgz", + "integrity": "sha1-mmhRzhysHBzqX+hsCTHWIMLPqeY=", + "dev": true, + "requires": { + "defaults": "^1.0.0", + "glob-stream": "^3.1.5", + "glob-watcher": "^0.0.6", + "graceful-fs": "^3.0.0", + "mkdirp": "^0.5.0", + "strip-bom": "^1.0.0", + "through2": "^0.6.1", + "vinyl": "^0.4.0" + }, + "dependencies": { + "clone": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/clone/-/clone-0.2.0.tgz", + "integrity": "sha1-xhJqkK1Pctv1rNskPMN3JP6T/B8=", + "dev": true + }, + "graceful-fs": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-3.0.11.tgz", + "integrity": "sha1-dhPHeKGv6mLyXGMKCG1/Osu92Bg=", + "dev": true, + "requires": { + "natives": "^1.1.0" + } + }, + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "readable-stream": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", + "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + }, + "strip-bom": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-1.0.0.tgz", + "integrity": "sha1-hbiGLzhEtabV7IRnqTWYFzo295Q=", + "dev": true, + "requires": { + "first-chunk-stream": "^1.0.0", + "is-utf8": "^0.2.0" + } + }, + "through2": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-0.6.5.tgz", + "integrity": "sha1-QaucZ7KdVyCQcUEOHXp6lozTrUg=", + "dev": true, + "requires": { + "readable-stream": ">=1.0.33-1 <1.1.0-0", + "xtend": ">=4.0.0 <4.1.0-0" + } + }, + "vinyl": { + "version": "0.4.6", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-0.4.6.tgz", + "integrity": "sha1-LzVsh6VQolVGHza76ypbqL94SEc=", + "dev": true, + "requires": { + "clone": "^0.2.0", + "clone-stats": "^0.0.1" + } + } + } + }, + "vinyl-sourcemaps-apply": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/vinyl-sourcemaps-apply/-/vinyl-sourcemaps-apply-0.2.1.tgz", + "integrity": "sha1-q2VJ1h0XLCsbh75cUI0jnI74dwU=", + "dev": true, + "requires": { + "source-map": "^0.5.1" + } + }, + "which": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.0.tgz", + "integrity": "sha512-xcJpopdamTuY5duC/KnTTNBraPK54YwpenP4lzxU8H91GudWpFv38u0CKjclE1Wi2EH2EDz5LRcHcKbCIzqGyg==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } +} diff --git a/package.json b/package.json index ddf51dc..6ac682e 100644 --- a/package.json +++ b/package.json @@ -1,28 +1,22 @@ { "name": "x-tag", "description": "The X-Tag core library", - "version": "1.5.11", + "version": "2.0.3-beta", "homepage": "http://www.x-tags.org", "license": "MIT", "repository": { "type": "git", "url": "git://github.com/x-tag/core.git" }, - "scripts": { - "test": "grunt test" - }, - "main": "src/core.js", + "main": "dist/x-tag-polyfilled.js", "devDependencies": { - "grunt": "~0.4.0", - "grunt-cli": "0.1.13", - "grunt-contrib-jshint": "0.3.0", - "grunt-contrib-concat": "~0.1.2", - "grunt-contrib-uglify": "~0.1.1", - "grunt-contrib-connect": "~0.6.0", - "grunt-tagrelease": "~0.2.0", - "grunt-saucelabs": "~5.0.1", - "grunt-bumpup": "~0.2.0", - "async": "~0.2.9", - "watch": "~0.9.0" + "gulp": "^3.9.1", + "gulp-concat": "^2.6.1", + "gulp-uglify-es": "^0.1.11" + }, + "dependencies": { + "@webcomponents/custom-elements": "^1.0.9", + "natives": "^1.1.6", + "npm": "^5.8.0" } -} \ No newline at end of file +} diff --git a/plugins/attributes/src/main.js b/plugins/attributes/src/main.js new file mode 100644 index 0000000..a57e8a1 --- /dev/null +++ b/plugins/attributes/src/main.js @@ -0,0 +1,12 @@ + +xtag.extensions.src = { + mixin: (base) => class extends base { + set 'src::attr' (val){ + var xhr = new XMLHttpRequest(); + xhr.open('GET', val, true); + xhr.onload = () => xtag.fireEvent(this, 'load', { detail: xhr.response }); + xhr.onerror = () => xtag.fireEvent(this, 'error', { detail: xhr.response }); + xhr.send(null); + } + } +}; \ No newline at end of file diff --git a/plugins/events/tap/main.js b/plugins/events/tap/main.js new file mode 100644 index 0000000..3ada52c --- /dev/null +++ b/plugins/events/tap/main.js @@ -0,0 +1,14 @@ + +xtag.events.tap = { + attach: ['pointerdown', 'pointerup'], + onFilter (node, event, ref, resolve){ + var data = ref.data; + if (event.type == 'pointerdown') { + data.startX = event.clientX; + data.startY = event.clientY; + } + else if (event.button === 0 && + Math.abs(data.startX - event.clientX) < 10 && + Math.abs(data.startY - event.clientY) < 10) resolve(); + } +}; \ No newline at end of file diff --git a/plugins/events/tap/pep.min.js b/plugins/events/tap/pep.min.js new file mode 100644 index 0000000..9c3e25d --- /dev/null +++ b/plugins/events/tap/pep.min.js @@ -0,0 +1,210 @@ +/*! + * PEP v0.4.3 | https://github.com/jquery/PEP + * Copyright jQuery Foundation and other contributors | http://jquery.org/license + */ +!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):a.PointerEventsPolyfill=b()}(this,function(){"use strict";function a(a,b){b=b||Object.create(null);var c=document.createEvent("Event");c.initEvent(a,b.bubbles||!1,b.cancelable||!1); +// define inherited MouseEvent properties +// skip bubbles and cancelable since they're set above in initEvent() +for(var d,e=2;e element that is represented by the instance for Safari, Chrome, IE. +// This is the behavior implemented by Firefox. +!t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement); +// keep the semantics of preventDefault +return a.preventDefault&&(c.preventDefault=function(){a.preventDefault()}),c},getTarget:function(a){var b=this.captureInfo[a.pointerId];return b?a._target!==b&&a.type in s?void 0:b:a._target},propagate:function(a,b,c){ +// Order of conditions due to document.contains() missing in IE. +for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);) +// Touch: Do not propagate if node is detached. +if(e.push(d),d=d.parentNode,!d)return;c&&e.reverse(),e.forEach(function(c){a.target=c,b.call(this,a)},this)},setCapture:function(b,c,d){this.captureInfo[b]&&this.releaseCapture(b,d),this.captureInfo[b]=c,this.implicitRelease=this.releaseCapture.bind(this,b,d),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease);var e=new a("gotpointercapture");e.pointerId=b,e._target=c,d||this.asyncDispatchEvent(e)},releaseCapture:function(b,c){var d=this.captureInfo[b];if(d){this.captureInfo[b]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease);var e=new a("lostpointercapture");e.pointerId=b,e._target=d,c||this.asyncDispatchEvent(e)}},/** + * Dispatches the event to its target. + * + * @param {Event} inEvent The event to be dispatched. + * @return {Boolean} True if an event handler returns true, false otherwise. + */ +dispatchEvent:/*scope.external.dispatchEvent || */function(a){var b=this.getTarget(a);if(b)return b.dispatchEvent(a)},asyncDispatchEvent:function(a){requestAnimationFrame(this.dispatchEvent.bind(this,a))}};u.boundHandler=u.eventHandler.bind(u);var v={shadow:function(a){if(a)return a.shadowRoot||a.webkitShadowRoot},canTarget:function(a){return a&&Boolean(a.elementFromPoint)},targetingShadow:function(a){var b=this.shadow(a);if(this.canTarget(b))return b},olderShadow:function(a){var b=a.olderShadowRoot;if(!b){var c=a.querySelector("shadow");c&&(b=c.olderShadowRoot)}return b},allShadows:function(a){for(var b=[],c=this.shadow(a);c;)b.push(c),c=this.olderShadow(c);return b},searchRoot:function(a,b,c){if(a){var d,e,f=a.elementFromPoint(b,c);for( +// is element a shadow host? +e=this.targetingShadow(f);e;){if( +// find the the element inside the shadow root +d=e.elementFromPoint(b,c)){ +// shadowed element may contain a shadow root +var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d} +// check for older shadows +e=this.olderShadow(e)} +// light dom element is the target +return f}},owner:function(a){ +// walk up until you hit the shadow root or document +for(var b=a;b.parentNode;)b=b.parentNode; +// the owner element is expected to be a Document or ShadowRoot +return b.nodeType!==Node.DOCUMENT_NODE&&b.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(b=document),b},findTarget:function(a){var b=a.clientX,c=a.clientY,d=this.owner(a.target); +// if x, y is not in this root, fall back to document search +return d.elementFromPoint(b,c)||(d=document),this.searchRoot(d,b,c)}},w=Array.prototype.forEach.call.bind(Array.prototype.forEach),x=Array.prototype.map.call.bind(Array.prototype.map),y=Array.prototype.slice.call.bind(Array.prototype.slice),z=Array.prototype.filter.call.bind(Array.prototype.filter),A=window.MutationObserver||window.WebKitMutationObserver,B="[touch-action]",C={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};c.prototype={watchSubtree:function(a){ +// Only watch scopes that can target find, as these are top-level. +// Otherwise we can see duplicate additions and removals that add noise. +// +// TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see +// a removal without an insertion when a node is redistributed among +// shadows. Since it all ends up correct in the document, watching only +// the document will yield the correct mutations to watch. +this.observer&&v.canTarget(a)&&this.observer.observe(a,C)},enableOnSubtree:function(a){this.watchSubtree(a),a===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(a)},installNewSubtree:function(a){w(this.findElements(a),this.addElement,this)},findElements:function(a){return a.querySelectorAll?a.querySelectorAll(B):[]},removeElement:function(a){this.removeCallback(a)},addElement:function(a){this.addCallback(a)},elementChanged:function(a,b){this.changedCallback(a,b)},concatLists:function(a,b){return a.concat(y(b))}, +// register all touch-action = none nodes on document load +installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(a){return a.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(a){ +// find children with touch-action +var b=x(a,this.findElements,this); +// flatten the list +// make sure the added nodes are accounted for +return b.push(z(a,this.isElement)),b.reduce(this.concatLists,[])},mutationWatcher:function(a){a.forEach(this.mutationHandler,this)},mutationHandler:function(a){if("childList"===a.type){var b=this.flattenMutationTree(a.addedNodes);b.forEach(this.addElement,this);var c=this.flattenMutationTree(a.removedNodes);c.forEach(this.removeElement,this)}else"attributes"===a.type&&this.elementChanged(a.target,a.oldValue)}};var D=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],E="",F=window.PointerEvent||window.MSPointerEvent,G=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,H=u.pointermap,I=25,J=[1,4,2,8,16],K=!1;try{K=1===new MouseEvent("test",{buttons:1}).buttons}catch(L){} +// handler block for native mouse events +var M,N={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},lastTouches:[], +// collide with the global mouse listener +isEventSimulatedFromTouch:function(a){for(var b,c=this.lastTouches,d=a.clientX,e=a.clientY,f=0,g=c.length;f delta other axis, scroll instead of +// making events +b=g>=h}return this.firstXY=null,b}},findTouch:function(a,b){for(var c,d=0,e=a.length;d=b.length){var c=[];R.forEach(function(a,d){ +// Never remove pointerId == 1, which is mouse. +// Touch identifiers are 2 smaller than their pointerId, which is the +// index in pointermap. +if(1!==d&&!this.findTouch(b,d-2)){var e=a.out;c.push(e)}},this),c.forEach(this.cancelOut,this)}},touchstart:function(a){this.vacuumTouches(a),this.setPrimaryTouch(a.changedTouches[0]),this.dedupSynthMouse(a),this.scrolling||(this.clickCount++,this.processTouches(a,this.overDown))},overDown:function(a){R.set(a.pointerId,{target:a.target,out:a,outTarget:a.target}),u.enterOver(a),u.down(a)},touchmove:function(a){this.scrolling||(this.shouldScroll(a)?(this.scrolling=!0,this.touchcancel(a)):(a.preventDefault(),this.processTouches(a,this.moveOverOut)))},moveOverOut:function(a){var b=a,c=R.get(b.pointerId); +// a finger drifted off the screen, ignore it +if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e, +// recover from retargeting by shadow +d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):( +// clean up case when finger leaves the screen +b.target=e,b.relatedTarget=null,this.cancelOut(b))),c.out=b,c.outTarget=b.target}},touchend:function(a){this.dedupSynthMouse(a),this.processTouches(a,this.upOut)},upOut:function(a){this.scrolling||(u.up(a),u.leaveOut(a)),this.cleanUpPointer(a)},touchcancel:function(a){this.processTouches(a,this.cancelOut)},cancelOut:function(a){u.cancel(a),u.leaveOut(a),this.cleanUpPointer(a)},cleanUpPointer:function(a){R["delete"](a.pointerId),this.removePrimaryPointer(a)}, +// prevent synth mouse events from creating pointer events +dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0]; +// only the primary finger will synth mouse events +if(this.isPrimaryTouch(c)){ +// remember x/y of last touch +var d={x:c.clientX,y:c.clientY};b.push(d);var e=function(a,b){var c=a.indexOf(b);c>-1&&a.splice(c,1)}.bind(null,b,d);setTimeout(e,S)}}};M=new c(V.elementAdded,V.elementRemoved,V.elementChanged,V);var W,X,Y,Z=u.pointermap,$=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,_={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(a){var b=a;return $&&(b=u.cloneEvent(a),b.pointerType=this.POINTER_TYPES[a.pointerType]),b},cleanup:function(a){Z["delete"](a)},MSPointerDown:function(a){Z.set(a.pointerId,a);var b=this.prepareEvent(a);u.down(b)},MSPointerMove:function(a){var b=this.prepareEvent(a);u.move(b)},MSPointerUp:function(a){var b=this.prepareEvent(a);u.up(b),this.cleanup(a.pointerId)},MSPointerOut:function(a){var b=this.prepareEvent(a);u.leaveOut(b)},MSPointerOver:function(a){var b=this.prepareEvent(a);u.enterOver(b)},MSPointerCancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.cleanup(a.pointerId)},MSLostPointerCapture:function(a){var b=u.makeEvent("lostpointercapture",a);u.dispatchEvent(b)},MSGotPointerCapture:function(a){var b=u.makeEvent("gotpointercapture",a);u.dispatchEvent(b)}},aa=window.navigator;aa.msPointerEnabled?(W=function(a){i(a),j(this),k(a)&&(u.setCapture(a,this,!0),this.msSetPointerCapture(a))},X=function(a){i(a),u.releaseCapture(a,!0),this.msReleasePointerCapture(a)}):(W=function(a){i(a),j(this),k(a)&&u.setCapture(a,this)},X=function(a){i(a),u.releaseCapture(a)}),Y=function(a){return!!u.captureInfo[a]},g(),h(),l();var ba={dispatcher:u,Installer:c,PointerEvent:a,PointerMap:p,targetFinding:v};return ba}); \ No newline at end of file diff --git a/plugins/rendering/hyperHTML/hyperHTML.min.js b/plugins/rendering/hyperHTML/hyperHTML.min.js new file mode 100644 index 0000000..ec8cd37 --- /dev/null +++ b/plugins/rendering/hyperHTML/hyperHTML.min.js @@ -0,0 +1 @@ +/*! (c) Andrea Giammarchi (ISC) */var hyperHTML=function(e){"use strict";function t(){}function n(e){this.childNodes=e,this.length=e.length,this.first=e[0],this.last=e[this.length-1]}function r(){}function i(){var e=function(e,n){for(var r=new w(n),i=e.length,o=0;o\"'=]+",R="<([A-Za-z]+[A-Za-z0-9:_-]*)((?:",H="(?:=(?:'[^']*?'|\"[^\"]*?\"|<[^>]*?>|[^ \\f\\n\\r\\t\\/>\"'=]+))?)",_=new RegExp(R+B+H+"+)([ "+$+"]*/?>)","g"),F=new RegExp(R+B+H+"*)([ "+$+"]*/>)","g"),Z=D(document),z="append"in Z,V="content"in O(document,"template");Z.appendChild(P(Z,"g")),Z.appendChild(P(Z,""));var G=1===Z.cloneNode(!0).childNodes.length,I="importNode"in document,W=z?function(e,t){e.append.apply(e,t)}:function(e,t){for(var n=t.length,r=0;r"+t+"",W(r,Y.call(n.querySelectorAll(i)))}else n.innerHTML=t,W(r,Y.call(n.childNodes));return r},re=V?function(e,t){var n=D(e),r=M(e).createElementNS(h,"svg");return r.innerHTML=t,W(n,Y.call(r.childNodes)),n}:function(e,t){var n=D(e),r=O(e,"div");return r.innerHTML=''+t+"",W(n,Y.call(r.firstChild.childNodes)),n};n.prototype.insert=function(){var e=D(this.first);return W(e,this.childNodes),e},n.prototype.remove=function(){var e=this.first,t=this.last;if(2===this.length)t.parentNode.removeChild(t);else{var n=M(e).createRange();n.setStartBefore(this.childNodes[1]),n.setEndAfter(t),n.deleteContents()}return e};var ie=function(e){var t=[],n=void 0;switch(e.nodeType){case f:case 11:n=e;break;case 8:n=e.parentNode,oe(t,n,e);break;default:n=e.ownerElement}for(e=n;n=n.parentNode;e=n)oe(t,n,e);return t},oe=function(e,t,n){e.unshift(e.indexOf.call(t.childNodes,n))},ae={create:function(e,t,n){return{type:e,name:n,node:t,path:ie(t)}},find:function(e,t){for(var n=t.length,r=0;rc){var m=n[d+1],b=null==m?a:o(m,0);if(l===d)e.insertBefore(o(n[l],1),b);else{for(var w=e.ownerDocument.createDocumentFragment();l<=d;)w.appendChild(o(n[l++],1));e.insertBefore(w,b)}}else if(null==t[u]&&u++,u===c)e.removeChild(o(t[u],-1));else{var y=e.ownerDocument.createRange();y.setStartBefore(o(t[u],-1)),y.setEndAfter(o(t[c],-1)),y.deleteContents()}return n},pe=new x;r.prototype=Object.create(null);var ge=function(e){return{html:e}},me=function Ze(e,t){return"ELEMENT_NODE"in e?e:e.constructor===n?1/t<0?t?e.remove():e.last:t?e.insert():e.first:Ze(e.render(),t)},be=function(e){return"ELEMENT_NODE"in e||e instanceof n||e instanceof t},we=function(e,t){for(var n=[],r=t.length,i=0;i"},De=new N,Pe=function(e,t){return null==e?$e(t||"html"):Be(e,t||"html")},$e=function(e){var t=void 0,n=void 0,r=void 0,i=void 0,a=void 0;return function(u){u=ee(u);var l=i!==u;return l&&(i=u,r=D(document),n="svg"===e?document.createElementNS(h,"svg"):r,a=o.bind(n)),a.apply(null,arguments),l&&("svg"===e&&W(r,Y.call(n.childNodes)),t=Re(r)),t}},Be=function(e,t){var n=t.indexOf(":"),r=De.get(e),i=t;return-1 class extends base { + _render (template, queued){ + if (template._hyper) { + template.call(this, hyperHTML.bind); + this._XTagRender = null; + if (queued.resolve) queued.resolve(this); + } + else super._render(template, queued); + } + }, + onParse (klass, property, args, descriptor){ + descriptor.value._hyper = true; + klass.getOptions('templates')[property || 'default'] = descriptor.value; + return false; + }, + onReady (node, resolve, property, args){ + if (args[0]) { + if (args[0] === 'ready') node.render(property); + else node.rxn('firstpaint', () => node.render(property)); + } + resolve(); + }, +} + +})(); \ No newline at end of file diff --git a/polyfills/custom-elements.min.js b/polyfills/custom-elements.min.js new file mode 100644 index 0000000..a960e24 --- /dev/null +++ b/polyfills/custom-elements.min.js @@ -0,0 +1,30 @@ +(function(){ + 'use strict';var h=new function(){};var aa=new Set("annotation-xml color-profile font-face font-face-src font-face-uri font-face-format font-face-name missing-glyph".split(" "));function k(b){var a=aa.has(b);b=/^[a-z][.0-9_a-z]*-[\-.0-9_a-z]*$/.test(b);return!a&&b}function l(b){var a=b.isConnected;if(void 0!==a)return a;for(;b&&!(b.__CE_isImportDocument||b instanceof Document);)b=b.parentNode||(window.ShadowRoot&&b instanceof ShadowRoot?b.host:void 0);return!(!b||!(b.__CE_isImportDocument||b instanceof Document))} + function m(b,a){for(;a&&a!==b&&!a.nextSibling;)a=a.parentNode;return a&&a!==b?a.nextSibling:null} + function n(b,a,e){e=e?e:new Set;for(var c=b;c;){if(c.nodeType===Node.ELEMENT_NODE){var d=c;a(d);var f=d.localName;if("link"===f&&"import"===d.getAttribute("rel")){c=d.import;if(c instanceof Node&&!e.has(c))for(e.add(c),c=c.firstChild;c;c=c.nextSibling)n(c,a,e);c=m(b,d);continue}else if("template"===f){c=m(b,d);continue}if(d=d.__CE_shadowRoot)for(d=d.firstChild;d;d=d.nextSibling)n(d,a,e)}c=c.firstChild?c.firstChild:m(b,c)}}function q(b,a,e){b[a]=e};function r(){this.a=new Map;this.m=new Map;this.f=[];this.b=!1}function ba(b,a,e){b.a.set(a,e);b.m.set(e.constructor,e)}function t(b,a){b.b=!0;b.f.push(a)}function v(b,a){b.b&&n(a,function(a){return w(b,a)})}function w(b,a){if(b.b&&!a.__CE_patched){a.__CE_patched=!0;for(var e=0;e'); - - waitsFor(function (){ - return created; - }, "new tag lifecycle event {created} should fire", 500); - - runs(function (){ - var fooElement = document.getElementById('foo'); - expect(created).toEqual(true); - expect(fooElement.bar()).toEqual(true); - }); - }); - - - it('should fire CREATED when custom element is added within a parent to innerHTML', function (){ - var created = false; - - xtag.register('x-foo4', { - lifecycle: { - created: function(){ - created = true; - } - }, - methods: { - bar: function (){ - return true; - }, - zoo: function(){ - return true; - } - } - }); - - xtag.set(testbox, 'innerHTML', '
'); - - waitsFor(function (){ - return created; - }, "new tag lifecycle event {created} should fire", 500); - - runs(function (){ - var fooElement = document.getElementById('foo'); - expect(created).toEqual(true); - expect(fooElement.bar()).toEqual(true); - }); - }); - - it('should fire INSERTED when injected into the DOM', function (){ - var inserted = false; - xtag.register('x-foo5', { - lifecycle: { - inserted: function (){ - inserted = true; - } - } - }); - - var foo = document.createElement('x-foo5'); - testbox.appendChild(foo); - waitsFor(function (){ - return inserted; - }, "new tag onInsert should fire", 1000); - - runs(function (){ - expect(inserted).toEqual(true); - }); - }); - - it('should fire REMOVED when removed into the DOM (w/inserted)', function (){ - var removed = false; - xtag.register('x-foo5-removed', { - lifecycle: { - inserted: function (){}, - removed: function (){ - removed = true; - } - } - }); - - var foo = document.createElement('x-foo5-removed'); - testbox.appendChild(foo); - setTimeout(function(){ - testbox.removeChild(foo); - },100); - - waitsFor(function (){ - return removed; - }, "new tag removed should fire", 500); - - runs(function (){ - expect(removed).toEqual(true); - }); - }); - - it('should fire REMOVED when removed into the DOM', function (){ - var removed = false; - xtag.register('x-foo5-removed-1', { - lifecycle: { - removed: function (){ - removed = true; - } - } - }); - - var foo = document.createElement('x-foo5-removed-1'); - testbox.appendChild(foo); - setTimeout(function(){ - testbox.removeChild(foo); - },100); - waitsFor(function (){ - return removed; - }, "new tag removed should fire", 500); - - runs(function (){ - expect(removed).toEqual(true); - }); - }); - - it('should parse new tag as soon as it is registered', function (){ - var foo = document.createElement('x-foo6'); - - testbox.appendChild(foo); - - xtag.register('x-foo6', { - methods: { - bar: function(){ return 'baz'; } - } - }); - - runs(function (){ - expect(foo.bar()).toEqual('baz'); - }); - }); - - it('should register methods for element', function (){ - - xtag.register('x-foo7', { - methods: { - baz: function (){ } - } - }); - - var foo = document.createElement('x-foo7'); - testbox.appendChild(foo); - - expect(foo.baz).toBeDefined(); - - }); - - it('should register getters for element', function (){ - - xtag.register('x-foo8', { - accessors: { - name: { - get: function (){ - return this.nodeName; - } - } - } - }); - - var foo = document.createElement('x-foo8'); - testbox.appendChild(foo); - - expect(foo.name).toEqual('X-FOO8'); - - }); - - it('should register setters for element', function (){ - - xtag.register('x-foo9', { - accessors: { - name: { - set: function (value){ - this.setAttribute('name', value); - } - } - } - }); - - var foo = document.createElement('x-foo9'); - testbox.appendChild(foo); - foo.name = 'pizza'; - - expect(foo.getAttribute('name')).toEqual('pizza'); - - }); - - it('xtag.innerHTML should instantiate x-tags in innerHTML', function (){ - xtag.register('x-foo10', { - accessors: { - name: { - set: function (value){ - this.setAttribute('name', value); - } - } - } - }); - xtag.innerHTML(testbox, ''); - var foo = document.getElementById('foo'); - foo.name = "Bob"; - expect(foo.getAttribute('name')).toEqual('Bob'); - }); - - it('should only fire INSERT when inserted into the DOM', function (){ - var inserted = false; - xtag.register('x-foo11', { - lifecycle: { - inserted: function (){ - inserted = true; - } - } - }); - var temp = document.createElement('div'); - temp.id = 'ZZZZZZZZZZZZZZZZZZZZZ'; - temp.appendChild(document.createElement('x-foo11')); - expect(inserted).toEqual(false); - - testbox.appendChild(temp); - - waitsFor(function (){ - return inserted; - }, "new tag onInsert should fire", 500); - - runs(function (){ - expect(inserted).toEqual(true); - }); - }); - - it("mixins should not override existing properties", function (){ - var onCreateFired = 0; - xtag.mixins.test = { - lifecycle: { - created: function (){ - onCreateFired++; - } - } - }; - - xtag.register('x-foo12', { - mixins: ['test'], - lifecycle: { - created: function (){ - onCreateFired++; - } - } - }); - - var foo = document.createElement('x-foo12'); - - expect(2).toEqual(onCreateFired); - }); - - it("should create a mixin, fire CREATED", function (){ - var onCreateFired = false; - xtag.mixins.test = { - lifecycle: { - created: function (){ - onCreateFired = true; - } - } - }; - - xtag.register('x-foo13', { - mixins: ['test'] - }); - - var foo = document.createElement('x-foo13'); - expect(true).toEqual(onCreateFired); - }); - - it("should create a mixin, fire inserted", function (){ - var onInsertFired = false; - xtag.mixins.test = { - lifecycle: { - inserted: function (){ - onInsertFired = true; - } - } - }; - - xtag.register('x-foo14', { - mixins: ['test'] - }); - - var foo = document.createElement('x-foo14'); - testbox.appendChild(foo); - - waitsFor(function (){ - return onInsertFired; - }, "new tag mixin inserted should fire", 500); - - runs(function (){ - expect(true).toEqual(onInsertFired); - }); - }); - - it("mixins should wrap functions by default", function (){ - var count = 0, - mixinFired, - originalFired; - - xtag.mixins.wrapFn = { - lifecycle: { - created: function (){ - mixinFired = ++count; - } - } - }; - - xtag.register('x-foo-mixin-fn', { - mixins: ['wrapFn'], - lifecycle: { - 'created:mixins': function (){ - originalFired = ++count; - } - } - }); - - var foo = document.createElement('x-foo-mixin-fn'); - - waitsFor(function (){ - return mixinFired && originalFired; - }, "new tag mixin created should fire", 500); - - runs(function (){ - expect(1).toEqual(mixinFired); - expect(2).toEqual(originalFired); - }); - }); - - it("should fire all mixins, even when there is no base function", function (){ - var count = 0, - mixinOne, - mixinTwo; - - xtag.mixins.mixinOne = { - lifecycle: { - created: function (){ - mixinOne = ++count; - } - } - }; - - xtag.mixins.mixinTwo = { - lifecycle: { - created: function (){ - mixinTwo = ++count; - } - } - }; - - xtag.register('x-foo-multi-mixin', { - mixins: ['mixinOne', 'mixinTwo'] - }); - - var foo = document.createElement('x-foo-multi-mixin'); - - waitsFor(function (){ - return count == 2; - }, "new tag mixin created should fire", 500); - - runs(function (){ - expect(2).toEqual(mixinOne); - expect(1).toEqual(mixinTwo); - }); - }); - - it("it should fire the mixin created function BEFORE the element's", function (){ - var count = 0, - createdFired1, - createdFired2; - - xtag.mixins.test = { - lifecycle: { - created: function (){ - createdFired1 = ++count; - } - } - }; - - xtag.register('x-foo15', { - mixins: ['test'], - lifecycle: { - 'created:mixins(before)': function (){ - createdFired2 = ++count; - } - } - }); - - var foo = document.createElement('x-foo15'); - testbox.appendChild(foo); - - waitsFor(function (){ - return createdFired1 && createdFired2; - }, "new tag mixin created should fire", 500); - - runs(function (){ - expect(1).toEqual(createdFired1); - expect(2).toEqual(createdFired2); - }); - }); - - it("it should fire the mixin created function AFTER the element's", function (){ - var count = 0, - createdFired1, - createdFired2; - - xtag.mixins.test = { - lifecycle: { - 'created': function (){ - createdFired2 = ++count; - } - } - }; - - xtag.register('x-foo16', { - mixins: ['test'], - lifecycle: { - 'created:mixins(after)': function (){ - createdFired1 = ++count; - } - } - }); - - var foo = document.createElement('x-foo16'); - testbox.appendChild(foo); - - waitsFor(function (){ - return createdFired1 && createdFired2; - }, "new tag mixin created should fire", 500); - - runs(function (){ - expect(1).toEqual(createdFired1); - expect(2).toEqual(createdFired2); - }); - }); - - it("it should fire the mixin created function BEFORE, WHEN NO OPTION IS PASSED the element's", function (){ - var count = 0, - createdFired1, - createdFired2; - - xtag.mixins.test = { - lifecycle: { - 'created': function (){ - createdFired2 = ++count; - } - } - }; - - xtag.register('x-foo17', { - mixins: ['test'], - lifecycle: { - 'created:mixins': function (){ - createdFired1 = ++count; - } - } - }); - - var foo = document.createElement('x-foo17'); - testbox.appendChild(foo); - - waitsFor(function (){ - return createdFired1 && createdFired2; - }, "new tag mixin created should fire", 500); - - runs(function (){ - expect(2).toEqual(createdFired1); - expect(1).toEqual(createdFired2); - }); - }); - - it("should allow mixins to create getters", function (){ - var count = 0, base, mixin; - - xtag.mixins.test = { - accessors: { - bar: { - get: function (){ - mixin = ++count; - return "barr"; - } - } - } - }; - - xtag.register('x-foo18', { - mixins: ['test'], - accessors: { - bar: { - 'get:mixins': function (){ - base = ++count; - return "barr"; - } - } - } - }); - - var foo = document.createElement('x-foo18'); - var testing = foo.bar; - expect(mixin).toEqual(1); - expect(base).toEqual(2); - }); - - it("should allow mixins to create setters", function (){ - xtag.mixins.test = { - accessors: { - foo: { - set: function (value){ - this.setAttribute('foo', value); - } - } - } - }; - - xtag.register('x-foo19', { - mixins: ['test'] - }); - - var foo = document.createElement('x-foo19'); - foo.foo = 'barr'; - - expect('barr').toEqual(foo.getAttribute('foo')); - }); - - it("should allow mixins to handle events", function (){ - var mixinEvent1 = 0, - mixinEvent2 = 0, - mixinEvent3 = 0, - mixinEvent4 = 0, - count = 0; - - xtag.mixins.test = { - events: { - 'click': function(e){ - mixinEvent1 = ++count; - }, - 'bar': function(){ - mixinEvent4 = ++count; - } - } - }; - - xtag.register('x-foo20', { - mixins: ['test'], - events: { - 'click': function(e){ - mixinEvent2 = ++count; - }, - 'foo': function(e){ - mixinEvent3 = ++count; - xtag.fireEvent(this, 'bar'); - } - } - }); - - var foo = document.createElement('x-foo20'); - testbox.appendChild(foo); - - xtag.fireEvent(foo, 'click'); - xtag.fireEvent(foo, 'foo'); - - runs(function (){ - expect(mixinEvent1).toEqual(2); - expect(mixinEvent2).toEqual(1); - expect(mixinEvent3).toEqual(3); - expect(mixinEvent4).toEqual(4); - }); - }); - - it('delegate event pseudo should pass the custom element as second param', function (){ - - var customElement, currentTarget; - - xtag.register('x-foo21', { - lifecycle: { - created: function (){ - customElement = this; - this.innerHTML = '
'; - } - }, - events: { - 'click:delegate(div > div:first-child)': function (e, elem){ - currentTarget = e.currentTarget; - } - } - }); - - var foo = document.createElement('x-foo21'); - testbox.appendChild(foo); - - waitsFor(function (){ - return customElement; - }, "new tag mixin onInsert should fire", 500); - - runs(function (){ - xtag.fireEvent(xtag.query(customElement, 'div')[1], 'click'); - expect(customElement).toEqual(currentTarget); - }); - - }); - - it('delegate event pseudo should register a click on an inner element', function (){ - - var clicked = false, customElement; - - xtag.register('x-foo22', { - lifecycle: { - created: function (){ - customElement = this; - this.innerHTML = '
'; - } - }, - events: { - 'click:delegate(div:not(:nth-child(2)))': function (e, elem){ - clicked = true; - } - } - }); - - var foo = document.createElement('x-foo22'); - testbox.appendChild(foo); - - waitsFor(function (){ - return customElement; - }, "new tag mixin onInsert should fire", 500); - - runs(function (){ - xtag.fireEvent(xtag.query(customElement, 'div')[1], 'click'); - expect(clicked).toEqual(true); - }); - - }); - - it('delegate event pseudo should register a click on an inner pseudo element', function (){ - - var clicked = false, customElement; - - xtag.register('x-foo22-b', { - lifecycle: { - created: function (){ - customElement = this; - this.innerHTML = '
'; - } - }, - events: { - 'click:delegate(div:nth-child(2))': function (e, elem){ - clicked = true; - } - } - }); - - var foo = document.createElement('x-foo22-b'); - testbox.appendChild(foo); - - waitsFor(function (){ - return customElement; - }, "new tag mixin onInsert should fire", 1000); - - runs(function (){ - xtag.fireEvent(xtag.query(customElement, 'div')[1], 'click'); - expect(clicked).toEqual(true); - }); - - }); - - it('delegate event pseudo "this" should be the element filtered by pseudo', function (){ - - var customElement, delegateElement; - - xtag.register('x-foo23', { - lifecycle: { - created: function (){ - customElement = this; - this.innerHTML = '
'; - } - }, - events: { - 'click:delegate(div)': function (e, elem){ - delegateElement = this; - } - } - }); - - var foo = document.createElement('x-foo23'); - testbox.appendChild(foo); - - waitsFor(function (){ - return customElement; - }, "new tag mixin onInsert should fire", 500); - - runs(function (){ - xtag.fireEvent(xtag.query(customElement, 'div')[0], 'click'); - expect(delegateElement).toEqual(customElement.firstElementChild); - }); - - }); - - it('delegate event pseudo should support chaining', function (){ - - var clickThis = null; - - xtag.register('x-foo24', { - lifecycle: { - created: function (){ - this.innerHTML = '
'; - } - }, - - events: { - 'click:delegate(div):delegate(bazz)': function (e, elem){ - clickThis = this; - } - } - }); - - var foo = document.createElement('x-foo24'); - testbox.appendChild(foo); - - var innerDiv = xtag.query(foo,'bazz')[0]; - xtag.fireEvent(innerDiv,'click'); - - expect(innerDiv).toEqual(clickThis); - - }); - - it('setter foo should setAttribute foo on target', function (){ - - xtag.register('x-foo25', { - accessors:{ - foo: { attribute: {} } - } - }); - - var foo = document.createElement('x-foo25'); - testbox.appendChild(foo); - foo.foo = 'bar'; - - expect(foo.getAttribute('foo')).toEqual('bar'); - - }); - - it('setter foo should setAttribute bar on target', function (){ - - xtag.register('x-foo26', { - accessors:{ - foo: { - attribute: { name: 'bar' } - } - } - }); - - var foo = document.createElement('x-foo26'); - testbox.appendChild(foo); - - foo.foo = 'bar'; - - expect(foo.getAttribute('bar')).toEqual('bar'); - - }); - - it('setter fooBar should auto link to the attribute name foo-bar', function (){ - - xtag.register('x-foo-auto-attr-name', { - accessors:{ - fooBar: { - attribute: {} - } - } - }); - - var foo = document.createElement('x-foo-auto-attr-name'); - testbox.appendChild(foo); - - foo.fooBar = 'bar'; - - expect(foo.getAttribute('foo-bar')).toEqual('bar'); - - }); - - it('setter fooBar should run the validate and pass along the modified value', function (){ - var filteredValue; - xtag.register('x-foo-attr-validate', { - accessors:{ - fooBar: { - attribute: { - validate: function(value){ - return value | 0; - } - }, - set: function(value){ - filteredValue = value; - } - } - } - }); - - var foo = document.createElement('x-foo-attr-validate'); - testbox.appendChild(foo); - - foo.fooBar = 'bar'; - - expect(foo.getAttribute('foo-bar')).toEqual('0'); - - }); - - it('x-tag pseudos should allow css pseudos', function (){ - - var clickThis = null; - - xtag.register('x-foo27', { - lifecycle: { - created: function (){ - this.innerHTML = '
'; - } - }, - events: { - 'click:delegate(div):delegate(bazz:first-child)': function (e, elem){ - clickThis = this; - } - } - }); - - var foo = document.createElement('x-foo27'); - testbox.appendChild(foo); - - var button = xtag.query(foo,'button')[0]; - xtag.fireEvent(button,'click'); - - expect(button).toEqual(clickThis.childNodes[0]); - - }); - - it('the currentTarget property should always be populated with the attached element', function (){ - - var foo, count = 0; - - xtag.register('x-foo30', { - events: { - bar: function (e, elem){ - if (e.currentTarget == foo) count++; - }, - click: function (e, elem){ - if (e.currentTarget == foo) count++; - }, - barf: function(e, elem){ - if (e.currentTarget == foo) count++; - }, - 'barf:delegate(div)': function(e, elem){ - if (e.currentTarget == foo) count++; - } - } - }); - - foo = document.createElement('x-foo30'); - var d1 = document.createElement('div'); - foo.appendChild(d1); - var foo2 = document.createElement('x-foo30'); - testbox.appendChild(foo); - testbox.appendChild(foo2); - - var event = document.createEvent('MouseEvent'); - event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null); - foo.dispatchEvent(event); - - xtag.fireEvent(foo, 'bar'); - xtag.fireEvent(d1, 'barf'); - - waitsFor(function(){ - return count == 4; - }, 'both clicks to bubble', 500); - - runs(function (){ - expect(count).toEqual(4); - }); - - }); - - it('custom event pseudo should fire', function (){ - - var pseudoFired = false, - clickThis = null; - - xtag.pseudos.blah = { - action: function (pseudo, event){ - pseudoFired = true; - event.foo = this; - return true; - } - }; - - xtag.register('x-foo28', { - lifecycle: { - created: function (){ - this.innerHTML = '
'; - } - }, - events: { - 'click:delegate(div):blah:delegate(bazz)': function (e, elem){ - clickThis = this; - } - } - }); - - var foo = document.createElement('x-foo28'); - testbox.appendChild(foo); - - var innerDiv = xtag.query(foo,'bazz')[0]; - xtag.fireEvent(innerDiv,'click'); - - expect(pseudoFired).toEqual(true); - - expect(innerDiv).toEqual(clickThis); - - }); - - - - it('extends should allow elements to use other elements base functionality', function(){ - xtag.register("x-foo29", { - extends: 'div', - lifecycle: { - created: function() { - var nodes = xtag.createFragment('
hello
').cloneNode(true); - this.appendChild(nodes); - } - } - }); - - var foo = document.createElement('div', 'x-foo29'); - expect(foo.innerHTML).toEqual('
hello
'); - - }); - - it('extends should instantiate elements in natural source', function(){ - xtag.register("x-extendelement1",{ - extends: 'div', - lifecycle: { - created: function() { - var nodes = xtag.createFragment('
hello
').cloneNode(true); - this.appendChild(nodes); - } - } - }); - var foo = document.getElementById('extend_element'); - expect(foo.innerHTML).toEqual('
hello
'); - }); - - - it('is="" should bootstrap element', function(){ - var count = 0; - xtag.register("x-superdivo", { - extends: 'div', - methods: { - test: function(){ - count++; - } - } - }); - - var foo = document.createElement('div', 'x-superdivo'); - expect(foo.test).toBeDefined(); - foo.test(); - expect(count).toEqual(1); - - }); - - it('should allow a custom prototype to be used', function(){ - xtag.register("x-raw-proto", { - prototype: { fn: { value: function(){ - return 'passed'; - }}} - }); - - var foo = document.createElement('x-raw-proto'); - - expect(foo.fn).toBeDefined(); - expect(foo.fn()).toEqual('passed'); - expect(foo.click).toBeDefined(); - - }); - - it('should allow an inherited custom element prototype to be used', function(){ - var count = 0; - xtag.mixins.compACreated = { - content: '
foo
', - lifecycle: { - created: function(){ - count++; - } - } - }; - var CompA = xtag.register('comp-a', { - mixins: ['compACreated'], - lifecycle: { - created: function(){ - count++; - } - }, - accessors: { - foo: { - set: function(){ - count++; - }, - get: function(){ - return count; - } - } - }, - methods: { - sayHi: function () { - return count + 1; - } - } - }); - - xtag.register('comp-b', { - prototype: CompA.prototype, - content: '
bar
', - lifecycle: { - created: function(){ - count++; - } - } - }); - - var compb = document.createElement('comp-b'); - compb.foo = 'bar'; - - expect(compb.children[0].textContent).toEqual('foo'); - expect(compb.children[1].textContent).toEqual('bar'); - expect(count).toEqual(4); - expect(compb.foo).toEqual(4); - expect(compb.sayHi()).toEqual(5); - }); - - it('should be able to extend existing elements', function(){ - xtag.register("x-foo-extend", { - extends: 'input' - }); - - var foo = document.createElement('input', 'x-foo-extend'); - testbox.appendChild(foo); - - expect(foo.value).toBeDefined(); - - }); - - it('should pass the previous parentNode as the first parameter in the lifecycle removed callback', function(){ - var insertParent, removedParent, removed; - xtag.register("x-foo31", { - lifecycle: { - inserted: function() { - insertParent = this.parentNode; - }, - removed: function(parent) { - if(!removed) { - removedParent = parent; - removed = true; - } - } - } - }); - - var foo = document.createElement('x-foo31'); - testbox.appendChild(foo); - setTimeout(function(){ testbox.removeChild(foo); }, 200); - waitsFor(function(){ - return removed; - }, 'removed to be passed the last parentNode', 300); - - runs(function (){ - expect(insertParent == removedParent).toEqual(true); - }); - }); - - it('should add Shadow DOM to the element', function (){ - xtag.register('x-foo-shadow', { - shadow: '
bar
' - }); - - var foo = document.createElement('x-foo-shadow'); - expect(Element.prototype.createShadowRoot ? foo.shadowRoot.firstElementChild.textContent == 'bar' : !foo.firstElementChild).toEqual(true); - }); - - it('should add default content to the element', function (){ - xtag.register('x-foo-content', { - content: '
bar
' - }); - - var foo = document.createElement('x-foo-content'); - expect(foo.firstElementChild.textContent).toEqual('bar'); - }); - }); - - describe('helper methods', function (){ - describe('class', function (){ - var body; - - beforeEach(function (){ - body = document.body; - }); - - afterEach(function (){ - body.removeAttribute('class'); - }); - - it('hasClass', function (){ - expect(xtag.hasClass(body, 'foo')).toEqual(false); - body.setAttribute('class', 'foo'); - expect(xtag.hasClass(body, 'foo')).toEqual(true); - }); - - it('addClass', function (){ - expect(xtag.hasClass(body, 'foo')).toEqual(false); - xtag.addClass(body,'foo'); - expect(xtag.hasClass(body, 'foo')).toEqual(true); - - xtag.addClass(body,'bar'); - expect(xtag.hasClass(body, 'bar')).toEqual(true); - expect('foo bar').toEqual(body.getAttribute('class')); - expect(2).toEqual(body.getAttribute('class').split(' ').length); - - xtag.addClass(body,'biz red'); - - expect('foo bar biz red').toEqual(body.getAttribute('class')); - - // prevent dups - xtag.addClass(body,'foo red'); - expect('foo bar biz red').toEqual(body.getAttribute('class')); - - }); - - it('removeClass', function (){ - xtag.addClass(body,'foo'); - xtag.addClass(body,'bar'); - xtag.addClass(body,'baz'); - expect('foo bar baz').toEqual(body.getAttribute('class')); - - xtag.removeClass(body,'bar'); - expect('foo baz').toEqual(body.getAttribute('class')); - - xtag.addClass(body,'bar'); - expect('foo baz bar').toEqual(body.getAttribute('class')); - - xtag.removeClass(body,'foo'); - expect('baz bar').toEqual(body.getAttribute('class')); - - xtag.removeClass(body,'baz'); - expect('bar').toEqual(body.getAttribute('class')); - - xtag.removeClass(body,'random'); - body.setAttribute('class',' foo bar baz red '); - - xtag.removeClass(body,'bar'); - expect('foo baz red').toEqual(body.getAttribute('class')); - }); - - it('toggleClass', function (){ - xtag.toggleClass(body, 'foo'); - expect('foo').toEqual(body.getAttribute('class')); - - xtag.toggleClass(body, 'foo'); - expect('').toEqual(body.getAttribute('class')); - - xtag.addClass(body, 'baz'); - xtag.toggleClass(body, 'baz'); - expect('').toEqual(body.getAttribute('class')); - - }); - - it('Random combination of Class tests', function (){ - body.setAttribute('class', 'flex-stack'); - xtag.addClass(body, 'small_desktop'); - expect('flex-stack small_desktop').toEqual(body.getAttribute('class')); - - body.setAttribute('class', 'flex-stack'); - xtag.addClass(body, 'small_desktop'); - xtag.removeClass(body, 'small_desktop'); - expect('flex-stack').toEqual(body.getAttribute('class')); - - body.setAttribute('class', 'small_desktop flex-stack'); - xtag.removeClass(body, 'small_desktop'); - expect('flex-stack').toEqual(body.getAttribute('class')); - - body.setAttribute('class', 'small_desktop flex-stack'); - xtag.removeClass(body, 'small_desktop'); - xtag.removeClass(body, 'large_desktop'); - expect('flex-stack').toEqual(body.getAttribute('class')); - }); - }); - - describe('utils', function (){ - it('typeOf', function (){ - expect('object').toEqual(xtag.typeOf({})); - expect('array').toEqual(xtag.typeOf([])); - expect('string').toEqual(xtag.typeOf('d')); - expect('number').toEqual(xtag.typeOf(42)); - }); - - it('toArray', function (){ - expect([]).toEqual(xtag.toArray({})); - }); - - it('uid', function(){ - expect(xtag.uid).toBeDefined(); - expect('string').toEqual(typeof xtag.uid()); - }); - - describe('wrap', function(){ - it('should create new function that calls both functions', function(){ - var f1Called = false, - f1 = function(){ - f1Called = true; - }; - - var f2Called = false, - f2 = function(){ - f2Called = true; - }; - - var f3 = xtag.wrap(f1, f2); - f3(); - - expect(f1Called).toEqual(true); - expect(f2Called).toEqual(true); - }); - - }); - - it('queryChildren', function(){ - testbox.appendChild(document.createElement('a')); - testbox.appendChild(document.createElement('a')); - var div = document.createElement('div'); - div.appendChild(document.createElement('a')); - testbox.appendChild(div); - expect(2).toEqual(xtag.queryChildren(testbox, 'a').length); - expect(div.parentElement).toBeDefined(); - }); - - it('queryChildren no parent', function(){ - var div = document.createElement('div'); - div.appendChild(document.createElement('a')); - div.appendChild(document.createElement('a')); - expect(2).toEqual(xtag.queryChildren(div, 'a').length); - expect(div.parentElement).toBeNull(); - }); - - }); - }); -}); diff --git a/spec/events.js b/spec/events.js deleted file mode 100644 index 4f78cf1..0000000 --- a/spec/events.js +++ /dev/null @@ -1,20 +0,0 @@ - - - -describe("x-tag ", function () { - - var $ = document.getElementById; - - var tap = $('tap'), - tapCount = 0, - tapTimer = null; - - xtag.addEvent($('tap'), 'tap', function(){ - - tapCount++; - tapTimer = setTimeout(function(){ - - }, 1000); - }); - -}); diff --git a/spec/shadow.css b/spec/shadow.css deleted file mode 100644 index 9750bfb..0000000 --- a/spec/shadow.css +++ /dev/null @@ -1,4 +0,0 @@ - -x-shadowroot-styled::shadow div { - visibility: hidden; -} \ No newline at end of file diff --git a/spec/shadow.js b/spec/shadow.js deleted file mode 100644 index f08b7c0..0000000 --- a/spec/shadow.js +++ /dev/null @@ -1,165 +0,0 @@ - - -var DOMComponentsLoaded = false; -var WebComponentsReady = false; -var HTMLImportsLoaded = false; - -document.addEventListener('DOMComponentsLoaded', function (){ - DOMComponentsLoaded = true; -}); - -document.addEventListener('WebComponentsReady', function (){ - WebComponentsReady = true; -}); - -window.addEventListener('HTMLImportsLoaded', function (){ - HTMLImportsLoaded = true; -}); - -var xtagLoaded = false, - core = document.createElement('script'); - core.onload = function(){ - xtagLoaded = true; - DOMComponentsLoaded = true; - }; - core.src = '../src/core.js?d=' + new Date().getTime(); -document.querySelector('head').appendChild(core); - -describe("x-tag ", function () { - - it('should load x-tag.js and fire DOMComponentsLoaded', function (){ - - waitsFor(function(){ - return xtagLoaded && DOMComponentsLoaded && WebComponentsReady && xtag; - }, "document.register should be polyfilled", 2000); - - runs(function () { - expect(xtag).toBeDefined(); - }); - }); - - it('upgrades all elements synchronously when registered', function (){ - var createdFired = false; - xtag.register('x-sync', { - lifecycle: { - created: function (){ - createdFired = true; - } - }, - accessors: { - foo: { - get: function(){ - return 'bar'; - } - } - } - }); - - var created = document.createElement('x-sync'); - var existing = document.getElementById('sync_element'); - - waitsFor(function (){ - return createdFired; - }, "new tag lifecycle event CREATED should fire", 1000); - - runs(function (){ - expect(existing.foo).toEqual('bar'); - }); - }); - - it('should fire lifecycle event CREATED with its shadow root populated', function (){ - var shadowRootPopulated = false; - xtag.register('x-shadowroot-created', { - shadow: function(){/* -
foo
- */}, - lifecycle: { - created: function (){ - shadowRootPopulated = this.shadowRoot.firstChild.textContent == 'foo'; - } - } - }); - - var foo = document.createElement('x-shadowroot-created'); - - waitsFor(function (){ - return shadowRootPopulated; - }, "new tag lifecycle event CREATED should fire", 1); - - runs(function (){ - expect(shadowRootPopulated).toEqual(true); - }); - }); - - it('should be styled correctly using X-Tag\'s Shadow DOM features', function (){ - var shadowRootStyled = false; - xtag.register('x-shadowroot-styled', { - shadow: function(){/* -
foo
- */}, - lifecycle: { - created: function (){ - shadowRootStyled = getComputedStyle(this.shadowRoot.firstChild).visibility == 'hidden'; - } - } - }); - - var foo = document.createElement('x-shadowroot-styled'); - - // document.body.appendChild(foo); - - waitsFor(function (){ - return shadowRootStyled; - }, "new tag lifecycle event CREATED should fire", 1); - - runs(function (){ - expect(shadowRootStyled).toEqual(true); - }); - }); - - - describe('using testbox', function (){ - var testbox; - - beforeEach(function (){ - testbox = document.getElementById('testbox'); - }); - - afterEach(function (){ - testbox.innerHTML = ""; - }); - - it('testbox should exist', function (){ - expect(testbox).toBeDefined(); - }); - - it('should fire CREATED when tag is added to innerHTML', function (){ - var created = false; - xtag.register('x-foo3', { - lifecycle: { - created: function (){ - created = true; - } - }, - methods: { - bar: function (){ - return true; - } - } - }); - - xtag.set(testbox, 'innerHTML', ''); - - waitsFor(function (){ - return created; - }, "new tag lifecycle event {created} should fire", 1000); - - runs(function (){ - var fooElement = document.getElementById('foo'); - expect(created).toEqual(true); - expect(fooElement.bar()).toEqual(true); - }); - }); - - }); -}); diff --git a/src/core-v2.js b/src/core-v2.js deleted file mode 100644 index 45ae57f..0000000 --- a/src/core-v2.js +++ /dev/null @@ -1,368 +0,0 @@ - - -(function(){ - - // var root = document.documentElement; - // var matches = function(node, selector) { - // return this.call(node, selector); - // }.bind(root.matches || root.webkitMatchesSelector || root.mozMatchesSelector || root.msMatchesSelector || root.oMatchesSelector); - - // NodeList.prototype.forEach = NodeList.prototype.forEach || Array.prototype.forEach; - - var regexParseProperty = /(\w+)|(?:(:*)(\w+)(?:\((.+?(?=\)))\))?)/g; - var regexPseudoCapture = /(\w+)|:(\w+)\((.+?(?=\)?))?|:(\w+)/g; - var regexCamelToDash = /([a-z])([A-Z])/g; - var regexCaptureDigits = /(\d+)/g; - var emptyObj = {}; - var range = document.createRange(); - - var xtag = { - events: { - tap: { - attach: ['pointerdown', 'pointerup'], - onFilter: function(node, event, data){ - if (event.type == 'pointerdown') { - data.startX = event.clientX; - data.startY = event.clientY; - } - else return (event.button === 0 && - Math.abs(data.startX - event.clientX) < 10 && - Math.abs(data.startY - event.clientY) < 10) || null; - } - } - }, - pseudos: { - log: { - onInvoke: function(){ - console.log(arguments); - } - } - }, - extensions: { - attr: { - mixin: (base) => class extends base { - attributeChangedCallback(attr, last, current){ - var desc = this.constructor.getOptions('attributes')[attr]; - if (desc && desc.set && !desc._skip) { - desc._skip = true; - desc.set.call(this, current); - desc._skip = null; - } - } - }, - types: { - boolean: { - set: function(prop, val){ - val ? this.setAttribute(prop, '') : this.removeAttribute(prop); - }, - get: function(prop){ - return this.hasAttribute(prop); - } - } - }, - onParse: function(klass, prop, args, descriptor){ - klass.getOptions('attributes')[prop] = descriptor; - var type = this.types[args[0]] || {}; - let descSet = descriptor.set; - let typeSet = type.set || HTMLElement.prototype.setAttribute; - descriptor.set = function(val){ - var output; - if (descSet) output = descSet.call(this, val); - typeSet.call(this, prop, typeof output == 'undefined' ? val : output) ; - } - let descGet = descriptor.get; - let typeGet = type.get || HTMLElement.prototype.getAttribute; - descriptor.get = function(){ - var output; - var val = typeGet.call(this, prop); - if (descGet) output = descGet.call(this, val); - return typeof output == 'undefined' ? val : output; - } - delete descriptor.value; - delete descriptor.writable; - }, - onCompiled: function(klass, descriptors){ - klass.observedAttributes = Object.keys(klass.getOptions('attributes')).concat(klass.observedAttributes || []) - } - }, - event: { - onParse: function(klass, property, args, descriptor){ - return false; - }, - onConstruct: function(node, property, args, descriptor){ - xtag.addEvent(node, property, descriptor.value); - } - }, - template: { - mixin: (base) => class extends base { - set 'template::attr' (name){ - this.render(name); - } - get templates (){ - return this.constructor.getOptions('templates'); - } - render(name){ - var _name = name || 'default'; - var template = this.templates[_name]; - if (template) { - this.innerHTML = ''; - this.appendChild(range.createContextualFragment(template.call(this))); - } - else throw new ReferenceError('Template "' + _name + '" is undefined'); - } - }, - onParse: function(klass, property, args, descriptor){ - klass.getOptions('templates')[property || 'default'] = descriptor.value; - return false; - } - } - }, - create: function(klass){ - processExtensions('onParse', klass); - return klass; - }, - register: function (name, klass) { - customElements.define(name, klass); - }, - addEvent: function(node, key, fn, capture){ - var type; - var _fn = fn; - var pseudos = node.constructor.getOptions('pseudos'); - key.replace(regexPseudoCapture, (match, name, pseudo1, args, pseudo2) => { - if (name) type = name; - else { - var pseudo = pseudo1 || pseudo2, - pseudo = pseudos[pseudo] || xtag.pseudos[pseudo]; - var _args = args ? JSON.parse('['+ args +']') : []; - _fn = pseudoWrap(pseudo, _args, _fn); - if (pseudo.onParse) pseudo.onParse(node, type, _args, _fn); - } - }) - - node.addEventListener(type, _fn, capture); - var ref = { type: type, listener: _fn, capture: capture, data: {} }; - var event = node.constructor.getOptions('events')[type] || xtag.events[type]; - if (event) { - var listener = function(e){ - var output = event.onFilter(this, e, ref.data); - if (!output) return output; - xtag.fireEvent(e.target, type); - } - ref.attached = event.attach.map(type => { - return xtag.addEvent(node, type, listener); - }); - } - return ref; - }, - removeEvent: function(node, ref){ - node.removeEventListener(ref.type, ref.listener, ref.capture); - if (ref.attached) ref.attached.forEach(attached => { xtag.removeEvent(node, ref) }) - }, - fireEvent: function(node, name, obj = {}){ - node.dispatchEvent(new CustomEvent(name, obj)); - } - } - - function createClass(options = {}){ - var klass; - klass = class extends (options.native ? Object.getPrototypeOf(document.createElement(options.native)).constructor : HTMLElement) { - constructor () { - super(); - processExtensions('onConstruct', this); - } - }; - - klass.options = {}; - klass.getOptions = function(name){ - return this.options[name] || (this.options[name] = Object.assign({}, this.__proto__.options ? this.__proto__.options[name] : {})); - } - - klass.getOptions('extensions'); - klass.getOptions('pseudos'); - - klass.extensions = function extensions(...extensions){ - var exts = this.getOptions('extensions'); - return extensions.reduce((current, extension) => { - var mixin; - var extended = current; - if (!exts[extension.name]) { - if (typeof extension == 'string') { - mixin = xtag.extensions[extension].mixin; - exts[extension] = xtag.extensions[extension]; - } - else { - mixin = extension.mixin; - exts[extension.name] = extension; - } - if (mixin) { - extended = mixin(current); - processExtensions('onParse', extended); - } - } - return extended; - }, klass); - } - - klass.as = function(tag){ - return createClass({ - native: tag - }); - } - - return klass.extensions('attr', 'event', 'template'); - } - - XTagElement = createClass(); - - function pseudoWrap(pseudo, args, fn){ - return function(){ - var output = pseudo.onInvoke(this, args, fn); - if (output === null || output === false) return output; - return fn.apply(this, output instanceof Array ? output : arguments); - }; - } - - var doubleColon = '::'; - function processExtensions(event, target){ - switch (event) { - case 'onParse': { - var processedProps = {}; - var descriptors = getDescriptors(target); - var extensions = target.getOptions('extensions'); - var processed = target._processedExtensions = new Map(); - for (let z in descriptors) { - let property; - let extension; - let extensionArgs = []; - let descriptor = descriptors[z]; - let pseudos = target._pseudos || xtag.pseudos; - z.replace(regexParseProperty, function(match, prop, dots, name, args){ - property = prop || property; - if (args) var _args = JSON.parse('['+ args +']'); - if (dots && dots == '::') { - extensionArgs = _args || []; - extension = extensions[name] || xtag.extensions[name]; - if (!processed.get(extension)) processed.set(extension, []); - } - else if (!prop){ - let pseudo = pseudos[name]; - if (pseudo) { - for (let y in descriptor) { - let fn = descriptor[y]; - if (typeof fn == 'function' && pseudo.onInvoke) { - fn = descriptor[y] = pseudoWrap(pseudo, _args, fn); - if (pseudo.onParse) pseudo.onParse(target, property, _args, fn); - } - } - } - } - }); - let attachProperty; - if (extension) { - processed.get(extension).push([property, extensionArgs, descriptor]); - if (extension.onParse) attachProperty = extension.onParse(target, property, extensionArgs, descriptor); - } - if (!property || attachProperty === false) delete target.prototype[z]; - if (property && attachProperty !== false) { - let prop = processedProps[property] || (processedProps[property] = {}); - for (let y in descriptor) prop[y] = descriptor[y]; - } - } - for (let ext of processed.keys()) { - if (ext.onCompiled) ext.onCompiled(target, processedProps); - } - Object.defineProperties(target.prototype, processedProps); - break; - } - - case 'onConstruct': { - var processed = target.constructor._processedExtensions; - for (let [ext, items] of processed) { - if (ext.onConstruct) items.forEach(item => ext.onConstruct(target, ...item)) - } - break; - } - - } - } - - function getDescriptors(target){ - var descriptors = {}; - var proto = target.prototype; - Object.getOwnPropertyNames(proto).forEach(key => { - descriptors[key] = Object.getOwnPropertyDescriptor(proto, key); - }); - return descriptors; - } - - if (typeof define === 'function' && define.amd) { - define(xtag); - define(XTagElement); - } - else if (typeof module !== 'undefined' && module.exports) { - module.exports = { xtag: xtag, XTagElement: XTagElement }; - } - else { - window.xtag = xtag; - window.XTagElement = XTagElement; - } - -})(); - - - -Post = xtag.create(class Post extends XTagElement { - 'title::attr'(val){} - 'byline::attr'(val){} - get 'listItems'(){ - return [1,2,3]; - } - 'basic::template' (){ return `

${this.title}

-

${this.byline}

-
    ${this.listItems.map(item => `
  • ${item}
  • `).join('')}
`; - } -}); - -xtag.register('x-post', Post); - - -Article = xtag.create(class Article extends Post { - get test(){ return 'Test'; } -}); - -xtag.register('x-article', Article); - - - -Clock = xtag.create(class Clock extends XTagElement { - set 'test::attr("boolean")'(val){ console.log('setting test to: ' + val); } - connectedCallback (){ - this.start(); - } - start (){ - this.update(); - this.interval = setInterval(this.update.bind(this), 1000); - } - stop (){ - this.interval = clearInterval(this.interval); - } - update (){ - this.textContent = new Date().toLocaleTimeString(); - } - 'tap::event:log' (){ - if (this.interval) this.stop(); - else this.start(); - } -}); - -xtag.register('x-clock', Clock); - -DigitalClock = xtag.create(class DigitalClock extends Clock { - - static get observedAttributes(){ - return ['foo']; - } - -}); - -xtag.register('x-clock2', DigitalClock); diff --git a/src/core.js b/src/core.js index a4193df..5682d97 100644 --- a/src/core.js +++ b/src/core.js @@ -1,866 +1,432 @@ -(function () { +(function(){ -/*** Variables ***/ + var docElement = document.documentElement; + (Element.prototype.matches || (Element.prototype.matches = docElement.webkitMatchesSelector || + docElement.msMatchesSelector || + docElement.oMatchesSelector)) - var win = window, - doc = document, - attrProto = { - setAttribute: Element.prototype.setAttribute, - removeAttribute: Element.prototype.removeAttribute - }, - hasShadow = Element.prototype.createShadowRoot, - container = doc.createElement('div'), - noop = function(){}, - trueop = function(){ return true; }, - regexReplaceCommas = /,/g, - regexCamelToDash = /([a-z])([A-Z])/g, - regexPseudoParens = /\(|\)/g, - regexPseudoCapture = /:(\w+)\u276A(.+?(?=\u276B))|:(\w+)/g, - regexDigits = /(\d+)/g, - keypseudo = { - action: function (pseudo, event) { - return pseudo.value.match(regexDigits).indexOf(String(event.keyCode)) > -1 == (pseudo.name == 'keypass') || null; - } - }, - /* - - The prefix object generated here is added to the xtag object as xtag.prefix later in the code - - Prefix provides a variety of prefix variations for the browser in which your code is running - - The 4 variations of prefix are as follows: - * prefix.dom: the correct prefix case and form when used on DOM elements/style properties - * prefix.lowercase: a lowercase version of the prefix for use in various user-code situations - * prefix.css: the lowercase, dashed version of the prefix - * prefix.js: addresses prefixed APIs present in global and non-Element contexts - */ - prefix = (function () { - var keys = Object.keys(Object.getPrototypeOf(window)).concat(Object.keys(window)).join(); - var pre = (keys.match(/,(ms|moz|O)/) || [null, 'webkit'])[1].toLowerCase(); - return { - dom: pre == 'ms' ? 'MS' : pre, - lowercase: pre, - css: '-' + pre + '-', - js: pre == 'ms' ? pre : pre.charAt(0).toUpperCase() + pre.substring(1) - }; - })(), - matchSelector = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype[prefix.lowercase + 'MatchesSelector']; - -/*** Functions ***/ - -// Utilities - - /* - This is an enhanced typeof check for all types of objects. Where typeof would normaly return - 'object' for many common DOM objects (like NodeLists and HTMLCollections). - - For example: typeOf(document.children) will correctly return 'htmlcollection' - */ - var typeCache = {}, - typeString = typeCache.toString, - typeRegexp = /\s([a-zA-Z]+)/; - function typeOf(obj) { - var type = typeString.call(obj); - return typeCache[type] || (typeCache[type] = type.match(typeRegexp)[1].toLowerCase()); - } - - function clone(item, type){ - var fn = clone[type || typeOf(item)]; - return fn ? fn(item) : item; - } - clone.object = function(src){ - var obj = {}; - for (var key in src) obj[key] = clone(src[key]); - return obj; - }; - clone.array = function(src){ - var i = src.length, array = new Array(i); - while (i--) array[i] = clone(src[i]); - return array; - }; - - /* - The toArray() method allows for conversion of any object to a true array. For types that - cannot be converted to an array, the method returns a 1 item array containing the passed-in object. - */ - var unsliceable = { 'undefined': 1, 'null': 1, 'number': 1, 'boolean': 1, 'string': 1, 'function': 1 }; - function toArray(obj){ - return unsliceable[typeOf(obj)] ? [obj] : Array.prototype.slice.call(obj, 0); - } - -// DOM - - var str = ''; - function query(element, selector){ - return (selector || str).length ? toArray(element.querySelectorAll(selector)) : []; - } - -// Pseudos - - function parsePseudo(fn){fn();} - -// Mixins - - function mergeOne(source, key, current){ - var type = typeOf(current); - if (type == 'object' && typeOf(source[key]) == 'object') xtag.merge(source[key], current); - else source[key] = clone(current, type); - return source; - } - - function mergeMixin(tag, original, mixin, name) { - var key, keys = {}; - for (var z in original) keys[z.split(':')[0]] = z; - for (z in mixin) { - key = keys[z.split(':')[0]]; - if (typeof original[key] == 'function') { - if (!key.match(':mixins')) { - original[key + ':mixins'] = original[key]; - delete original[key]; - key = key + ':mixins'; - } - original[key].__mixin__ = xtag.applyPseudos(z + (z.match(':mixins') ? '' : ':mixins'), mixin[z], tag.pseudos, original[key].__mixin__); - } - else { - original[z] = mixin[z]; - delete original[key]; - } - } - } - - var uniqueMixinCount = 0; - function addMixin(tag, original, mixin){ - for (var z in mixin){ - original[z + ':__mixin__(' + (uniqueMixinCount++) + ')'] = xtag.applyPseudos(z, mixin[z], tag.pseudos); - } - } - - function resolveMixins(mixins, output){ - var index = mixins.length; - while (index--){ - output.unshift(mixins[index]); - if (xtag.mixins[mixins[index]] && xtag.mixins[mixins[index]].mixins) resolveMixins(xtag.mixins[mixins[index]].mixins, output); - } - return output; - } - - function applyMixins(tag) { - resolveMixins(tag.mixins, []).forEach(function(name){ - var mixin = xtag.mixins[name]; - for (var type in mixin) { - var item = mixin[type], - original = tag[type]; - if (!original) tag[type] = item; - else { - switch (type){ - case 'mixins': break; - case 'events': addMixin(tag, original, item); break; - case 'accessors': - case 'prototype': - for (var z in item) { - if (!original[z]) original[z] = item[z]; - else mergeMixin(tag, original[z], item[z], name); - } - break; - default: mergeMixin(tag, original, item, name); - } - } - } - }); - return tag; - } - -// Events + var regexParseExt = /([\w\-]+)|(::|:)(\w+)(?:\((.+?(?=\)))\))?/g; + var regexCommaArgs = /,\s*/; + var regexCamel = /[A-Z]/g; + var dashLower = c => "-" + c.toLowerCase(); - function delegateAction(pseudo, event) { + function delegateAction(node, pseudo, event) { var match, target = event.target, root = event.currentTarget; while (!match && target && target != root) { - if (target.tagName && matchSelector.call(target, pseudo.value)) match = target; + if (target.tagName && target.matches(pseudo.args)) match = target; target = target.parentNode; } - if (!match && root.tagName && matchSelector.call(root, pseudo.value)) match = root; - return match ? pseudo.listener = pseudo.listener.bind(match) : null; - } - - function touchFilter(event){ - return event.button === 0; - } - - function writeProperty(key, event, base, desc){ - if (desc) event[key] = base[key]; - else Object.defineProperty(event, key, { - writable: true, - enumerable: true, - value: base[key] - }); - } - - var skipProps = {}; - for (var z in doc.createEvent('CustomEvent')) skipProps[z] = 1; - function inheritEvent(event, base){ - var desc = Object.getOwnPropertyDescriptor(event, 'target'); - for (var z in base) { - if (!skipProps[z]) writeProperty(z, event, base, desc); - } - event.baseEvent = base; - } - -// Accessors - - function modAttr(element, attr, name, value, method){ - attrProto[method].call(element, name, attr && attr.boolean ? '' : value); - } - - function syncAttr(element, attr, name, value, method){ - if (attr && (attr.property || attr.selector)) { - var nodes = attr.property ? [element.xtag[attr.property]] : attr.selector ? xtag.query(element, attr.selector) : [], - index = nodes.length; - while (index--) nodes[index][method](name, value); - } + if (!match && root.tagName && root.matches(pseudo.args)) match = root; + if (match) pseudo.fn = pseudo.fn.bind(match); + else return null; } - function attachProperties(tag, prop, z, accessor, attr, name){ - var key = z.split(':'), type = key[0]; - if (type == 'get') { - key[0] = prop; - tag.prototype[prop].get = xtag.applyPseudos(key.join(':'), accessor[z], tag.pseudos, accessor[z]); - } - else if (type == 'set') { - key[0] = prop; - var setter = tag.prototype[prop].set = xtag.applyPseudos(key.join(':'), attr ? function(value){ - var old, method = 'setAttribute'; - if (attr.boolean){ - value = !!value; - old = this.hasAttribute(name); - if (!value) method = 'removeAttribute'; - } - else { - value = attr.validate ? attr.validate.call(this, value) : value; - old = this.getAttribute(name); - } - modAttr(this, attr, name, value, method); - accessor[z].call(this, value, old); - syncAttr(this, attr, name, value, method); - } : accessor[z] ? function(value){ - accessor[z].call(this, value); - } : null, tag.pseudos, accessor[z]); - - if (attr) attr.setter = accessor[z]; - } - else tag.prototype[prop][z] = accessor[z]; - } - - function parseAccessor(tag, prop){ - tag.prototype[prop] = {}; - var accessor = tag.accessors[prop], - attr = accessor.attribute, - name; - - if (attr) { - name = attr.name = (attr ? (attr.name || prop.replace(regexCamelToDash, '$1-$2')) : prop).toLowerCase(); - attr.key = prop; - tag.attributes[name] = attr; - } - - for (var z in accessor) attachProperties(tag, prop, z, accessor, attr, name); - - if (attr) { - if (!tag.prototype[prop].get) { - var method = (attr.boolean ? 'has' : 'get') + 'Attribute'; - tag.prototype[prop].get = function(){ - return this[method](name); - }; - } - if (!tag.prototype[prop].set) tag.prototype[prop].set = function(value){ - value = attr.boolean ? !!value : attr.validate ? attr.validate.call(this, value) : value; - var method = attr.boolean ? (value ? 'setAttribute' : 'removeAttribute') : 'setAttribute'; - modAttr(this, attr, name, value, method); - syncAttr(this, attr, name, value, method); - }; - } - } - - var unwrapComment = /\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//; - function parseMultiline(fn){ - return typeof fn == 'function' ? unwrapComment.exec(fn.toString())[1] : fn; - } - -/*** X-Tag Object Definition ***/ - var xtag = { - tags: {}, - defaultOptions: { - pseudos: [], - mixins: [], - events: {}, - methods: {}, - accessors: {}, - lifecycle: {}, - attributes: {}, - 'prototype': { - xtag: { - get: function(){ - return this.__xtag__ ? this.__xtag__ : (this.__xtag__ = { data: {} }); - } - } + events: {}, + pseudos: { + delegate: { + onInvoke: delegateAction } }, - register: function (name, options) { - var _name; - if (typeof name == 'string') _name = name.toLowerCase(); - else throw 'First argument must be a Custom Element string name'; - xtag.tags[_name] = options || {}; - - var basePrototype = options.prototype; - delete options.prototype; - var tag = xtag.tags[_name].compiled = applyMixins(xtag.merge({}, xtag.defaultOptions, options)); - var proto = tag.prototype; - var lifecycle = tag.lifecycle; - - for (var z in tag.events) tag.events[z] = xtag.parseEvent(z, tag.events[z]); - for (z in lifecycle) lifecycle[z.split(':')[0]] = xtag.applyPseudos(z, lifecycle[z], tag.pseudos, lifecycle[z]); - for (z in tag.methods) proto[z.split(':')[0]] = { value: xtag.applyPseudos(z, tag.methods[z], tag.pseudos, tag.methods[z]), enumerable: true }; - for (z in tag.accessors) parseAccessor(tag, z); - - if (tag.shadow) tag.shadow = tag.shadow.nodeName ? tag.shadow : xtag.createFragment(tag.shadow); - if (tag.content) tag.content = tag.content.nodeName ? tag.content.innerHTML : parseMultiline(tag.content); - var created = lifecycle.created; - var finalized = lifecycle.finalized; - proto.createdCallback = { - enumerable: true, - value: function(){ - var element = this; - if (tag.shadow && hasShadow) this.createShadowRoot().appendChild(tag.shadow.cloneNode(true)); - if (tag.content) this.appendChild(document.createElement('div')).outerHTML = tag.content; - var output = created ? created.apply(this, arguments) : null; - xtag.addEvents(this, tag.events); - for (var name in tag.attributes) { - var attr = tag.attributes[name], - hasAttr = this.hasAttribute(name), - hasDefault = attr.def !== undefined; - if (hasAttr || attr.boolean || hasDefault) { - this[attr.key] = attr.boolean ? hasAttr : !hasAttr && hasDefault ? attr.def : this.getAttribute(name); - } - } - tag.pseudos.forEach(function(obj){ - obj.onAdd.call(element, obj); - }); - this.xtagComponentReady = true; - if (finalized) finalized.apply(this, arguments); - return output; + extensions: { + rxn: { + onParse (klass, prop, args, descriptor, key){ + delete klass.prototype[key]; + return false; + }, + onConstruct (node, property, args, descriptor){ + node.rxn(property, descriptor.value, !!args[1]); } - }; - - var inserted = lifecycle.inserted; - var removed = lifecycle.removed; - if (inserted || removed) { - proto.attachedCallback = { value: function(){ - if (removed) this.xtag.__parentNode__ = this.parentNode; - if (inserted) return inserted.apply(this, arguments); - }, enumerable: true }; - } - if (removed) { - proto.detachedCallback = { value: function(){ - var args = toArray(arguments); - args.unshift(this.xtag.__parentNode__); - var output = removed.apply(this, args); - delete this.xtag.__parentNode__; - return output; - }, enumerable: true }; - } - if (lifecycle.attributeChanged) proto.attributeChangedCallback = { value: lifecycle.attributeChanged, enumerable: true }; - - proto.setAttribute = { - writable: true, - enumerable: true, - value: function (name, value){ - var old; - var _name = name.toLowerCase(); - var attr = tag.attributes[_name]; - if (attr) { - old = this.getAttribute(_name); - value = attr.boolean ? '' : attr.validate ? attr.validate.call(this, value) : value; + }, + attr: { + mixin: (base) => class extends base { + attributeChangedCallback(attr, last, current){ + var desc = this.constructor.getOptions('attributes')[attr]; + if (desc && desc.set && !desc._skip) { + desc.set.call(this, current); + desc._skip = null; + } } - modAttr(this, attr, _name, value, 'setAttribute'); - if (attr) { - if (attr.setter) attr.setter.call(this, attr.boolean ? true : value, old); - syncAttr(this, attr, _name, value, 'setAttribute'); + }, + types: { + boolean: { + set: function(prop, val){ + val || val === '' ? this.setAttribute(prop, '') : this.removeAttribute(prop); + }, + get: function(prop){ + return this.hasAttribute(prop); + } } - } - }; - - proto.removeAttribute = { - writable: true, - enumerable: true, - value: function (name){ - var _name = name.toLowerCase(); - var attr = tag.attributes[_name]; - var old = this.hasAttribute(_name); - modAttr(this, attr, _name, '', 'removeAttribute'); - if (attr) { - if (attr.setter) attr.setter.call(this, attr.boolean ? false : undefined, old); - syncAttr(this, attr, _name, '', 'removeAttribute'); + }, + onParse (klass, prop, args, descriptor, key){ + if (descriptor.value) throw 'Attribute accessor "'+ prop +'" was declared as a value, but must be declared as get or set'; + var _prop = prop.replace(regexCamel, dashLower); + klass.getOptions('attributes')[_prop] = descriptor; + var type = this.types[args[0]] || {}; + let descSet = descriptor.set; + let typeSet = type.set || HTMLElement.prototype.setAttribute; + descriptor.set = function(val){ + if (!descriptor._skip){ + descriptor._skip = true; + var output; + if (descSet) output = descSet.call(this, val); + typeSet.call(this, _prop, typeof output == 'undefined' ? val : output); + descriptor._skip = null; + } } - } - }; - - var definition = {}; - var instance = basePrototype instanceof win.HTMLElement; - var extended = tag['extends'] && (definition['extends'] = tag['extends']); - - if (basePrototype) Object.getOwnPropertyNames(basePrototype).forEach(function(z){ - var prop = proto[z]; - var desc = instance ? Object.getOwnPropertyDescriptor(basePrototype, z) : basePrototype[z]; - if (prop) { - for (var y in desc) { - if (typeof desc[y] == 'function' && prop[y]) prop[y] = xtag.wrap(desc[y], prop[y]); - else prop[y] = desc[y]; + let descGet = descriptor.get; + let typeGet = type.get || HTMLElement.prototype.getAttribute; + descriptor.get = function(){ + var output; + var val = typeGet.call(this, _prop); + if (descGet) output = descGet.call(this, val); + return typeof output == 'undefined' ? val : output; } + delete klass.prototype[key]; + }, + onCompiled (klass){ + klass.observedAttributes = Object.keys(klass.getOptions('attributes')).concat(klass.observedAttributes || []) } - proto[z] = prop || desc; - }); - - definition['prototype'] = Object.create( - extended ? Object.create(doc.createElement(extended).constructor).prototype : win.HTMLElement.prototype, - proto - ); - - return doc.registerElement(_name, definition); - }, - - /* Exposed Variables */ - - mixins: {}, - prefix: prefix, - captureEvents: { focus: 1, blur: 1, scroll: 1, DOMMouseScroll: 1 }, - customEvents: { - animationstart: { - attach: [prefix.dom + 'AnimationStart'] - }, - animationend: { - attach: [prefix.dom + 'AnimationEnd'] }, - transitionend: { - attach: [prefix.dom + 'TransitionEnd'] - }, - move: { - attach: ['pointermove'] - }, - enter: { - attach: ['pointerenter'] - }, - leave: { - attach: ['pointerleave'] - }, - scrollwheel: { - attach: ['DOMMouseScroll', 'mousewheel'], - condition: function(event){ - event.delta = event.wheelDelta ? event.wheelDelta / 40 : Math.round(event.detail / 3.5 * -1); - return true; + event: { + onParse (klass, property, args, descriptor, key){ + delete klass.prototype[key]; + return false; + }, + onConstruct (node, property, args, descriptor){ + xtag.addEvent(node, property, descriptor.value); } }, - tap: { - attach: ['pointerdown', 'pointerup'], - condition: function(event, custom){ - if (event.type == 'pointerdown') { - custom.startX = event.clientX; - custom.startY = event.clientY; + template: { + throttle: { + frame: function (node, template, queued){ + queued.cancel = cancelAnimationFrame.bind(window, requestAnimationFrame(() => { + node._render(template, queued); + })) + }, + debounce: function (node, template, queued, options){ + queued.cancel = clearTimeout.bind(window, setTimeout(() => { + node_.render(template, queued); + }, options.throttle)) } - else if (event.button === 0 && - Math.abs(custom.startX - event.clientX) < 10 && - Math.abs(custom.startY - event.clientY) < 10) return true; - } - }, - tapstart: { - attach: ['pointerdown'], - condition: touchFilter - }, - tapend: { - attach: ['pointerup'], - condition: touchFilter - }, - tapmove: { - attach: ['pointerdown'], - condition: function(event, custom){ - if (event.type == 'pointerdown') { - var listener = custom.listener.bind(this); - if (!custom.tapmoveListeners) custom.tapmoveListeners = xtag.addEvents(document, { - pointermove: listener, - pointerup: listener, - pointercancel: listener - }); + }, + mixin: (base) => class extends base { + set 'template::attr' (name){ + this.render(name); } - else if (event.type == 'pointerup' || event.type == 'pointercancel') { - xtag.removeEvents(document, custom.tapmoveListeners); - custom.tapmoveListeners = null; + get templates (){ + return this.constructor.getOptions('templates'); } - return true; - } - }, - taphold: { - attach: ['pointerdown', 'pointerup'], - condition: function(event, custom){ - if (event.type == 'pointerdown') { - (custom.pointers = custom.pointers || {})[event.pointerId] = setTimeout( - xtag.fireEvent.bind(null, this, 'taphold'), - custom.duration || 1000 - ); + _render (template, queued){ + this.innerHTML = template.call(this); + this._XTagRender = null; + if (queued.resolve) queued.resolve(this); } - else if (event.type == 'pointerup') { - if (custom.pointers) { - clearTimeout(custom.pointers[event.pointerId]); - delete custom.pointers[event.pointerId]; + render (name, options = {}){ + var _name = name || 'default'; + var template = this.templates[_name]; + if (!template) { + throw new ReferenceError('Template "' + _name + '" undefined for ' + this.nodeName); + } + var queued = this._XTagRender; + if (queued) { + if (queued.name === _name) return queued.promise; + else if (queued.cancel) queued.cancel(); + } + if (this.getAttribute('template') != _name) this.setAttribute('template', _name); + queued = this._XTagRender = { name: _name }; + var ext = xtag.extensions.template.throttle; + var throttle = (options.throttle ? ext[options.throttle] || ext.debounce : false); + if (throttle) { + return queued.promise = new Promise(resolve => { + queued.resolve = resolve; + throttle(this, template, queued, options); + }); + } + else { + this._render(template, queued); + return Promise.resolve(this); } } - else return true; - } - } - }, - pseudos: { - __mixin__: {}, - mixins: { - onCompiled: function(fn, pseudo){ - var mixin = pseudo.source && pseudo.source.__mixin__ || pseudo.source; - if (mixin) switch (pseudo.value) { - case null: case '': case 'before': return function(){ - mixin.apply(this, arguments); - return fn.apply(this, arguments); - }; - case 'after': return function(){ - var returns = fn.apply(this, arguments); - mixin.apply(this, arguments); - return returns; - }; - case 'none': return fn; + }, + onParse (klass, property, args, descriptor){ + klass.getOptions('templates')[property || 'default'] = descriptor.value; + return false; + }, + onReady (node, resolve, property, args){ + if (args[0]) { + if (args[0] === 'ready') node.render(property); + else node.rxn('firstpaint', () => node.render(property)); } - else return fn; - } - }, - keypass: keypseudo, - keyfail: keypseudo, - delegate: { - action: delegateAction - }, - preventable: { - action: function (pseudo, event) { - return !event.defaultPrevented; + resolve(); } - }, - duration: { - onAdd: function(pseudo){ - pseudo.source.duration = Number(pseudo.value); - } - }, - capture: { - onCompiled: function(fn, pseudo){ - if (pseudo.source) pseudo.source.capture = true; - } - } - }, - - /* UTILITIES */ - - clone: clone, - typeOf: typeOf, - toArray: toArray, - - wrap: function (original, fn) { - return function(){ - var output = original.apply(this, arguments); - fn.apply(this, arguments); - return output; - }; - }, - /* - Recursively merges one object with another. The first argument is the destination object, - all other objects passed in as arguments are merged from right to left, conflicts are overwritten - */ - merge: function(source, k, v){ - if (typeOf(k) == 'string') return mergeOne(source, k, v); - for (var i = 1, l = arguments.length; i < l; i++){ - var object = arguments[i]; - for (var key in object) mergeOne(source, key, object[key]); } - return source; - }, - - /* - ----- This should be simplified! ----- - Generates a random ID string - */ - uid: function(){ - return Math.random().toString(36).substr(2,10); - }, - - /* DOM */ - - query: query, - - skipTransition: function(element, fn, bind){ - var prop = prefix.js + 'TransitionProperty'; - element.style[prop] = element.style.transitionProperty = 'none'; - var callback = fn ? fn.call(bind || element) : null; - return xtag.skipFrame(function(){ - element.style[prop] = element.style.transitionProperty = ''; - if (callback) callback.call(bind || element); - }); - }, - - requestFrame: (function(){ - var raf = win.requestAnimationFrame || - win[prefix.lowercase + 'RequestAnimationFrame'] || - function(fn){ return win.setTimeout(fn, 20); }; - return function(fn){ return raf(fn); }; - })(), - - cancelFrame: (function(){ - var cancel = win.cancelAnimationFrame || - win[prefix.lowercase + 'CancelAnimationFrame'] || - win.clearTimeout; - return function(id){ return cancel(id); }; - })(), - - skipFrame: function(fn){ - var id = xtag.requestFrame(function(){ id = xtag.requestFrame(fn); }); - return id; }, - - matchSelector: function (element, selector) { - return matchSelector.call(element, selector); + create (name, klass){ + var c = klass || name; + c.options = Object.assign({}, c.options); + onParse(c); + if (klass && name) customElements.define(name, c); + return c; }, - - set: function (element, method, value) { - element[method] = value; - if (window.CustomElements) CustomElements.upgradeAll(element); + register (name, klass) { + customElements.define(name, klass); }, - - innerHTML: function(el, html){ - xtag.set(el, 'innerHTML', html); + addEvents (node, events){ + let refs = {}; + for (let z in events) refs[z] = xtag.addEvent(node, z, events[z]); + return refs; }, - - hasClass: function (element, klass) { - return element.className.split(' ').indexOf(klass.trim())>-1; - }, - - addClass: function (element, klass) { - var list = element.className.trim().split(' '); - klass.trim().split(' ').forEach(function (name) { - if (!~list.indexOf(name)) list.push(name); + addEvent (node, key, fn, options){ + var type; + var stack = fn; + var ref = options || {}; + ref.data = {}; + key.replace(regexParseExt, (match, name, dots, pseudo, args) => { + if (name) type = name; + else if (dots == ':'){ + var pseudo = xtag.pseudos[pseudo]; + var _args = args ? args.split(regexCommaArgs) : []; + stack = pseudoWrap(pseudo, _args, stack, ref); + if (pseudo.onParse) pseudo.onParse(node, type, _args, stack, ref); + } }); - element.className = list.join(' ').trim(); - return element; + node.addEventListener(type, stack, ref); + ref.type = type; + ref.listener = stack; + var event = xtag.events[type]; + if (event) { + var listener = function(e){ + new Promise(resolve => { + event.onFilter ? event.onFilter(this, e, ref, resolve) : resolve(); + }).then(() => { + let fired = '_' + type + 'EventFired'; + if (!e[fired]) { + e[fired] = true; + xtag.fireEvent(e.target || this, type); + } + }) + } + ref.attached = event.attach.map(key => { + return xtag.addEvent(node, key, listener, {capture: true}); + }); + if (event.onAdd) event.onAdd(node, ref); + } + return ref; }, - - removeClass: function (element, klass) { - var classes = klass.trim().split(' '); - element.className = element.className.trim().split(' ').filter(function (name) { - return name && !~classes.indexOf(name); - }).join(' '); - return element; + removeEvents (node, refs) { + for (let z in refs) xtag.removeEvent(node, refs[z]); }, - - toggleClass: function (element, klass) { - return xtag[xtag.hasClass(element, klass) ? 'removeClass' : 'addClass'].call(null, element, klass); + removeEvent (node, ref){ + node.removeEventListener(ref.type, ref.listener, ref.capture); + var event = xtag.events[ref.type]; + if (event && event.onRemove) event.onRemove(node, ref); + if (ref.attached) ref.attached.forEach(attached => { xtag.removeEvent(node, ref) }) }, + fireEvent (node, name, obj = {}){ + let options = Object.assign({ + bubbles: true, + cancelable: true + }, obj); + node.dispatchEvent(new CustomEvent(name, options)); + } + } - /* - Runs a query on only the children of an element - */ - queryChildren: function (element, selector) { - var id = element.id, - attr = '#' + (element.id = id || 'x_' + xtag.uid()) + ' > ', - parent = element.parentNode || !container.appendChild(element); - selector = attr + (selector + '').replace(regexReplaceCommas, ',' + attr); - var result = element.parentNode.querySelectorAll(selector); - if (!id) element.removeAttribute('id'); - if (!parent) container.removeChild(element); - return toArray(result); - }, + var rxnID = 0; + function processRxns(node, type){ + var rxn = node.rxns[type]; + var queue = rxn.queue; + for (let z in queue) { + queue[z].fn.call(node); + if (rxn.singleton || !queue[z].recurring) delete queue[z]; + } + rxn.fired = true; + } - /* - Creates a document fragment with the content passed in - content can be - a string of HTML, an element, or an array/collection of elements - */ - createFragment: function(content) { - var template = document.createElement('template'); - if (content) { - if (content.nodeName) toArray(arguments).forEach(function(e){ - template.content.appendChild(e); + function createClass(options = {}){ + var klass; + klass = class extends (options.native ? Object.getPrototypeOf(document.createElement(options.native)).constructor : HTMLElement) { + constructor () { + super(); + if (!this.rxns) this.rxns = { + ready: { queue: {}, singleton: true }, + firstpaint: { queue: {}, singleton: true }, + render: { queue: {} } + }; + onConstruct(this); + new Promise(resolve => onReady(this, resolve)).then(() => { + processRxns(this, 'ready') + if (this.readyCallback) this.readyCallback(); }); - else template.innerHTML = parseMultiline(content); } - return document.importNode(template.content, true); - }, - /* - Removes an element from the DOM for more performant node manipulation. The element - is placed back into the DOM at the place it was taken from. - */ - manipulate: function(element, fn){ - var next = element.nextSibling, - parent = element.parentNode, - returned = fn.call(element) || element; - if (next) parent.insertBefore(returned, next); - else parent.appendChild(returned); - }, - - /* PSEUDOS */ - - applyPseudos: function(key, fn, target, source) { - var listener = fn, - pseudos = {}; - if (key.match(':')) { - var matches = [], - valueFlag = 0; - key.replace(regexPseudoParens, function(match){ - if (match == '(') return ++valueFlag == 1 ? '\u276A' : '('; - return !--valueFlag ? '\u276B' : ')'; - }).replace(regexPseudoCapture, function(z, name, value, solo){ - matches.push([name || solo, value]); - }); - var i = matches.length; - while (i--) parsePseudo(function(){ - var name = matches[i][0], - value = matches[i][1]; - if (!xtag.pseudos[name]) throw "pseudo not found: " + name + " " + value; - value = (value === '' || typeof value == 'undefined') ? null : value; - var pseudo = pseudos[i] = Object.create(xtag.pseudos[name]); - pseudo.key = key; - pseudo.name = name; - pseudo.value = value; - pseudo['arguments'] = (value || '').split(','); - pseudo.action = pseudo.action || trueop; - pseudo.source = source; - pseudo.onAdd = pseudo.onAdd || noop; - pseudo.onRemove = pseudo.onRemove || noop; - var original = pseudo.listener = listener; - listener = function(){ - var output = pseudo.action.apply(this, [pseudo].concat(toArray(arguments))); - if (output === null || output === false) return output; - output = pseudo.listener.apply(this, arguments); - pseudo.listener = original; - return output; - }; - if (!target) pseudo.onAdd.call(fn, pseudo); - else target.push(pseudo); - }); + connectedCallback () { + onConnect(this); + if (!this.rxns.firstpaint.frame) { + this.rxns.firstpaint.frame = requestAnimationFrame(() => processRxns(this, 'firstpaint')); + } + } + + rxn (type, fn, recurring){ + var rxn = this.rxns[type]; + if (rxn.singleton && rxn.fired) fn.call(this); + else { + rxn.queue[rxnID++] = { fn: fn, recurring: recurring }; + return rxnID; + } } - for (var z in pseudos) { - if (pseudos[z].onCompiled) listener = pseudos[z].onCompiled(listener, pseudos[z]) || listener; + + cancelRxn (type, id){ + delete this.rxns[type].queue[id]; } - return listener; - }, - - removePseudos: function(target, pseudos){ - pseudos.forEach(function(obj){ - obj.onRemove.call(target, obj); - }); - }, + }; - /*** Events ***/ + klass.options = { + extensions: {}, + pseudos: {} + }; + + klass.getOptions = function(name){ + return this.options[name] || (this.options[name] = Object.assign({}, Object.getPrototypeOf(this).options ? Object.getPrototypeOf(this).options[name] : {})); + } - parseEvent: function(type, fn) { - var pseudos = type.split(':'), - key = pseudos.shift(), - custom = xtag.customEvents[key], - event = xtag.merge({ - type: key, - stack: noop, - condition: trueop, - capture: xtag.captureEvents[key], - attach: [], - _attach: [], - pseudos: '', - _pseudos: [], - onAdd: noop, - onRemove: noop - }, custom || {}); - event.attach = toArray(event.base || event.attach); - event.chain = key + (event.pseudos.length ? ':' + event.pseudos : '') + (pseudos.length ? ':' + pseudos.join(':') : ''); - var stack = xtag.applyPseudos(event.chain, fn, event._pseudos, event); - event.stack = function(e){ - e.currentTarget = e.currentTarget || this; - var detail = e.detail || {}; - if (!detail.__stack__) return stack.apply(this, arguments); - else if (detail.__stack__ == stack) { - e.stopPropagation(); - e.cancelBubble = true; - return stack.apply(this, arguments); - } - }; - event.listener = function(e){ - var args = toArray(arguments), - output = event.condition.apply(this, args.concat([event])); - if (!output) return output; - // The second condition in this IF is to address the following Blink regression: https://code.google.com/p/chromium/issues/detail?id=367537 - // Remove this when affected browser builds with this regression fall below 5% marketshare - if (e.type != key && (e.baseEvent && e.type != e.baseEvent.type)) { - xtag.fireEvent(e.target, key, { - baseEvent: e, - detail: output !== true && (output.__stack__ = stack) ? output : { __stack__: stack } - }); + klass.extensions = function extensions(...extensions){ + var exts = this.getOptions('extensions'); + return extensions.reduce((current, extension) => { + var mixin; + var extended = current; + if (!exts[extension.name]) { + if (typeof extension == 'string') { + mixin = xtag.extensions[extension].mixin; + } + else { + mixin = extension.mixin; + exts[extension.name] = extension; + } + if (mixin) { + extended = mixin(current); + onParse(extended); + } } - else return event.stack.apply(this, args); - }; - event.attach.forEach(function(name) { - event._attach.push(xtag.parseEvent(name, event.listener)); - }); - return event; - }, + return extended; + }, this); + } - addEvent: function (element, type, fn, capture) { - var event = typeof fn == 'function' ? xtag.parseEvent(type, fn) : fn; - event._pseudos.forEach(function(obj){ - obj.onAdd.call(element, obj); - }); - event._attach.forEach(function(obj) { - xtag.addEvent(element, obj.type, obj); + klass.as = function(tag){ + return createClass({ + native: tag }); - event.onAdd.call(element, event, event.listener); - element.addEventListener(event.type, event.stack, capture || event.capture); - return event; - }, + } - addEvents: function (element, obj) { - var events = {}; - for (var z in obj) { - events[z] = xtag.addEvent(element, z, obj[z]); - } - return events; - }, + return klass.extensions('attr', 'event', 'template'); + } - removeEvent: function (element, type, event) { - event = event || type; - event.onRemove.call(element, event, event.listener); - xtag.removePseudos(element, event._pseudos); - event._attach.forEach(function(obj) { - xtag.removeEvent(element, obj); - }); - element.removeEventListener(event.type, event.stack); - }, + XTagElement = createClass(); - removeEvents: function(element, obj){ - for (var z in obj) xtag.removeEvent(element, obj[z]); - }, + function pseudoWrap(pseudo, args, fn, detail){ + return function(){ + var _pseudo = { fn: fn, args: args, detail: detail }; + var output = pseudo.onInvoke(this, _pseudo, ...arguments); + if (output === null || output === false) return output; + return _pseudo.fn.apply(this, output instanceof Array ? output : arguments); + }; + } - fireEvent: function(element, type, options){ - var event = doc.createEvent('CustomEvent'); - options = options || {}; - event.initCustomEvent(type, - options.bubbles !== false, - options.cancelable !== false, - options.detail - ); - if (options.baseEvent) inheritEvent(event, options.baseEvent); - element.dispatchEvent(event); + function onParse(target){ + var processedProps = {}; + var descriptors = getDescriptors(target); + var extensions = target.getOptions('extensions'); + var processed = target._processedExtensions = new Map(); + for (let z in descriptors) { + let matches = []; + let property; + let extension; + let extensionArgs = []; + let descriptor = descriptors[z]; + let pseudos = target._pseudos || xtag.pseudos; + z.replace(regexParseExt, function(){ matches.unshift(arguments); }); + matches.forEach(a => function(match, prop, dots, name, args){ + property = prop || property; + if (args) var _args = args.split(regexCommaArgs); + if (dots == '::') { + extensionArgs = _args || []; + extension = extensions[name] || xtag.extensions[name]; + if (!processed.get(extension)) processed.set(extension, []); + } + else if (!prop){ + let pseudo = pseudos[name]; + if (pseudo) { + for (let y in descriptor) { + let fn = descriptor[y]; + if (typeof fn == 'function' && pseudo.onInvoke) { + fn = descriptor[y] = pseudoWrap(pseudo, _args, fn); + if (pseudo.onParse) pseudo.onParse(target, property, _args, fn); + } + } + } + } + }.apply(null, a)); + let attachProperty; + if (extension) { + processed.get(extension).push([property, extensionArgs, descriptor]); + if (extension.onParse) attachProperty = extension.onParse(target, property, extensionArgs, descriptor, z); + } + if (!property) delete target.prototype[z]; + else if (attachProperty !== false) { + let prop = processedProps[property] || (processedProps[property] = {}); + for (let y in descriptor) prop[y] = descriptor[y]; + } + } + for (let ext of processed.keys()) { + if (ext.onCompiled) ext.onCompiled(target, processedProps); } + Object.defineProperties(target.prototype, processedProps); + } - }; + function onConstruct (target){ + var processed = target.constructor._processedExtensions; + for (let [ext, items] of processed) { + if (ext.onConstruct) items.forEach(item => ext.onConstruct(target, ...item)) + } + } - if (typeof define === 'function' && define.amd) define(xtag); - else if (typeof module !== 'undefined' && module.exports) module.exports = xtag; - else win.xtag = xtag; + function onReady (target, resolve){ + var processed = target.constructor._processedExtensions; + for (let [ext, items] of processed) { + if (ext.onReady) Promise.all(items.map(item => { + return new Promise(resolve => ext.onReady(target, resolve, ...item)) + })).then(resolve) + } + } + + function onConnect (target){ + var processed = target.constructor._processedExtensions; + for (let [ext, items] of processed) { + if (ext.onConnect) items.forEach(item => ext.onConnect(target, ...item)) + } + } - doc.addEventListener('WebComponentsReady', function(){ - xtag.fireEvent(doc.body, 'DOMComponentsLoaded'); - }); + function getDescriptors(target){ + var descriptors = {}; + var proto = target.prototype; + Object.getOwnPropertyNames(proto).forEach(key => { + descriptors[key] = Object.getOwnPropertyDescriptor(proto, key); + }); + return descriptors; + } + + if (typeof define === 'function' && define.amd) { + define(xtag); + define(XTagElement); + } + else if (typeof module !== 'undefined' && module.exports) { + module.exports = { xtag: xtag, XTagElement: XTagElement }; + } + else { + window.xtag = xtag; + window.XTagElement = XTagElement; + } -})(); +})(); \ No newline at end of file diff --git a/test/events.html b/test/events.html deleted file mode 100644 index 6976c1f..0000000 --- a/test/events.html +++ /dev/null @@ -1,174 +0,0 @@ - - - - - X-Tag: Event Tester - - - - - - - - - - - -
    -
  • -
- -
- -
    -
  • -
- -
- -
- -
- -
- -
- - - - - - diff --git a/test/index.html b/test/index.html deleted file mode 100644 index 0eb2c39..0000000 --- a/test/index.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - X-Tag: Jasmine Spec Runner - - - - - - - - - - - - - - -
- - -
- - diff --git a/test/jasmine/lib/MIT.LICENSE b/test/jasmine/lib/MIT.LICENSE deleted file mode 100644 index 7c435ba..0000000 --- a/test/jasmine/lib/MIT.LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008-2011 Pivotal Labs - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/test/jasmine/lib/jasmine-1.2.0/MIT.LICENSE b/test/jasmine/lib/jasmine-1.2.0/MIT.LICENSE deleted file mode 100644 index 7c435ba..0000000 --- a/test/jasmine/lib/jasmine-1.2.0/MIT.LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008-2011 Pivotal Labs - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/test/jasmine/lib/jasmine-1.2.0/jasmine-html.js b/test/jasmine/lib/jasmine-1.2.0/jasmine-html.js deleted file mode 100644 index a0b0639..0000000 --- a/test/jasmine/lib/jasmine-1.2.0/jasmine-html.js +++ /dev/null @@ -1,616 +0,0 @@ -jasmine.HtmlReporterHelpers = {}; - -jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) { - var el = document.createElement(type); - - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - - if (typeof child === 'string') { - el.appendChild(document.createTextNode(child)); - } else { - if (child) { - el.appendChild(child); - } - } - } - - for (var attr in attrs) { - if (attr == "className") { - el[attr] = attrs[attr]; - } else { - el.setAttribute(attr, attrs[attr]); - } - } - - return el; -}; - -jasmine.HtmlReporterHelpers.getSpecStatus = function(child) { - var results = child.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.skipped) { - status = 'skipped'; - } - - return status; -}; - -jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) { - var parentDiv = this.dom.summary; - var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite'; - var parent = child[parentSuite]; - - if (parent) { - if (typeof this.views.suites[parent.id] == 'undefined') { - this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views); - } - parentDiv = this.views.suites[parent.id].element; - } - - parentDiv.appendChild(childElement); -}; - - -jasmine.HtmlReporterHelpers.addHelpers = function(ctor) { - for(var fn in jasmine.HtmlReporterHelpers) { - ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn]; - } -}; - -jasmine.HtmlReporter = function(_doc) { - var self = this; - var doc = _doc || window.document; - - var reporterView; - - var dom = {}; - - // Jasmine Reporter Public Interface - self.logRunningSpecs = false; - - self.reportRunnerStarting = function(runner) { - var specs = runner.specs() || []; - - if (specs.length == 0) { - return; - } - - createReporterDom(runner.env.versionString()); - doc.body.appendChild(dom.reporter); - - reporterView = new jasmine.HtmlReporter.ReporterView(dom); - reporterView.addSpecs(specs, self.specFilter); - }; - - self.reportRunnerResults = function(runner) { - reporterView && reporterView.complete(); - }; - - self.reportSuiteResults = function(suite) { - reporterView.suiteComplete(suite); - }; - - self.reportSpecStarting = function(spec) { - if (self.logRunningSpecs) { - self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); - } - }; - - self.reportSpecResults = function(spec) { - reporterView.specComplete(spec); - }; - - self.log = function() { - var console = jasmine.getGlobal().console; - if (console && console.log) { - if (console.log.apply) { - console.log.apply(console, arguments); - } else { - console.log(arguments); // ie fix: console.log.apply doesn't exist on ie - } - } - }; - - self.specFilter = function(spec) { - if (!focusedSpecName()) { - return true; - } - - return spec.getFullName().indexOf(focusedSpecName()) === 0; - }; - - return self; - - function focusedSpecName() { - var specName; - - (function memoizeFocusedSpec() { - if (specName) { - return; - } - - var paramMap = []; - var params = doc.location.search.substring(1).split('&'); - - for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); - } - - specName = paramMap.spec; - })(); - - return specName; - } - - function createReporterDom(version) { - dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' }, - dom.banner = self.createDom('div', { className: 'banner' }, - self.createDom('span', { className: 'title' }, "Jasmine "), - self.createDom('span', { className: 'version' }, version)), - - dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}), - dom.alert = self.createDom('div', {className: 'alert'}), - dom.results = self.createDom('div', {className: 'results'}, - dom.summary = self.createDom('div', { className: 'summary' }), - dom.details = self.createDom('div', { id: 'details' })) - ); - } -}; -jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);jasmine.HtmlReporter.ReporterView = function(dom) { - this.startedAt = new Date(); - this.runningSpecCount = 0; - this.completeSpecCount = 0; - this.passedCount = 0; - this.failedCount = 0; - this.skippedCount = 0; - - this.createResultsMenu = function() { - this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'}, - this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'), - ' | ', - this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing')); - - this.summaryMenuItem.onclick = function() { - dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, ''); - }; - - this.detailsMenuItem.onclick = function() { - showDetails(); - }; - }; - - this.addSpecs = function(specs, specFilter) { - this.totalSpecCount = specs.length; - - this.views = { - specs: {}, - suites: {} - }; - - for (var i = 0; i < specs.length; i++) { - var spec = specs[i]; - this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views); - if (specFilter(spec)) { - this.runningSpecCount++; - } - } - }; - - this.specComplete = function(spec) { - this.completeSpecCount++; - - if (isUndefined(this.views.specs[spec.id])) { - this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom); - } - - var specView = this.views.specs[spec.id]; - - switch (specView.status()) { - case 'passed': - this.passedCount++; - break; - - case 'failed': - this.failedCount++; - break; - - case 'skipped': - this.skippedCount++; - break; - } - - specView.refresh(); - this.refresh(); - }; - - this.suiteComplete = function(suite) { - var suiteView = this.views.suites[suite.id]; - if (isUndefined(suiteView)) { - return; - } - suiteView.refresh(); - }; - - this.refresh = function() { - - if (isUndefined(this.resultsMenu)) { - this.createResultsMenu(); - } - - // currently running UI - if (isUndefined(this.runningAlert)) { - this.runningAlert = this.createDom('a', {href: "?", className: "runningAlert bar"}); - dom.alert.appendChild(this.runningAlert); - } - this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount); - - // skipped specs UI - if (isUndefined(this.skippedAlert)) { - this.skippedAlert = this.createDom('a', {href: "?", className: "skippedAlert bar"}); - } - - this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; - - if (this.skippedCount === 1 && isDefined(dom.alert)) { - dom.alert.appendChild(this.skippedAlert); - } - - // passing specs UI - if (isUndefined(this.passedAlert)) { - this.passedAlert = this.createDom('span', {href: "?", className: "passingAlert bar"}); - } - this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount); - - // failing specs UI - if (isUndefined(this.failedAlert)) { - this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"}); - } - this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount); - - if (this.failedCount === 1 && isDefined(dom.alert)) { - dom.alert.appendChild(this.failedAlert); - dom.alert.appendChild(this.resultsMenu); - } - - // summary info - this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount); - this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing"; - }; - - this.complete = function() { - dom.alert.removeChild(this.runningAlert); - - this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; - - if (this.failedCount === 0) { - dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount))); - } else { - showDetails(); - } - - dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s")); - }; - - return this; - - function showDetails() { - if (dom.reporter.className.search(/showDetails/) === -1) { - dom.reporter.className += " showDetails"; - } - } - - function isUndefined(obj) { - return typeof obj === 'undefined'; - } - - function isDefined(obj) { - return !isUndefined(obj); - } - - function specPluralizedFor(count) { - var str = count + " spec"; - if (count > 1) { - str += "s" - } - return str; - } - -}; - -jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView); - - -jasmine.HtmlReporter.SpecView = function(spec, dom, views) { - this.spec = spec; - this.dom = dom; - this.views = views; - - this.symbol = this.createDom('li', { className: 'pending' }); - this.dom.symbolSummary.appendChild(this.symbol); - - this.summary = this.createDom('div', { className: 'specSummary' }, - this.createDom('a', { - className: 'description', - href: '?spec=' + encodeURIComponent(this.spec.getFullName()), - title: this.spec.getFullName() - }, this.spec.description) - ); - - this.detail = this.createDom('div', { className: 'specDetail' }, - this.createDom('a', { - className: 'description', - href: '?spec=' + encodeURIComponent(this.spec.getFullName()), - title: this.spec.getFullName() - }, this.spec.getFullName()) - ); -}; - -jasmine.HtmlReporter.SpecView.prototype.status = function() { - return this.getSpecStatus(this.spec); -}; - -jasmine.HtmlReporter.SpecView.prototype.refresh = function() { - this.symbol.className = this.status(); - - switch (this.status()) { - case 'skipped': - break; - - case 'passed': - this.appendSummaryToSuiteDiv(); - break; - - case 'failed': - this.appendSummaryToSuiteDiv(); - this.appendFailureDetail(); - break; - } -}; - -jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() { - this.summary.className += ' ' + this.status(); - this.appendToSummary(this.spec, this.summary); -}; - -jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() { - this.detail.className += ' ' + this.status(); - - var resultItems = this.spec.results().getItems(); - var messagesDiv = this.createDom('div', { className: 'messages' }); - - for (var i = 0; i < resultItems.length; i++) { - var result = resultItems[i]; - - if (result.type == 'log') { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); - } else if (result.type == 'expect' && result.passed && !result.passed()) { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); - - if (result.trace.stack) { - messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); - } - } - } - - if (messagesDiv.childNodes.length > 0) { - this.detail.appendChild(messagesDiv); - this.dom.details.appendChild(this.detail); - } -}; - -jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) { - this.suite = suite; - this.dom = dom; - this.views = views; - - this.element = this.createDom('div', { className: 'suite' }, - this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.suite.getFullName()) }, this.suite.description) - ); - - this.appendToSummary(this.suite, this.element); -}; - -jasmine.HtmlReporter.SuiteView.prototype.status = function() { - return this.getSpecStatus(this.suite); -}; - -jasmine.HtmlReporter.SuiteView.prototype.refresh = function() { - this.element.className += " " + this.status(); -}; - -jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView); - -/* @deprecated Use jasmine.HtmlReporter instead - */ -jasmine.TrivialReporter = function(doc) { - this.document = doc || document; - this.suiteDivs = {}; - this.logRunningSpecs = false; -}; - -jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { - var el = document.createElement(type); - - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - - if (typeof child === 'string') { - el.appendChild(document.createTextNode(child)); - } else { - if (child) { el.appendChild(child); } - } - } - - for (var attr in attrs) { - if (attr == "className") { - el[attr] = attrs[attr]; - } else { - el.setAttribute(attr, attrs[attr]); - } - } - - return el; -}; - -jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { - var showPassed, showSkipped; - - this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' }, - this.createDom('div', { className: 'banner' }, - this.createDom('div', { className: 'logo' }, - this.createDom('span', { className: 'title' }, "Jasmine"), - this.createDom('span', { className: 'version' }, runner.env.versionString())), - this.createDom('div', { className: 'options' }, - "Show ", - showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), - showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") - ) - ), - - this.runnerDiv = this.createDom('div', { className: 'runner running' }, - this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), - this.runnerMessageSpan = this.createDom('span', {}, "Running..."), - this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) - ); - - this.document.body.appendChild(this.outerDiv); - - var suites = runner.suites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - var suiteDiv = this.createDom('div', { className: 'suite' }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), - this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); - this.suiteDivs[suite.id] = suiteDiv; - var parentDiv = this.outerDiv; - if (suite.parentSuite) { - parentDiv = this.suiteDivs[suite.parentSuite.id]; - } - parentDiv.appendChild(suiteDiv); - } - - this.startedAt = new Date(); - - var self = this; - showPassed.onclick = function(evt) { - if (showPassed.checked) { - self.outerDiv.className += ' show-passed'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); - } - }; - - showSkipped.onclick = function(evt) { - if (showSkipped.checked) { - self.outerDiv.className += ' show-skipped'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); - } - }; -}; - -jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { - var results = runner.results(); - var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; - this.runnerDiv.setAttribute("class", className); - //do it twice for IE - this.runnerDiv.setAttribute("className", className); - var specs = runner.specs(); - var specCount = 0; - for (var i = 0; i < specs.length; i++) { - if (this.specFilter(specs[i])) { - specCount++; - } - } - var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); - message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; - this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); - - this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); -}; - -jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { - var results = suite.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.totalCount === 0) { // todo: change this to check results.skipped - status = 'skipped'; - } - this.suiteDivs[suite.id].className += " " + status; -}; - -jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { - if (this.logRunningSpecs) { - this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); - } -}; - -jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { - var results = spec.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.skipped) { - status = 'skipped'; - } - var specDiv = this.createDom('div', { className: 'spec ' + status }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), - this.createDom('a', { - className: 'description', - href: '?spec=' + encodeURIComponent(spec.getFullName()), - title: spec.getFullName() - }, spec.description)); - - - var resultItems = results.getItems(); - var messagesDiv = this.createDom('div', { className: 'messages' }); - for (var i = 0; i < resultItems.length; i++) { - var result = resultItems[i]; - - if (result.type == 'log') { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); - } else if (result.type == 'expect' && result.passed && !result.passed()) { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); - - if (result.trace.stack) { - messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); - } - } - } - - if (messagesDiv.childNodes.length > 0) { - specDiv.appendChild(messagesDiv); - } - - this.suiteDivs[spec.suite.id].appendChild(specDiv); -}; - -jasmine.TrivialReporter.prototype.log = function() { - var console = jasmine.getGlobal().console; - if (console && console.log) { - if (console.log.apply) { - console.log.apply(console, arguments); - } else { - console.log(arguments); // ie fix: console.log.apply doesn't exist on ie - } - } -}; - -jasmine.TrivialReporter.prototype.getLocation = function() { - return this.document.location; -}; - -jasmine.TrivialReporter.prototype.specFilter = function(spec) { - var paramMap = {}; - var params = this.getLocation().search.substring(1).split('&'); - for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); - } - - if (!paramMap.spec) { - return true; - } - return spec.getFullName().indexOf(paramMap.spec) === 0; -}; diff --git a/test/jasmine/lib/jasmine-1.2.0/jasmine.css b/test/jasmine/lib/jasmine-1.2.0/jasmine.css deleted file mode 100644 index 826e575..0000000 --- a/test/jasmine/lib/jasmine-1.2.0/jasmine.css +++ /dev/null @@ -1,81 +0,0 @@ -body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; } - -#HTMLReporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; } -#HTMLReporter a { text-decoration: none; } -#HTMLReporter a:hover { text-decoration: underline; } -#HTMLReporter p, #HTMLReporter h1, #HTMLReporter h2, #HTMLReporter h3, #HTMLReporter h4, #HTMLReporter h5, #HTMLReporter h6 { margin: 0; line-height: 14px; } -#HTMLReporter .banner, #HTMLReporter .symbolSummary, #HTMLReporter .summary, #HTMLReporter .resultMessage, #HTMLReporter .specDetail .description, #HTMLReporter .alert .bar, #HTMLReporter .stackTrace { padding-left: 9px; padding-right: 9px; } -#HTMLReporter #jasmine_content { position: fixed; right: 100%; } -#HTMLReporter .version { color: #aaaaaa; } -#HTMLReporter .banner { margin-top: 14px; } -#HTMLReporter .duration { color: #aaaaaa; float: right; } -#HTMLReporter .symbolSummary { overflow: hidden; *zoom: 1; margin: 14px 0; } -#HTMLReporter .symbolSummary li { display: block; float: left; height: 7px; width: 14px; margin-bottom: 7px; font-size: 16px; } -#HTMLReporter .symbolSummary li.passed { font-size: 14px; } -#HTMLReporter .symbolSummary li.passed:before { color: #5e7d00; content: "\02022"; } -#HTMLReporter .symbolSummary li.failed { line-height: 9px; } -#HTMLReporter .symbolSummary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; } -#HTMLReporter .symbolSummary li.skipped { font-size: 14px; } -#HTMLReporter .symbolSummary li.skipped:before { color: #bababa; content: "\02022"; } -#HTMLReporter .symbolSummary li.pending { line-height: 11px; } -#HTMLReporter .symbolSummary li.pending:before { color: #aaaaaa; content: "-"; } -#HTMLReporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; } -#HTMLReporter .runningAlert { background-color: #666666; } -#HTMLReporter .skippedAlert { background-color: #aaaaaa; } -#HTMLReporter .skippedAlert:first-child { background-color: #333333; } -#HTMLReporter .skippedAlert:hover { text-decoration: none; color: white; text-decoration: underline; } -#HTMLReporter .passingAlert { background-color: #a6b779; } -#HTMLReporter .passingAlert:first-child { background-color: #5e7d00; } -#HTMLReporter .failingAlert { background-color: #cf867e; } -#HTMLReporter .failingAlert:first-child { background-color: #b03911; } -#HTMLReporter .results { margin-top: 14px; } -#HTMLReporter #details { display: none; } -#HTMLReporter .resultsMenu, #HTMLReporter .resultsMenu a { background-color: #fff; color: #333333; } -#HTMLReporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; } -#HTMLReporter.showDetails .summaryMenuItem:hover { text-decoration: underline; } -#HTMLReporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; } -#HTMLReporter.showDetails .summary { display: none; } -#HTMLReporter.showDetails #details { display: block; } -#HTMLReporter .summaryMenuItem { font-weight: bold; text-decoration: underline; } -#HTMLReporter .summary { margin-top: 14px; } -#HTMLReporter .summary .suite .suite, #HTMLReporter .summary .specSummary { margin-left: 14px; } -#HTMLReporter .summary .specSummary.passed a { color: #5e7d00; } -#HTMLReporter .summary .specSummary.failed a { color: #b03911; } -#HTMLReporter .description + .suite { margin-top: 0; } -#HTMLReporter .suite { margin-top: 14px; } -#HTMLReporter .suite a { color: #333333; } -#HTMLReporter #details .specDetail { margin-bottom: 28px; } -#HTMLReporter #details .specDetail .description { display: block; color: white; background-color: #b03911; } -#HTMLReporter .resultMessage { padding-top: 14px; color: #333333; } -#HTMLReporter .resultMessage span.result { display: block; } -#HTMLReporter .stackTrace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; } - -#TrivialReporter { padding: 8px 13px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; overflow-y: scroll; background-color: white; font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; /*.resultMessage {*/ /*white-space: pre;*/ /*}*/ } -#TrivialReporter a:visited, #TrivialReporter a { color: #303; } -#TrivialReporter a:hover, #TrivialReporter a:active { color: blue; } -#TrivialReporter .run_spec { float: right; padding-right: 5px; font-size: .8em; text-decoration: none; } -#TrivialReporter .banner { color: #303; background-color: #fef; padding: 5px; } -#TrivialReporter .logo { float: left; font-size: 1.1em; padding-left: 5px; } -#TrivialReporter .logo .version { font-size: .6em; padding-left: 1em; } -#TrivialReporter .runner.running { background-color: yellow; } -#TrivialReporter .options { text-align: right; font-size: .8em; } -#TrivialReporter .suite { border: 1px outset gray; margin: 5px 0; padding-left: 1em; } -#TrivialReporter .suite .suite { margin: 5px; } -#TrivialReporter .suite.passed { background-color: #dfd; } -#TrivialReporter .suite.failed { background-color: #fdd; } -#TrivialReporter .spec { margin: 5px; padding-left: 1em; clear: both; } -#TrivialReporter .spec.failed, #TrivialReporter .spec.passed, #TrivialReporter .spec.skipped { padding-bottom: 5px; border: 1px solid gray; } -#TrivialReporter .spec.failed { background-color: #fbb; border-color: red; } -#TrivialReporter .spec.passed { background-color: #bfb; border-color: green; } -#TrivialReporter .spec.skipped { background-color: #bbb; } -#TrivialReporter .messages { border-left: 1px dashed gray; padding-left: 1em; padding-right: 1em; } -#TrivialReporter .passed { background-color: #cfc; display: none; } -#TrivialReporter .failed { background-color: #fbb; } -#TrivialReporter .skipped { color: #777; background-color: #eee; display: none; } -#TrivialReporter .resultMessage span.result { display: block; line-height: 2em; color: black; } -#TrivialReporter .resultMessage .mismatch { color: black; } -#TrivialReporter .stackTrace { white-space: pre; font-size: .8em; margin-left: 10px; max-height: 5em; overflow: auto; border: 1px inset red; padding: 1em; background: #eef; } -#TrivialReporter .finished-at { padding-left: 1em; font-size: .6em; } -#TrivialReporter.show-passed .passed, #TrivialReporter.show-skipped .skipped { display: block; } -#TrivialReporter #jasmine_content { position: fixed; right: 100%; } -#TrivialReporter .runner { border: 1px solid gray; display: block; margin: 5px 0; padding: 2px 0 2px 10px; } diff --git a/test/jasmine/lib/jasmine-1.2.0/jasmine.js b/test/jasmine/lib/jasmine-1.2.0/jasmine.js deleted file mode 100644 index 03bf89a..0000000 --- a/test/jasmine/lib/jasmine-1.2.0/jasmine.js +++ /dev/null @@ -1,2529 +0,0 @@ -var isCommonJS = typeof window == "undefined"; - -/** - * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework. - * - * @namespace - */ -var jasmine = {}; -if (isCommonJS) exports.jasmine = jasmine; -/** - * @private - */ -jasmine.unimplementedMethod_ = function() { - throw new Error("unimplemented method"); -}; - -/** - * Use jasmine.undefined instead of undefined, since undefined is just - * a plain old variable and may be redefined by somebody else. - * - * @private - */ -jasmine.undefined = jasmine.___undefined___; - -/** - * Show diagnostic messages in the console if set to true - * - */ -jasmine.VERBOSE = false; - -/** - * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed. - * - */ -jasmine.DEFAULT_UPDATE_INTERVAL = 250; - -/** - * Default timeout interval in milliseconds for waitsFor() blocks. - */ -jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; - -jasmine.getGlobal = function() { - function getGlobal() { - return this; - } - - return getGlobal(); -}; - -/** - * Allows for bound functions to be compared. Internal use only. - * - * @ignore - * @private - * @param base {Object} bound 'this' for the function - * @param name {Function} function to find - */ -jasmine.bindOriginal_ = function(base, name) { - var original = base[name]; - if (original.apply) { - return function() { - return original.apply(base, arguments); - }; - } else { - // IE support - return jasmine.getGlobal()[name]; - } -}; - -jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout'); -jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout'); -jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval'); -jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval'); - -jasmine.MessageResult = function(values) { - this.type = 'log'; - this.values = values; - this.trace = new Error(); // todo: test better -}; - -jasmine.MessageResult.prototype.toString = function() { - var text = ""; - for (var i = 0; i < this.values.length; i++) { - if (i > 0) text += " "; - if (jasmine.isString_(this.values[i])) { - text += this.values[i]; - } else { - text += jasmine.pp(this.values[i]); - } - } - return text; -}; - -jasmine.ExpectationResult = function(params) { - this.type = 'expect'; - this.matcherName = params.matcherName; - this.passed_ = params.passed; - this.expected = params.expected; - this.actual = params.actual; - this.message = this.passed_ ? 'Passed.' : params.message; - - var trace = (params.trace || new Error(this.message)); - this.trace = this.passed_ ? '' : trace; -}; - -jasmine.ExpectationResult.prototype.toString = function () { - return this.message; -}; - -jasmine.ExpectationResult.prototype.passed = function () { - return this.passed_; -}; - -/** - * Getter for the Jasmine environment. Ensures one gets created - */ -jasmine.getEnv = function() { - var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env(); - return env; -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isArray_ = function(value) { - return jasmine.isA_("Array", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isString_ = function(value) { - return jasmine.isA_("String", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isNumber_ = function(value) { - return jasmine.isA_("Number", value); -}; - -/** - * @ignore - * @private - * @param {String} typeName - * @param value - * @returns {Boolean} - */ -jasmine.isA_ = function(typeName, value) { - return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; -}; - -/** - * Pretty printer for expecations. Takes any object and turns it into a human-readable string. - * - * @param value {Object} an object to be outputted - * @returns {String} - */ -jasmine.pp = function(value) { - var stringPrettyPrinter = new jasmine.StringPrettyPrinter(); - stringPrettyPrinter.format(value); - return stringPrettyPrinter.string; -}; - -/** - * Returns true if the object is a DOM Node. - * - * @param {Object} obj object to check - * @returns {Boolean} - */ -jasmine.isDomNode = function(obj) { - return obj.nodeType > 0; -}; - -/** - * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter. - * - * @example - * // don't care about which function is passed in, as long as it's a function - * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function)); - * - * @param {Class} clazz - * @returns matchable object of the type clazz - */ -jasmine.any = function(clazz) { - return new jasmine.Matchers.Any(clazz); -}; - -/** - * Returns a matchable subset of a JSON object. For use in expectations when you don't care about all of the - * attributes on the object. - * - * @example - * // don't care about any other attributes than foo. - * expect(mySpy).toHaveBeenCalledWith(jasmine.objectContaining({foo: "bar"}); - * - * @param sample {Object} sample - * @returns matchable object for the sample - */ -jasmine.objectContaining = function (sample) { - return new jasmine.Matchers.ObjectContaining(sample); -}; - -/** - * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. - * - * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine - * expectation syntax. Spies can be checked if they were called or not and what the calling params were. - * - * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs). - * - * Spies are torn down at the end of every spec. - * - * Note: Do not call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj. - * - * @example - * // a stub - * var myStub = jasmine.createSpy('myStub'); // can be used anywhere - * - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // actual foo.not will not be called, execution stops - * spyOn(foo, 'not'); - - // foo.not spied upon, execution will continue to implementation - * spyOn(foo, 'not').andCallThrough(); - * - * // fake example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // foo.not(val) will return val - * spyOn(foo, 'not').andCallFake(function(value) {return value;}); - * - * // mock example - * foo.not(7 == 7); - * expect(foo.not).toHaveBeenCalled(); - * expect(foo.not).toHaveBeenCalledWith(true); - * - * @constructor - * @see spyOn, jasmine.createSpy, jasmine.createSpyObj - * @param {String} name - */ -jasmine.Spy = function(name) { - /** - * The name of the spy, if provided. - */ - this.identity = name || 'unknown'; - /** - * Is this Object a spy? - */ - this.isSpy = true; - /** - * The actual function this spy stubs. - */ - this.plan = function() { - }; - /** - * Tracking of the most recent call to the spy. - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy.mostRecentCall.args = [1, 2]; - */ - this.mostRecentCall = {}; - - /** - * Holds arguments for each call to the spy, indexed by call count - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy(7, 8); - * mySpy.mostRecentCall.args = [7, 8]; - * mySpy.argsForCall[0] = [1, 2]; - * mySpy.argsForCall[1] = [7, 8]; - */ - this.argsForCall = []; - this.calls = []; -}; - -/** - * Tells a spy to call through to the actual implemenatation. - * - * @example - * var foo = { - * bar: function() { // do some stuff } - * } - * - * // defining a spy on an existing property: foo.bar - * spyOn(foo, 'bar').andCallThrough(); - */ -jasmine.Spy.prototype.andCallThrough = function() { - this.plan = this.originalValue; - return this; -}; - -/** - * For setting the return value of a spy. - * - * @example - * // defining a spy from scratch: foo() returns 'baz' - * var foo = jasmine.createSpy('spy on foo').andReturn('baz'); - * - * // defining a spy on an existing property: foo.bar() returns 'baz' - * spyOn(foo, 'bar').andReturn('baz'); - * - * @param {Object} value - */ -jasmine.Spy.prototype.andReturn = function(value) { - this.plan = function() { - return value; - }; - return this; -}; - -/** - * For throwing an exception when a spy is called. - * - * @example - * // defining a spy from scratch: foo() throws an exception w/ message 'ouch' - * var foo = jasmine.createSpy('spy on foo').andThrow('baz'); - * - * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch' - * spyOn(foo, 'bar').andThrow('baz'); - * - * @param {String} exceptionMsg - */ -jasmine.Spy.prototype.andThrow = function(exceptionMsg) { - this.plan = function() { - throw exceptionMsg; - }; - return this; -}; - -/** - * Calls an alternate implementation when a spy is called. - * - * @example - * var baz = function() { - * // do some stuff, return something - * } - * // defining a spy from scratch: foo() calls the function baz - * var foo = jasmine.createSpy('spy on foo').andCall(baz); - * - * // defining a spy on an existing property: foo.bar() calls an anonymnous function - * spyOn(foo, 'bar').andCall(function() { return 'baz';} ); - * - * @param {Function} fakeFunc - */ -jasmine.Spy.prototype.andCallFake = function(fakeFunc) { - this.plan = fakeFunc; - return this; -}; - -/** - * Resets all of a spy's the tracking variables so that it can be used again. - * - * @example - * spyOn(foo, 'bar'); - * - * foo.bar(); - * - * expect(foo.bar.callCount).toEqual(1); - * - * foo.bar.reset(); - * - * expect(foo.bar.callCount).toEqual(0); - */ -jasmine.Spy.prototype.reset = function() { - this.wasCalled = false; - this.callCount = 0; - this.argsForCall = []; - this.calls = []; - this.mostRecentCall = {}; -}; - -jasmine.createSpy = function(name) { - - var spyObj = function() { - spyObj.wasCalled = true; - spyObj.callCount++; - var args = jasmine.util.argsToArray(arguments); - spyObj.mostRecentCall.object = this; - spyObj.mostRecentCall.args = args; - spyObj.argsForCall.push(args); - spyObj.calls.push({object: this, args: args}); - return spyObj.plan.apply(this, arguments); - }; - - var spy = new jasmine.Spy(name); - - for (var prop in spy) { - spyObj[prop] = spy[prop]; - } - - spyObj.reset(); - - return spyObj; -}; - -/** - * Determines whether an object is a spy. - * - * @param {jasmine.Spy|Object} putativeSpy - * @returns {Boolean} - */ -jasmine.isSpy = function(putativeSpy) { - return putativeSpy && putativeSpy.isSpy; -}; - -/** - * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something - * large in one call. - * - * @param {String} baseName name of spy class - * @param {Array} methodNames array of names of methods to make spies - */ -jasmine.createSpyObj = function(baseName, methodNames) { - if (!jasmine.isArray_(methodNames) || methodNames.length === 0) { - throw new Error('createSpyObj requires a non-empty array of method names to create spies for'); - } - var obj = {}; - for (var i = 0; i < methodNames.length; i++) { - obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]); - } - return obj; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the current spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.log = function() { - var spec = jasmine.getEnv().currentSpec; - spec.log.apply(spec, arguments); -}; - -/** - * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy. - * - * @example - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops - * - * @see jasmine.createSpy - * @param obj - * @param methodName - * @returns a Jasmine spy that can be chained with all spy methods - */ -var spyOn = function(obj, methodName) { - return jasmine.getEnv().currentSpec.spyOn(obj, methodName); -}; -if (isCommonJS) exports.spyOn = spyOn; - -/** - * Creates a Jasmine spec that will be added to the current suite. - * - * // TODO: pending tests - * - * @example - * it('should be true', function() { - * expect(true).toEqual(true); - * }); - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var it = function(desc, func) { - return jasmine.getEnv().it(desc, func); -}; -if (isCommonJS) exports.it = it; - -/** - * Creates a disabled Jasmine spec. - * - * A convenience method that allows existing specs to be disabled temporarily during development. - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var xit = function(desc, func) { - return jasmine.getEnv().xit(desc, func); -}; -if (isCommonJS) exports.xit = xit; - -/** - * Starts a chain for a Jasmine expectation. - * - * It is passed an Object that is the actual value and should chain to one of the many - * jasmine.Matchers functions. - * - * @param {Object} actual Actual value to test against and expected value - */ -var expect = function(actual) { - return jasmine.getEnv().currentSpec.expect(actual); -}; -if (isCommonJS) exports.expect = expect; - -/** - * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs. - * - * @param {Function} func Function that defines part of a jasmine spec. - */ -var runs = function(func) { - jasmine.getEnv().currentSpec.runs(func); -}; -if (isCommonJS) exports.runs = runs; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -var waits = function(timeout) { - jasmine.getEnv().currentSpec.waits(timeout); -}; -if (isCommonJS) exports.waits = waits; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); -}; -if (isCommonJS) exports.waitsFor = waitsFor; - -/** - * A function that is called before each spec in a suite. - * - * Used for spec setup, including validating assumptions. - * - * @param {Function} beforeEachFunction - */ -var beforeEach = function(beforeEachFunction) { - jasmine.getEnv().beforeEach(beforeEachFunction); -}; -if (isCommonJS) exports.beforeEach = beforeEach; - -/** - * A function that is called after each spec in a suite. - * - * Used for restoring any state that is hijacked during spec execution. - * - * @param {Function} afterEachFunction - */ -var afterEach = function(afterEachFunction) { - jasmine.getEnv().afterEach(afterEachFunction); -}; -if (isCommonJS) exports.afterEach = afterEach; - -/** - * Defines a suite of specifications. - * - * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared - * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization - * of setup in some tests. - * - * @example - * // TODO: a simple suite - * - * // TODO: a simple suite with a nested describe block - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var describe = function(description, specDefinitions) { - return jasmine.getEnv().describe(description, specDefinitions); -}; -if (isCommonJS) exports.describe = describe; - -/** - * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development. - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var xdescribe = function(description, specDefinitions) { - return jasmine.getEnv().xdescribe(description, specDefinitions); -}; -if (isCommonJS) exports.xdescribe = xdescribe; - - -// Provide the XMLHttpRequest class for IE 5.x-6.x: -jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() { - function tryIt(f) { - try { - return f(); - } catch(e) { - } - return null; - } - - var xhr = tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.6.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.3.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP"); - }) || - tryIt(function() { - return new ActiveXObject("Microsoft.XMLHTTP"); - }); - - if (!xhr) throw new Error("This browser does not support XMLHttpRequest."); - - return xhr; -} : XMLHttpRequest; -/** - * @namespace - */ -jasmine.util = {}; - -/** - * Declare that a child class inherit it's prototype from the parent class. - * - * @private - * @param {Function} childClass - * @param {Function} parentClass - */ -jasmine.util.inherit = function(childClass, parentClass) { - /** - * @private - */ - var subclass = function() { - }; - subclass.prototype = parentClass.prototype; - childClass.prototype = new subclass(); -}; - -jasmine.util.formatException = function(e) { - var lineNumber; - if (e.line) { - lineNumber = e.line; - } - else if (e.lineNumber) { - lineNumber = e.lineNumber; - } - - var file; - - if (e.sourceURL) { - file = e.sourceURL; - } - else if (e.fileName) { - file = e.fileName; - } - - var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString(); - - if (file && lineNumber) { - message += ' in ' + file + ' (line ' + lineNumber + ')'; - } - - return message; -}; - -jasmine.util.htmlEscape = function(str) { - if (!str) return str; - return str.replace(/&/g, '&') - .replace(//g, '>'); -}; - -jasmine.util.argsToArray = function(args) { - var arrayOfArgs = []; - for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]); - return arrayOfArgs; -}; - -jasmine.util.extend = function(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; -}; - -/** - * Environment for Jasmine - * - * @constructor - */ -jasmine.Env = function() { - this.currentSpec = null; - this.currentSuite = null; - this.currentRunner_ = new jasmine.Runner(this); - - this.reporter = new jasmine.MultiReporter(); - - this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; - this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; - this.lastUpdate = 0; - this.specFilter = function() { - return true; - }; - - this.nextSpecId_ = 0; - this.nextSuiteId_ = 0; - this.equalityTesters_ = []; - - // wrap matchers - this.matchersClass = function() { - jasmine.Matchers.apply(this, arguments); - }; - jasmine.util.inherit(this.matchersClass, jasmine.Matchers); - - jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); -}; - - -jasmine.Env.prototype.setTimeout = jasmine.setTimeout; -jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; -jasmine.Env.prototype.setInterval = jasmine.setInterval; -jasmine.Env.prototype.clearInterval = jasmine.clearInterval; - -/** - * @returns an object containing jasmine version build info, if set. - */ -jasmine.Env.prototype.version = function () { - if (jasmine.version_) { - return jasmine.version_; - } else { - throw new Error('Version not set'); - } -}; - -/** - * @returns string containing jasmine version build info, if set. - */ -jasmine.Env.prototype.versionString = function() { - if (!jasmine.version_) { - return "version unknown"; - } - - var version = this.version(); - var versionString = version.major + "." + version.minor + "." + version.build; - if (version.release_candidate) { - versionString += ".rc" + version.release_candidate; - } - versionString += " revision " + version.revision; - return versionString; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSpecId = function () { - return this.nextSpecId_++; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSuiteId = function () { - return this.nextSuiteId_++; -}; - -/** - * Register a reporter to receive status updates from Jasmine. - * @param {jasmine.Reporter} reporter An object which will receive status updates. - */ -jasmine.Env.prototype.addReporter = function(reporter) { - this.reporter.addReporter(reporter); -}; - -jasmine.Env.prototype.execute = function() { - this.currentRunner_.execute(); -}; - -jasmine.Env.prototype.describe = function(description, specDefinitions) { - var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); - - var parentSuite = this.currentSuite; - if (parentSuite) { - parentSuite.add(suite); - } else { - this.currentRunner_.add(suite); - } - - this.currentSuite = suite; - - var declarationError = null; - try { - specDefinitions.call(suite); - } catch(e) { - declarationError = e; - } - - if (declarationError) { - this.it("encountered a declaration exception", function() { - throw declarationError; - }); - } - - this.currentSuite = parentSuite; - - return suite; -}; - -jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { - if (this.currentSuite) { - this.currentSuite.beforeEach(beforeEachFunction); - } else { - this.currentRunner_.beforeEach(beforeEachFunction); - } -}; - -jasmine.Env.prototype.currentRunner = function () { - return this.currentRunner_; -}; - -jasmine.Env.prototype.afterEach = function(afterEachFunction) { - if (this.currentSuite) { - this.currentSuite.afterEach(afterEachFunction); - } else { - this.currentRunner_.afterEach(afterEachFunction); - } - -}; - -jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { - return { - execute: function() { - } - }; -}; - -jasmine.Env.prototype.it = function(description, func) { - var spec = new jasmine.Spec(this, this.currentSuite, description); - this.currentSuite.add(spec); - this.currentSpec = spec; - - if (func) { - spec.runs(func); - } - - return spec; -}; - -jasmine.Env.prototype.xit = function(desc, func) { - return { - id: this.nextSpecId(), - runs: function() { - } - }; -}; - -jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { - if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { - return true; - } - - a.__Jasmine_been_here_before__ = b; - b.__Jasmine_been_here_before__ = a; - - var hasKey = function(obj, keyName) { - return obj !== null && obj[keyName] !== jasmine.undefined; - }; - - for (var property in b) { - if (!hasKey(a, property) && hasKey(b, property)) { - mismatchKeys.push("expected has key '" + property + "', but missing from actual."); - } - } - for (property in a) { - if (!hasKey(b, property) && hasKey(a, property)) { - mismatchKeys.push("expected missing key '" + property + "', but present in actual."); - } - } - for (property in b) { - if (property == '__Jasmine_been_here_before__') continue; - if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { - mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); - } - } - - if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { - mismatchValues.push("arrays were not the same length"); - } - - delete a.__Jasmine_been_here_before__; - delete b.__Jasmine_been_here_before__; - return (mismatchKeys.length === 0 && mismatchValues.length === 0); -}; - -jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { - mismatchKeys = mismatchKeys || []; - mismatchValues = mismatchValues || []; - - for (var i = 0; i < this.equalityTesters_.length; i++) { - var equalityTester = this.equalityTesters_[i]; - var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); - if (result !== jasmine.undefined) return result; - } - - if (a === b) return true; - - if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { - return (a == jasmine.undefined && b == jasmine.undefined); - } - - if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { - return a === b; - } - - if (a instanceof Date && b instanceof Date) { - return a.getTime() == b.getTime(); - } - - if (a.jasmineMatches) { - return a.jasmineMatches(b); - } - - if (b.jasmineMatches) { - return b.jasmineMatches(a); - } - - if (a instanceof jasmine.Matchers.ObjectContaining) { - return a.matches(b); - } - - if (b instanceof jasmine.Matchers.ObjectContaining) { - return b.matches(a); - } - - if (jasmine.isString_(a) && jasmine.isString_(b)) { - return (a == b); - } - - if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { - return (a == b); - } - - if (typeof a === "object" && typeof b === "object") { - return this.compareObjects_(a, b, mismatchKeys, mismatchValues); - } - - //Straight check - return (a === b); -}; - -jasmine.Env.prototype.contains_ = function(haystack, needle) { - if (jasmine.isArray_(haystack)) { - for (var i = 0; i < haystack.length; i++) { - if (this.equals_(haystack[i], needle)) return true; - } - return false; - } - return haystack.indexOf(needle) >= 0; -}; - -jasmine.Env.prototype.addEqualityTester = function(equalityTester) { - this.equalityTesters_.push(equalityTester); -}; -/** No-op base class for Jasmine reporters. - * - * @constructor - */ -jasmine.Reporter = function() { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerStarting = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerResults = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecStarting = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecResults = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.log = function(str) { -}; - -/** - * Blocks are functions with executable code that make up a spec. - * - * @constructor - * @param {jasmine.Env} env - * @param {Function} func - * @param {jasmine.Spec} spec - */ -jasmine.Block = function(env, func, spec) { - this.env = env; - this.func = func; - this.spec = spec; -}; - -jasmine.Block.prototype.execute = function(onComplete) { - try { - this.func.apply(this.spec); - } catch (e) { - this.spec.fail(e); - } - onComplete(); -}; -/** JavaScript API reporter. - * - * @constructor - */ -jasmine.JsApiReporter = function() { - this.started = false; - this.finished = false; - this.suites_ = []; - this.results_ = {}; -}; - -jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) { - this.started = true; - var suites = runner.topLevelSuites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - this.suites_.push(this.summarize_(suite)); - } -}; - -jasmine.JsApiReporter.prototype.suites = function() { - return this.suites_; -}; - -jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) { - var isSuite = suiteOrSpec instanceof jasmine.Suite; - var summary = { - id: suiteOrSpec.id, - name: suiteOrSpec.description, - type: isSuite ? 'suite' : 'spec', - children: [] - }; - - if (isSuite) { - var children = suiteOrSpec.children(); - for (var i = 0; i < children.length; i++) { - summary.children.push(this.summarize_(children[i])); - } - } - return summary; -}; - -jasmine.JsApiReporter.prototype.results = function() { - return this.results_; -}; - -jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) { - return this.results_[specId]; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) { - this.finished = true; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) { - this.results_[spec.id] = { - messages: spec.results().getItems(), - result: spec.results().failedCount > 0 ? "failed" : "passed" - }; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.log = function(str) { -}; - -jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){ - var results = {}; - for (var i = 0; i < specIds.length; i++) { - var specId = specIds[i]; - results[specId] = this.summarizeResult_(this.results_[specId]); - } - return results; -}; - -jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ - var summaryMessages = []; - var messagesLength = result.messages.length; - for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) { - var resultMessage = result.messages[messageIndex]; - summaryMessages.push({ - text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined, - passed: resultMessage.passed ? resultMessage.passed() : true, - type: resultMessage.type, - message: resultMessage.message, - trace: { - stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined - } - }); - } - - return { - result : result.result, - messages : summaryMessages - }; -}; - -/** - * @constructor - * @param {jasmine.Env} env - * @param actual - * @param {jasmine.Spec} spec - */ -jasmine.Matchers = function(env, actual, spec, opt_isNot) { - this.env = env; - this.actual = actual; - this.spec = spec; - this.isNot = opt_isNot || false; - this.reportWasCalled_ = false; -}; - -// todo: @deprecated as of Jasmine 0.11, remove soon [xw] -jasmine.Matchers.pp = function(str) { - throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!"); -}; - -// todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw] -jasmine.Matchers.prototype.report = function(result, failing_message, details) { - throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs"); -}; - -jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) { - for (var methodName in prototype) { - if (methodName == 'report') continue; - var orig = prototype[methodName]; - matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig); - } -}; - -jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { - return function() { - var matcherArgs = jasmine.util.argsToArray(arguments); - var result = matcherFunction.apply(this, arguments); - - if (this.isNot) { - result = !result; - } - - if (this.reportWasCalled_) return result; - - var message; - if (!result) { - if (this.message) { - message = this.message.apply(this, arguments); - if (jasmine.isArray_(message)) { - message = message[this.isNot ? 1 : 0]; - } - } else { - var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); - message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate; - if (matcherArgs.length > 0) { - for (var i = 0; i < matcherArgs.length; i++) { - if (i > 0) message += ","; - message += " " + jasmine.pp(matcherArgs[i]); - } - } - message += "."; - } - } - var expectationResult = new jasmine.ExpectationResult({ - matcherName: matcherName, - passed: result, - expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0], - actual: this.actual, - message: message - }); - this.spec.addMatcherResult(expectationResult); - return jasmine.undefined; - }; -}; - - - - -/** - * toBe: compares the actual to the expected using === - * @param expected - */ -jasmine.Matchers.prototype.toBe = function(expected) { - return this.actual === expected; -}; - -/** - * toNotBe: compares the actual to the expected using !== - * @param expected - * @deprecated as of 1.0. Use not.toBe() instead. - */ -jasmine.Matchers.prototype.toNotBe = function(expected) { - return this.actual !== expected; -}; - -/** - * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc. - * - * @param expected - */ -jasmine.Matchers.prototype.toEqual = function(expected) { - return this.env.equals_(this.actual, expected); -}; - -/** - * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual - * @param expected - * @deprecated as of 1.0. Use not.toEqual() instead. - */ -jasmine.Matchers.prototype.toNotEqual = function(expected) { - return !this.env.equals_(this.actual, expected); -}; - -/** - * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes - * a pattern or a String. - * - * @param expected - */ -jasmine.Matchers.prototype.toMatch = function(expected) { - return new RegExp(expected).test(this.actual); -}; - -/** - * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch - * @param expected - * @deprecated as of 1.0. Use not.toMatch() instead. - */ -jasmine.Matchers.prototype.toNotMatch = function(expected) { - return !(new RegExp(expected).test(this.actual)); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeDefined = function() { - return (this.actual !== jasmine.undefined); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeUndefined = function() { - return (this.actual === jasmine.undefined); -}; - -/** - * Matcher that compares the actual to null. - */ -jasmine.Matchers.prototype.toBeNull = function() { - return (this.actual === null); -}; - -/** - * Matcher that boolean not-nots the actual. - */ -jasmine.Matchers.prototype.toBeTruthy = function() { - return !!this.actual; -}; - - -/** - * Matcher that boolean nots the actual. - */ -jasmine.Matchers.prototype.toBeFalsy = function() { - return !this.actual; -}; - - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called. - */ -jasmine.Matchers.prototype.toHaveBeenCalled = function() { - if (arguments.length > 0) { - throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to have been called.", - "Expected spy " + this.actual.identity + " not to have been called." - ]; - }; - - return this.actual.wasCalled; -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalled() instead */ -jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was not called. - * - * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead - */ -jasmine.Matchers.prototype.wasNotCalled = function() { - if (arguments.length > 0) { - throw new Error('wasNotCalled does not take arguments'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to not have been called.", - "Expected spy " + this.actual.identity + " to have been called." - ]; - }; - - return !this.actual.wasCalled; -}; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters. - * - * @example - * - */ -jasmine.Matchers.prototype.toHaveBeenCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - this.message = function() { - if (this.actual.callCount === 0) { - // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw] - return [ - "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.", - "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was." - ]; - } else { - return [ - "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall), - "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall) - ]; - } - }; - - return this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith; - -/** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasNotCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was", - "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was" - ]; - }; - - return !this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** - * Matcher that checks that the expected item is an element in the actual Array. - * - * @param {Object} expected - */ -jasmine.Matchers.prototype.toContain = function(expected) { - return this.env.contains_(this.actual, expected); -}; - -/** - * Matcher that checks that the expected item is NOT an element in the actual Array. - * - * @param {Object} expected - * @deprecated as of 1.0. Use not.toContain() instead. - */ -jasmine.Matchers.prototype.toNotContain = function(expected) { - return !this.env.contains_(this.actual, expected); -}; - -jasmine.Matchers.prototype.toBeLessThan = function(expected) { - return this.actual < expected; -}; - -jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { - return this.actual > expected; -}; - -/** - * Matcher that checks that the expected item is equal to the actual item - * up to a given level of decimal precision (default 2). - * - * @param {Number} expected - * @param {Number} precision - */ -jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) { - if (!(precision === 0)) { - precision = precision || 2; - } - var multiplier = Math.pow(10, precision); - var actual = Math.round(this.actual * multiplier); - expected = Math.round(expected * multiplier); - return expected == actual; -}; - -/** - * Matcher that checks that the expected exception was thrown by the actual. - * - * @param {String} expected - */ -jasmine.Matchers.prototype.toThrow = function(expected) { - var result = false; - var exception; - if (typeof this.actual != 'function') { - throw new Error('Actual is not a function'); - } - try { - this.actual(); - } catch (e) { - exception = e; - } - if (exception) { - result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); - } - - var not = this.isNot ? "not " : ""; - - this.message = function() { - if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) { - return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' '); - } else { - return "Expected function to throw an exception."; - } - }; - - return result; -}; - -jasmine.Matchers.Any = function(expectedClass) { - this.expectedClass = expectedClass; -}; - -jasmine.Matchers.Any.prototype.jasmineMatches = function(other) { - if (this.expectedClass == String) { - return typeof other == 'string' || other instanceof String; - } - - if (this.expectedClass == Number) { - return typeof other == 'number' || other instanceof Number; - } - - if (this.expectedClass == Function) { - return typeof other == 'function' || other instanceof Function; - } - - if (this.expectedClass == Object) { - return typeof other == 'object'; - } - - return other instanceof this.expectedClass; -}; - -jasmine.Matchers.Any.prototype.jasmineToString = function() { - return ''; -}; - -jasmine.Matchers.ObjectContaining = function (sample) { - this.sample = sample; -}; - -jasmine.Matchers.ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) { - mismatchKeys = mismatchKeys || []; - mismatchValues = mismatchValues || []; - - var env = jasmine.getEnv(); - - var hasKey = function(obj, keyName) { - return obj != null && obj[keyName] !== jasmine.undefined; - }; - - for (var property in this.sample) { - if (!hasKey(other, property) && hasKey(this.sample, property)) { - mismatchKeys.push("expected has key '" + property + "', but missing from actual."); - } - else if (!env.equals_(this.sample[property], other[property], mismatchKeys, mismatchValues)) { - mismatchValues.push("'" + property + "' was '" + (other[property] ? jasmine.util.htmlEscape(other[property].toString()) : other[property]) + "' in expected, but was '" + (this.sample[property] ? jasmine.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in actual."); - } - } - - return (mismatchKeys.length === 0 && mismatchValues.length === 0); -}; - -jasmine.Matchers.ObjectContaining.prototype.jasmineToString = function () { - return ""; -}; -// Mock setTimeout, clearTimeout -// Contributed by Pivotal Computer Systems, www.pivotalsf.com - -jasmine.FakeTimer = function() { - this.reset(); - - var self = this; - self.setTimeout = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false); - return self.timeoutsMade; - }; - - self.setInterval = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true); - return self.timeoutsMade; - }; - - self.clearTimeout = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - - self.clearInterval = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - -}; - -jasmine.FakeTimer.prototype.reset = function() { - this.timeoutsMade = 0; - this.scheduledFunctions = {}; - this.nowMillis = 0; -}; - -jasmine.FakeTimer.prototype.tick = function(millis) { - var oldMillis = this.nowMillis; - var newMillis = oldMillis + millis; - this.runFunctionsWithinRange(oldMillis, newMillis); - this.nowMillis = newMillis; -}; - -jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) { - var scheduledFunc; - var funcsToRun = []; - for (var timeoutKey in this.scheduledFunctions) { - scheduledFunc = this.scheduledFunctions[timeoutKey]; - if (scheduledFunc != jasmine.undefined && - scheduledFunc.runAtMillis >= oldMillis && - scheduledFunc.runAtMillis <= nowMillis) { - funcsToRun.push(scheduledFunc); - this.scheduledFunctions[timeoutKey] = jasmine.undefined; - } - } - - if (funcsToRun.length > 0) { - funcsToRun.sort(function(a, b) { - return a.runAtMillis - b.runAtMillis; - }); - for (var i = 0; i < funcsToRun.length; ++i) { - try { - var funcToRun = funcsToRun[i]; - this.nowMillis = funcToRun.runAtMillis; - funcToRun.funcToCall(); - if (funcToRun.recurring) { - this.scheduleFunction(funcToRun.timeoutKey, - funcToRun.funcToCall, - funcToRun.millis, - true); - } - } catch(e) { - } - } - this.runFunctionsWithinRange(oldMillis, nowMillis); - } -}; - -jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) { - this.scheduledFunctions[timeoutKey] = { - runAtMillis: this.nowMillis + millis, - funcToCall: funcToCall, - recurring: recurring, - timeoutKey: timeoutKey, - millis: millis - }; -}; - -/** - * @namespace - */ -jasmine.Clock = { - defaultFakeTimer: new jasmine.FakeTimer(), - - reset: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.reset(); - }, - - tick: function(millis) { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.tick(millis); - }, - - runFunctionsWithinRange: function(oldMillis, nowMillis) { - jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis); - }, - - scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) { - jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring); - }, - - useMock: function() { - if (!jasmine.Clock.isInstalled()) { - var spec = jasmine.getEnv().currentSpec; - spec.after(jasmine.Clock.uninstallMock); - - jasmine.Clock.installMock(); - } - }, - - installMock: function() { - jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer; - }, - - uninstallMock: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.installed = jasmine.Clock.real; - }, - - real: { - setTimeout: jasmine.getGlobal().setTimeout, - clearTimeout: jasmine.getGlobal().clearTimeout, - setInterval: jasmine.getGlobal().setInterval, - clearInterval: jasmine.getGlobal().clearInterval - }, - - assertInstalled: function() { - if (!jasmine.Clock.isInstalled()) { - throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()"); - } - }, - - isInstalled: function() { - return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer; - }, - - installed: null -}; -jasmine.Clock.installed = jasmine.Clock.real; - -//else for IE support -jasmine.getGlobal().setTimeout = function(funcToCall, millis) { - if (jasmine.Clock.installed.setTimeout.apply) { - return jasmine.Clock.installed.setTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.setTimeout(funcToCall, millis); - } -}; - -jasmine.getGlobal().setInterval = function(funcToCall, millis) { - if (jasmine.Clock.installed.setInterval.apply) { - return jasmine.Clock.installed.setInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.setInterval(funcToCall, millis); - } -}; - -jasmine.getGlobal().clearTimeout = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearTimeout(timeoutKey); - } -}; - -jasmine.getGlobal().clearInterval = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearInterval(timeoutKey); - } -}; - -/** - * @constructor - */ -jasmine.MultiReporter = function() { - this.subReporters_ = []; -}; -jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter); - -jasmine.MultiReporter.prototype.addReporter = function(reporter) { - this.subReporters_.push(reporter); -}; - -(function() { - var functionNames = [ - "reportRunnerStarting", - "reportRunnerResults", - "reportSuiteResults", - "reportSpecStarting", - "reportSpecResults", - "log" - ]; - for (var i = 0; i < functionNames.length; i++) { - var functionName = functionNames[i]; - jasmine.MultiReporter.prototype[functionName] = (function(functionName) { - return function() { - for (var j = 0; j < this.subReporters_.length; j++) { - var subReporter = this.subReporters_[j]; - if (subReporter[functionName]) { - subReporter[functionName].apply(subReporter, arguments); - } - } - }; - })(functionName); - } -})(); -/** - * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults - * - * @constructor - */ -jasmine.NestedResults = function() { - /** - * The total count of results - */ - this.totalCount = 0; - /** - * Number of passed results - */ - this.passedCount = 0; - /** - * Number of failed results - */ - this.failedCount = 0; - /** - * Was this suite/spec skipped? - */ - this.skipped = false; - /** - * @ignore - */ - this.items_ = []; -}; - -/** - * Roll up the result counts. - * - * @param result - */ -jasmine.NestedResults.prototype.rollupCounts = function(result) { - this.totalCount += result.totalCount; - this.passedCount += result.passedCount; - this.failedCount += result.failedCount; -}; - -/** - * Adds a log message. - * @param values Array of message parts which will be concatenated later. - */ -jasmine.NestedResults.prototype.log = function(values) { - this.items_.push(new jasmine.MessageResult(values)); -}; - -/** - * Getter for the results: message & results. - */ -jasmine.NestedResults.prototype.getItems = function() { - return this.items_; -}; - -/** - * Adds a result, tracking counts (total, passed, & failed) - * @param {jasmine.ExpectationResult|jasmine.NestedResults} result - */ -jasmine.NestedResults.prototype.addResult = function(result) { - if (result.type != 'log') { - if (result.items_) { - this.rollupCounts(result); - } else { - this.totalCount++; - if (result.passed()) { - this.passedCount++; - } else { - this.failedCount++; - } - } - } - this.items_.push(result); -}; - -/** - * @returns {Boolean} True if everything below passed - */ -jasmine.NestedResults.prototype.passed = function() { - return this.passedCount === this.totalCount; -}; -/** - * Base class for pretty printing for expectation results. - */ -jasmine.PrettyPrinter = function() { - this.ppNestLevel_ = 0; -}; - -/** - * Formats a value in a nice, human-readable string. - * - * @param value - */ -jasmine.PrettyPrinter.prototype.format = function(value) { - if (this.ppNestLevel_ > 40) { - throw new Error('jasmine.PrettyPrinter: format() nested too deeply!'); - } - - this.ppNestLevel_++; - try { - if (value === jasmine.undefined) { - this.emitScalar('undefined'); - } else if (value === null) { - this.emitScalar('null'); - } else if (value === jasmine.getGlobal()) { - this.emitScalar(''); - } else if (value.jasmineToString) { - this.emitScalar(value.jasmineToString()); - } else if (typeof value === 'string') { - this.emitString(value); - } else if (jasmine.isSpy(value)) { - this.emitScalar("spy on " + value.identity); - } else if (value instanceof RegExp) { - this.emitScalar(value.toString()); - } else if (typeof value === 'function') { - this.emitScalar('Function'); - } else if (typeof value.nodeType === 'number') { - this.emitScalar('HTMLNode'); - } else if (value instanceof Date) { - this.emitScalar('Date(' + value + ')'); - } else if (value.__Jasmine_been_here_before__) { - this.emitScalar(''); - } else if (jasmine.isArray_(value) || typeof value == 'object') { - value.__Jasmine_been_here_before__ = true; - if (jasmine.isArray_(value)) { - this.emitArray(value); - } else { - this.emitObject(value); - } - delete value.__Jasmine_been_here_before__; - } else { - this.emitScalar(value.toString()); - } - } finally { - this.ppNestLevel_--; - } -}; - -jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) { - for (var property in obj) { - if (property == '__Jasmine_been_here_before__') continue; - fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined && - obj.__lookupGetter__(property) !== null) : false); - } -}; - -jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_; - -jasmine.StringPrettyPrinter = function() { - jasmine.PrettyPrinter.call(this); - - this.string = ''; -}; -jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter); - -jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) { - this.append(value); -}; - -jasmine.StringPrettyPrinter.prototype.emitString = function(value) { - this.append("'" + value + "'"); -}; - -jasmine.StringPrettyPrinter.prototype.emitArray = function(array) { - this.append('[ '); - for (var i = 0; i < array.length; i++) { - if (i > 0) { - this.append(', '); - } - this.format(array[i]); - } - this.append(' ]'); -}; - -jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) { - var self = this; - this.append('{ '); - var first = true; - - this.iterateObject(obj, function(property, isGetter) { - if (first) { - first = false; - } else { - self.append(', '); - } - - self.append(property); - self.append(' : '); - if (isGetter) { - self.append(''); - } else { - self.format(obj[property]); - } - }); - - this.append(' }'); -}; - -jasmine.StringPrettyPrinter.prototype.append = function(value) { - this.string += value; -}; -jasmine.Queue = function(env) { - this.env = env; - this.blocks = []; - this.running = false; - this.index = 0; - this.offset = 0; - this.abort = false; -}; - -jasmine.Queue.prototype.addBefore = function(block) { - this.blocks.unshift(block); -}; - -jasmine.Queue.prototype.add = function(block) { - this.blocks.push(block); -}; - -jasmine.Queue.prototype.insertNext = function(block) { - this.blocks.splice((this.index + this.offset + 1), 0, block); - this.offset++; -}; - -jasmine.Queue.prototype.start = function(onComplete) { - this.running = true; - this.onComplete = onComplete; - this.next_(); -}; - -jasmine.Queue.prototype.isRunning = function() { - return this.running; -}; - -jasmine.Queue.LOOP_DONT_RECURSE = true; - -jasmine.Queue.prototype.next_ = function() { - var self = this; - var goAgain = true; - - while (goAgain) { - goAgain = false; - - if (self.index < self.blocks.length && !this.abort) { - var calledSynchronously = true; - var completedSynchronously = false; - - var onComplete = function () { - if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) { - completedSynchronously = true; - return; - } - - if (self.blocks[self.index].abort) { - self.abort = true; - } - - self.offset = 0; - self.index++; - - var now = new Date().getTime(); - if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) { - self.env.lastUpdate = now; - self.env.setTimeout(function() { - self.next_(); - }, 0); - } else { - if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) { - goAgain = true; - } else { - self.next_(); - } - } - }; - self.blocks[self.index].execute(onComplete); - - calledSynchronously = false; - if (completedSynchronously) { - onComplete(); - } - - } else { - self.running = false; - if (self.onComplete) { - self.onComplete(); - } - } - } -}; - -jasmine.Queue.prototype.results = function() { - var results = new jasmine.NestedResults(); - for (var i = 0; i < this.blocks.length; i++) { - if (this.blocks[i].results) { - results.addResult(this.blocks[i].results()); - } - } - return results; -}; - - -/** - * Runner - * - * @constructor - * @param {jasmine.Env} env - */ -jasmine.Runner = function(env) { - var self = this; - self.env = env; - self.queue = new jasmine.Queue(env); - self.before_ = []; - self.after_ = []; - self.suites_ = []; -}; - -jasmine.Runner.prototype.execute = function() { - var self = this; - if (self.env.reporter.reportRunnerStarting) { - self.env.reporter.reportRunnerStarting(this); - } - self.queue.start(function () { - self.finishCallback(); - }); -}; - -jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.splice(0,0,beforeEachFunction); -}; - -jasmine.Runner.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.splice(0,0,afterEachFunction); -}; - - -jasmine.Runner.prototype.finishCallback = function() { - this.env.reporter.reportRunnerResults(this); -}; - -jasmine.Runner.prototype.addSuite = function(suite) { - this.suites_.push(suite); -}; - -jasmine.Runner.prototype.add = function(block) { - if (block instanceof jasmine.Suite) { - this.addSuite(block); - } - this.queue.add(block); -}; - -jasmine.Runner.prototype.specs = function () { - var suites = this.suites(); - var specs = []; - for (var i = 0; i < suites.length; i++) { - specs = specs.concat(suites[i].specs()); - } - return specs; -}; - -jasmine.Runner.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Runner.prototype.topLevelSuites = function() { - var topLevelSuites = []; - for (var i = 0; i < this.suites_.length; i++) { - if (!this.suites_[i].parentSuite) { - topLevelSuites.push(this.suites_[i]); - } - } - return topLevelSuites; -}; - -jasmine.Runner.prototype.results = function() { - return this.queue.results(); -}; -/** - * Internal representation of a Jasmine specification, or test. - * - * @constructor - * @param {jasmine.Env} env - * @param {jasmine.Suite} suite - * @param {String} description - */ -jasmine.Spec = function(env, suite, description) { - if (!env) { - throw new Error('jasmine.Env() required'); - } - if (!suite) { - throw new Error('jasmine.Suite() required'); - } - var spec = this; - spec.id = env.nextSpecId ? env.nextSpecId() : null; - spec.env = env; - spec.suite = suite; - spec.description = description; - spec.queue = new jasmine.Queue(env); - - spec.afterCallbacks = []; - spec.spies_ = []; - - spec.results_ = new jasmine.NestedResults(); - spec.results_.description = description; - spec.matchersClass = null; -}; - -jasmine.Spec.prototype.getFullName = function() { - return this.suite.getFullName() + ' ' + this.description + '.'; -}; - - -jasmine.Spec.prototype.results = function() { - return this.results_; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.Spec.prototype.log = function() { - return this.results_.log(arguments); -}; - -jasmine.Spec.prototype.runs = function (func) { - var block = new jasmine.Block(this.env, func, this); - this.addToQueue(block); - return this; -}; - -jasmine.Spec.prototype.addToQueue = function (block) { - if (this.queue.isRunning()) { - this.queue.insertNext(block); - } else { - this.queue.add(block); - } -}; - -/** - * @param {jasmine.ExpectationResult} result - */ -jasmine.Spec.prototype.addMatcherResult = function(result) { - this.results_.addResult(result); -}; - -jasmine.Spec.prototype.expect = function(actual) { - var positive = new (this.getMatchersClass_())(this.env, actual, this); - positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); - return positive; -}; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -jasmine.Spec.prototype.waits = function(timeout) { - var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this); - this.addToQueue(waitsFunc); - return this; -}; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - var latchFunction_ = null; - var optional_timeoutMessage_ = null; - var optional_timeout_ = null; - - for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i]; - switch (typeof arg) { - case 'function': - latchFunction_ = arg; - break; - case 'string': - optional_timeoutMessage_ = arg; - break; - case 'number': - optional_timeout_ = arg; - break; - } - } - - var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this); - this.addToQueue(waitsForFunc); - return this; -}; - -jasmine.Spec.prototype.fail = function (e) { - var expectationResult = new jasmine.ExpectationResult({ - passed: false, - message: e ? jasmine.util.formatException(e) : 'Exception', - trace: { stack: e.stack } - }); - this.results_.addResult(expectationResult); -}; - -jasmine.Spec.prototype.getMatchersClass_ = function() { - return this.matchersClass || this.env.matchersClass; -}; - -jasmine.Spec.prototype.addMatchers = function(matchersPrototype) { - var parent = this.getMatchersClass_(); - var newMatchersClass = function() { - parent.apply(this, arguments); - }; - jasmine.util.inherit(newMatchersClass, parent); - jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass); - this.matchersClass = newMatchersClass; -}; - -jasmine.Spec.prototype.finishCallback = function() { - this.env.reporter.reportSpecResults(this); -}; - -jasmine.Spec.prototype.finish = function(onComplete) { - this.removeAllSpies(); - this.finishCallback(); - if (onComplete) { - onComplete(); - } -}; - -jasmine.Spec.prototype.after = function(doAfter) { - if (this.queue.isRunning()) { - this.queue.add(new jasmine.Block(this.env, doAfter, this)); - } else { - this.afterCallbacks.unshift(doAfter); - } -}; - -jasmine.Spec.prototype.execute = function(onComplete) { - var spec = this; - if (!spec.env.specFilter(spec)) { - spec.results_.skipped = true; - spec.finish(onComplete); - return; - } - - this.env.reporter.reportSpecStarting(this); - - spec.env.currentSpec = spec; - - spec.addBeforesAndAftersToQueue(); - - spec.queue.start(function () { - spec.finish(onComplete); - }); -}; - -jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() { - var runner = this.env.currentRunner(); - var i; - - for (var suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)); - } - } - for (i = 0; i < runner.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)); - } - for (i = 0; i < this.afterCallbacks.length; i++) { - this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this)); - } - for (suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, suite.after_[i], this)); - } - } - for (i = 0; i < runner.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, runner.after_[i], this)); - } -}; - -jasmine.Spec.prototype.explodes = function() { - throw 'explodes function should not have been called'; -}; - -jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) { - if (obj == jasmine.undefined) { - throw "spyOn could not find an object to spy upon for " + methodName + "()"; - } - - if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) { - throw methodName + '() method does not exist'; - } - - if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) { - throw new Error(methodName + ' has already been spied upon'); - } - - var spyObj = jasmine.createSpy(methodName); - - this.spies_.push(spyObj); - spyObj.baseObj = obj; - spyObj.methodName = methodName; - spyObj.originalValue = obj[methodName]; - - obj[methodName] = spyObj; - - return spyObj; -}; - -jasmine.Spec.prototype.removeAllSpies = function() { - for (var i = 0; i < this.spies_.length; i++) { - var spy = this.spies_[i]; - spy.baseObj[spy.methodName] = spy.originalValue; - } - this.spies_ = []; -}; - -/** - * Internal representation of a Jasmine suite. - * - * @constructor - * @param {jasmine.Env} env - * @param {String} description - * @param {Function} specDefinitions - * @param {jasmine.Suite} parentSuite - */ -jasmine.Suite = function(env, description, specDefinitions, parentSuite) { - var self = this; - self.id = env.nextSuiteId ? env.nextSuiteId() : null; - self.description = description; - self.queue = new jasmine.Queue(env); - self.parentSuite = parentSuite; - self.env = env; - self.before_ = []; - self.after_ = []; - self.children_ = []; - self.suites_ = []; - self.specs_ = []; -}; - -jasmine.Suite.prototype.getFullName = function() { - var fullName = this.description; - for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { - fullName = parentSuite.description + ' ' + fullName; - } - return fullName; -}; - -jasmine.Suite.prototype.finish = function(onComplete) { - this.env.reporter.reportSuiteResults(this); - this.finished = true; - if (typeof(onComplete) == 'function') { - onComplete(); - } -}; - -jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.unshift(beforeEachFunction); -}; - -jasmine.Suite.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.unshift(afterEachFunction); -}; - -jasmine.Suite.prototype.results = function() { - return this.queue.results(); -}; - -jasmine.Suite.prototype.add = function(suiteOrSpec) { - this.children_.push(suiteOrSpec); - if (suiteOrSpec instanceof jasmine.Suite) { - this.suites_.push(suiteOrSpec); - this.env.currentRunner().addSuite(suiteOrSpec); - } else { - this.specs_.push(suiteOrSpec); - } - this.queue.add(suiteOrSpec); -}; - -jasmine.Suite.prototype.specs = function() { - return this.specs_; -}; - -jasmine.Suite.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Suite.prototype.children = function() { - return this.children_; -}; - -jasmine.Suite.prototype.execute = function(onComplete) { - var self = this; - this.queue.start(function () { - self.finish(onComplete); - }); -}; -jasmine.WaitsBlock = function(env, timeout, spec) { - this.timeout = timeout; - jasmine.Block.call(this, env, null, spec); -}; - -jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block); - -jasmine.WaitsBlock.prototype.execute = function (onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...'); - } - this.env.setTimeout(function () { - onComplete(); - }, this.timeout); -}; -/** - * A block which waits for some condition to become true, with timeout. - * - * @constructor - * @extends jasmine.Block - * @param {jasmine.Env} env The Jasmine environment. - * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true. - * @param {Function} latchFunction A function which returns true when the desired condition has been met. - * @param {String} message The message to display if the desired condition hasn't been met within the given time period. - * @param {jasmine.Spec} spec The Jasmine spec. - */ -jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) { - this.timeout = timeout || env.defaultTimeoutInterval; - this.latchFunction = latchFunction; - this.message = message; - this.totalTimeSpentWaitingForLatch = 0; - jasmine.Block.call(this, env, null, spec); -}; -jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block); - -jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10; - -jasmine.WaitsForBlock.prototype.execute = function(onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')); - } - var latchFunctionResult; - try { - latchFunctionResult = this.latchFunction.apply(this.spec); - } catch (e) { - this.spec.fail(e); - onComplete(); - return; - } - - if (latchFunctionResult) { - onComplete(); - } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) { - var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen'); - this.spec.fail({ - name: 'timeout', - message: message - }); - - this.abort = true; - onComplete(); - } else { - this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT; - var self = this; - this.env.setTimeout(function() { - self.execute(onComplete); - }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT); - } -}; - -jasmine.version_= { - "major": 1, - "minor": 2, - "build": 0, - "revision": 1337005947 -}; diff --git a/test/jasmine/lib/jasmine-1.3.1/MIT.LICENSE b/test/jasmine/lib/jasmine-1.3.1/MIT.LICENSE deleted file mode 100644 index 7c435ba..0000000 --- a/test/jasmine/lib/jasmine-1.3.1/MIT.LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008-2011 Pivotal Labs - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/test/jasmine/lib/jasmine-1.3.1/jasmine-html.js b/test/jasmine/lib/jasmine-1.3.1/jasmine-html.js deleted file mode 100644 index 543d569..0000000 --- a/test/jasmine/lib/jasmine-1.3.1/jasmine-html.js +++ /dev/null @@ -1,681 +0,0 @@ -jasmine.HtmlReporterHelpers = {}; - -jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) { - var el = document.createElement(type); - - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - - if (typeof child === 'string') { - el.appendChild(document.createTextNode(child)); - } else { - if (child) { - el.appendChild(child); - } - } - } - - for (var attr in attrs) { - if (attr == "className") { - el[attr] = attrs[attr]; - } else { - el.setAttribute(attr, attrs[attr]); - } - } - - return el; -}; - -jasmine.HtmlReporterHelpers.getSpecStatus = function(child) { - var results = child.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.skipped) { - status = 'skipped'; - } - - return status; -}; - -jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) { - var parentDiv = this.dom.summary; - var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite'; - var parent = child[parentSuite]; - - if (parent) { - if (typeof this.views.suites[parent.id] == 'undefined') { - this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views); - } - parentDiv = this.views.suites[parent.id].element; - } - - parentDiv.appendChild(childElement); -}; - - -jasmine.HtmlReporterHelpers.addHelpers = function(ctor) { - for(var fn in jasmine.HtmlReporterHelpers) { - ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn]; - } -}; - -jasmine.HtmlReporter = function(_doc) { - var self = this; - var doc = _doc || window.document; - - var reporterView; - - var dom = {}; - - // Jasmine Reporter Public Interface - self.logRunningSpecs = false; - - self.reportRunnerStarting = function(runner) { - var specs = runner.specs() || []; - - if (specs.length == 0) { - return; - } - - createReporterDom(runner.env.versionString()); - doc.body.appendChild(dom.reporter); - setExceptionHandling(); - - reporterView = new jasmine.HtmlReporter.ReporterView(dom); - reporterView.addSpecs(specs, self.specFilter); - }; - - self.reportRunnerResults = function(runner) { - reporterView && reporterView.complete(); - }; - - self.reportSuiteResults = function(suite) { - reporterView.suiteComplete(suite); - }; - - self.reportSpecStarting = function(spec) { - if (self.logRunningSpecs) { - self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); - } - }; - - self.reportSpecResults = function(spec) { - reporterView.specComplete(spec); - }; - - self.log = function() { - var console = jasmine.getGlobal().console; - if (console && console.log) { - if (console.log.apply) { - console.log.apply(console, arguments); - } else { - console.log(arguments); // ie fix: console.log.apply doesn't exist on ie - } - } - }; - - self.specFilter = function(spec) { - if (!focusedSpecName()) { - return true; - } - - return spec.getFullName().indexOf(focusedSpecName()) === 0; - }; - - return self; - - function focusedSpecName() { - var specName; - - (function memoizeFocusedSpec() { - if (specName) { - return; - } - - var paramMap = []; - var params = jasmine.HtmlReporter.parameters(doc); - - for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); - } - - specName = paramMap.spec; - })(); - - return specName; - } - - function createReporterDom(version) { - dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' }, - dom.banner = self.createDom('div', { className: 'banner' }, - self.createDom('span', { className: 'title' }, "Jasmine "), - self.createDom('span', { className: 'version' }, version)), - - dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}), - dom.alert = self.createDom('div', {className: 'alert'}, - self.createDom('span', { className: 'exceptions' }, - self.createDom('label', { className: 'label', 'for': 'no_try_catch' }, 'No try/catch'), - self.createDom('input', { id: 'no_try_catch', type: 'checkbox' }))), - dom.results = self.createDom('div', {className: 'results'}, - dom.summary = self.createDom('div', { className: 'summary' }), - dom.details = self.createDom('div', { id: 'details' })) - ); - } - - function noTryCatch() { - return window.location.search.match(/catch=false/); - } - - function searchWithCatch() { - var params = jasmine.HtmlReporter.parameters(window.document); - var removed = false; - var i = 0; - - while (!removed && i < params.length) { - if (params[i].match(/catch=/)) { - params.splice(i, 1); - removed = true; - } - i++; - } - if (jasmine.CATCH_EXCEPTIONS) { - params.push("catch=false"); - } - - return params.join("&"); - } - - function setExceptionHandling() { - var chxCatch = document.getElementById('no_try_catch'); - - if (noTryCatch()) { - chxCatch.setAttribute('checked', true); - jasmine.CATCH_EXCEPTIONS = false; - } - chxCatch.onclick = function() { - window.location.search = searchWithCatch(); - }; - } -}; -jasmine.HtmlReporter.parameters = function(doc) { - var paramStr = doc.location.search.substring(1); - var params = []; - - if (paramStr.length > 0) { - params = paramStr.split('&'); - } - return params; -} -jasmine.HtmlReporter.sectionLink = function(sectionName) { - var link = '?'; - var params = []; - - if (sectionName) { - params.push('spec=' + encodeURIComponent(sectionName)); - } - if (!jasmine.CATCH_EXCEPTIONS) { - params.push("catch=false"); - } - if (params.length > 0) { - link += params.join("&"); - } - - return link; -}; -jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter); -jasmine.HtmlReporter.ReporterView = function(dom) { - this.startedAt = new Date(); - this.runningSpecCount = 0; - this.completeSpecCount = 0; - this.passedCount = 0; - this.failedCount = 0; - this.skippedCount = 0; - - this.createResultsMenu = function() { - this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'}, - this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'), - ' | ', - this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing')); - - this.summaryMenuItem.onclick = function() { - dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, ''); - }; - - this.detailsMenuItem.onclick = function() { - showDetails(); - }; - }; - - this.addSpecs = function(specs, specFilter) { - this.totalSpecCount = specs.length; - - this.views = { - specs: {}, - suites: {} - }; - - for (var i = 0; i < specs.length; i++) { - var spec = specs[i]; - this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views); - if (specFilter(spec)) { - this.runningSpecCount++; - } - } - }; - - this.specComplete = function(spec) { - this.completeSpecCount++; - - if (isUndefined(this.views.specs[spec.id])) { - this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom); - } - - var specView = this.views.specs[spec.id]; - - switch (specView.status()) { - case 'passed': - this.passedCount++; - break; - - case 'failed': - this.failedCount++; - break; - - case 'skipped': - this.skippedCount++; - break; - } - - specView.refresh(); - this.refresh(); - }; - - this.suiteComplete = function(suite) { - var suiteView = this.views.suites[suite.id]; - if (isUndefined(suiteView)) { - return; - } - suiteView.refresh(); - }; - - this.refresh = function() { - - if (isUndefined(this.resultsMenu)) { - this.createResultsMenu(); - } - - // currently running UI - if (isUndefined(this.runningAlert)) { - this.runningAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "runningAlert bar" }); - dom.alert.appendChild(this.runningAlert); - } - this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount); - - // skipped specs UI - if (isUndefined(this.skippedAlert)) { - this.skippedAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "skippedAlert bar" }); - } - - this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; - - if (this.skippedCount === 1 && isDefined(dom.alert)) { - dom.alert.appendChild(this.skippedAlert); - } - - // passing specs UI - if (isUndefined(this.passedAlert)) { - this.passedAlert = this.createDom('span', { href: jasmine.HtmlReporter.sectionLink(), className: "passingAlert bar" }); - } - this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount); - - // failing specs UI - if (isUndefined(this.failedAlert)) { - this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"}); - } - this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount); - - if (this.failedCount === 1 && isDefined(dom.alert)) { - dom.alert.appendChild(this.failedAlert); - dom.alert.appendChild(this.resultsMenu); - } - - // summary info - this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount); - this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing"; - }; - - this.complete = function() { - dom.alert.removeChild(this.runningAlert); - - this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; - - if (this.failedCount === 0) { - dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount))); - } else { - showDetails(); - } - - dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s")); - }; - - return this; - - function showDetails() { - if (dom.reporter.className.search(/showDetails/) === -1) { - dom.reporter.className += " showDetails"; - } - } - - function isUndefined(obj) { - return typeof obj === 'undefined'; - } - - function isDefined(obj) { - return !isUndefined(obj); - } - - function specPluralizedFor(count) { - var str = count + " spec"; - if (count > 1) { - str += "s" - } - return str; - } - -}; - -jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView); - - -jasmine.HtmlReporter.SpecView = function(spec, dom, views) { - this.spec = spec; - this.dom = dom; - this.views = views; - - this.symbol = this.createDom('li', { className: 'pending' }); - this.dom.symbolSummary.appendChild(this.symbol); - - this.summary = this.createDom('div', { className: 'specSummary' }, - this.createDom('a', { - className: 'description', - href: jasmine.HtmlReporter.sectionLink(this.spec.getFullName()), - title: this.spec.getFullName() - }, this.spec.description) - ); - - this.detail = this.createDom('div', { className: 'specDetail' }, - this.createDom('a', { - className: 'description', - href: '?spec=' + encodeURIComponent(this.spec.getFullName()), - title: this.spec.getFullName() - }, this.spec.getFullName()) - ); -}; - -jasmine.HtmlReporter.SpecView.prototype.status = function() { - return this.getSpecStatus(this.spec); -}; - -jasmine.HtmlReporter.SpecView.prototype.refresh = function() { - this.symbol.className = this.status(); - - switch (this.status()) { - case 'skipped': - break; - - case 'passed': - this.appendSummaryToSuiteDiv(); - break; - - case 'failed': - this.appendSummaryToSuiteDiv(); - this.appendFailureDetail(); - break; - } -}; - -jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() { - this.summary.className += ' ' + this.status(); - this.appendToSummary(this.spec, this.summary); -}; - -jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() { - this.detail.className += ' ' + this.status(); - - var resultItems = this.spec.results().getItems(); - var messagesDiv = this.createDom('div', { className: 'messages' }); - - for (var i = 0; i < resultItems.length; i++) { - var result = resultItems[i]; - - if (result.type == 'log') { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); - } else if (result.type == 'expect' && result.passed && !result.passed()) { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); - - if (result.trace.stack) { - messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); - } - } - } - - if (messagesDiv.childNodes.length > 0) { - this.detail.appendChild(messagesDiv); - this.dom.details.appendChild(this.detail); - } -}; - -jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) { - this.suite = suite; - this.dom = dom; - this.views = views; - - this.element = this.createDom('div', { className: 'suite' }, - this.createDom('a', { className: 'description', href: jasmine.HtmlReporter.sectionLink(this.suite.getFullName()) }, this.suite.description) - ); - - this.appendToSummary(this.suite, this.element); -}; - -jasmine.HtmlReporter.SuiteView.prototype.status = function() { - return this.getSpecStatus(this.suite); -}; - -jasmine.HtmlReporter.SuiteView.prototype.refresh = function() { - this.element.className += " " + this.status(); -}; - -jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView); - -/* @deprecated Use jasmine.HtmlReporter instead - */ -jasmine.TrivialReporter = function(doc) { - this.document = doc || document; - this.suiteDivs = {}; - this.logRunningSpecs = false; -}; - -jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { - var el = document.createElement(type); - - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - - if (typeof child === 'string') { - el.appendChild(document.createTextNode(child)); - } else { - if (child) { el.appendChild(child); } - } - } - - for (var attr in attrs) { - if (attr == "className") { - el[attr] = attrs[attr]; - } else { - el.setAttribute(attr, attrs[attr]); - } - } - - return el; -}; - -jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { - var showPassed, showSkipped; - - this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' }, - this.createDom('div', { className: 'banner' }, - this.createDom('div', { className: 'logo' }, - this.createDom('span', { className: 'title' }, "Jasmine"), - this.createDom('span', { className: 'version' }, runner.env.versionString())), - this.createDom('div', { className: 'options' }, - "Show ", - showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), - showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") - ) - ), - - this.runnerDiv = this.createDom('div', { className: 'runner running' }, - this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), - this.runnerMessageSpan = this.createDom('span', {}, "Running..."), - this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) - ); - - this.document.body.appendChild(this.outerDiv); - - var suites = runner.suites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - var suiteDiv = this.createDom('div', { className: 'suite' }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), - this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); - this.suiteDivs[suite.id] = suiteDiv; - var parentDiv = this.outerDiv; - if (suite.parentSuite) { - parentDiv = this.suiteDivs[suite.parentSuite.id]; - } - parentDiv.appendChild(suiteDiv); - } - - this.startedAt = new Date(); - - var self = this; - showPassed.onclick = function(evt) { - if (showPassed.checked) { - self.outerDiv.className += ' show-passed'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); - } - }; - - showSkipped.onclick = function(evt) { - if (showSkipped.checked) { - self.outerDiv.className += ' show-skipped'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); - } - }; -}; - -jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { - var results = runner.results(); - var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; - this.runnerDiv.setAttribute("class", className); - //do it twice for IE - this.runnerDiv.setAttribute("className", className); - var specs = runner.specs(); - var specCount = 0; - for (var i = 0; i < specs.length; i++) { - if (this.specFilter(specs[i])) { - specCount++; - } - } - var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); - message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; - this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); - - this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); -}; - -jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { - var results = suite.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.totalCount === 0) { // todo: change this to check results.skipped - status = 'skipped'; - } - this.suiteDivs[suite.id].className += " " + status; -}; - -jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { - if (this.logRunningSpecs) { - this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); - } -}; - -jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { - var results = spec.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.skipped) { - status = 'skipped'; - } - var specDiv = this.createDom('div', { className: 'spec ' + status }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), - this.createDom('a', { - className: 'description', - href: '?spec=' + encodeURIComponent(spec.getFullName()), - title: spec.getFullName() - }, spec.description)); - - - var resultItems = results.getItems(); - var messagesDiv = this.createDom('div', { className: 'messages' }); - for (var i = 0; i < resultItems.length; i++) { - var result = resultItems[i]; - - if (result.type == 'log') { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); - } else if (result.type == 'expect' && result.passed && !result.passed()) { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); - - if (result.trace.stack) { - messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); - } - } - } - - if (messagesDiv.childNodes.length > 0) { - specDiv.appendChild(messagesDiv); - } - - this.suiteDivs[spec.suite.id].appendChild(specDiv); -}; - -jasmine.TrivialReporter.prototype.log = function() { - var console = jasmine.getGlobal().console; - if (console && console.log) { - if (console.log.apply) { - console.log.apply(console, arguments); - } else { - console.log(arguments); // ie fix: console.log.apply doesn't exist on ie - } - } -}; - -jasmine.TrivialReporter.prototype.getLocation = function() { - return this.document.location; -}; - -jasmine.TrivialReporter.prototype.specFilter = function(spec) { - var paramMap = {}; - var params = this.getLocation().search.substring(1).split('&'); - for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); - } - - if (!paramMap.spec) { - return true; - } - return spec.getFullName().indexOf(paramMap.spec) === 0; -}; diff --git a/test/jasmine/lib/jasmine-1.3.1/jasmine.css b/test/jasmine/lib/jasmine-1.3.1/jasmine.css deleted file mode 100644 index 8c008dc..0000000 --- a/test/jasmine/lib/jasmine-1.3.1/jasmine.css +++ /dev/null @@ -1,82 +0,0 @@ -body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; } - -#HTMLReporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; } -#HTMLReporter a { text-decoration: none; } -#HTMLReporter a:hover { text-decoration: underline; } -#HTMLReporter p, #HTMLReporter h1, #HTMLReporter h2, #HTMLReporter h3, #HTMLReporter h4, #HTMLReporter h5, #HTMLReporter h6 { margin: 0; line-height: 14px; } -#HTMLReporter .banner, #HTMLReporter .symbolSummary, #HTMLReporter .summary, #HTMLReporter .resultMessage, #HTMLReporter .specDetail .description, #HTMLReporter .alert .bar, #HTMLReporter .stackTrace { padding-left: 9px; padding-right: 9px; } -#HTMLReporter #jasmine_content { position: fixed; right: 100%; } -#HTMLReporter .version { color: #aaaaaa; } -#HTMLReporter .banner { margin-top: 14px; } -#HTMLReporter .duration { color: #aaaaaa; float: right; } -#HTMLReporter .symbolSummary { overflow: hidden; *zoom: 1; margin: 14px 0; } -#HTMLReporter .symbolSummary li { display: block; float: left; height: 7px; width: 14px; margin-bottom: 7px; font-size: 16px; } -#HTMLReporter .symbolSummary li.passed { font-size: 14px; } -#HTMLReporter .symbolSummary li.passed:before { color: #5e7d00; content: "\02022"; } -#HTMLReporter .symbolSummary li.failed { line-height: 9px; } -#HTMLReporter .symbolSummary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; } -#HTMLReporter .symbolSummary li.skipped { font-size: 14px; } -#HTMLReporter .symbolSummary li.skipped:before { color: #bababa; content: "\02022"; } -#HTMLReporter .symbolSummary li.pending { line-height: 11px; } -#HTMLReporter .symbolSummary li.pending:before { color: #aaaaaa; content: "-"; } -#HTMLReporter .exceptions { color: #fff; float: right; margin-top: 5px; margin-right: 5px; } -#HTMLReporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; } -#HTMLReporter .runningAlert { background-color: #666666; } -#HTMLReporter .skippedAlert { background-color: #aaaaaa; } -#HTMLReporter .skippedAlert:first-child { background-color: #333333; } -#HTMLReporter .skippedAlert:hover { text-decoration: none; color: white; text-decoration: underline; } -#HTMLReporter .passingAlert { background-color: #a6b779; } -#HTMLReporter .passingAlert:first-child { background-color: #5e7d00; } -#HTMLReporter .failingAlert { background-color: #cf867e; } -#HTMLReporter .failingAlert:first-child { background-color: #b03911; } -#HTMLReporter .results { margin-top: 14px; } -#HTMLReporter #details { display: none; } -#HTMLReporter .resultsMenu, #HTMLReporter .resultsMenu a { background-color: #fff; color: #333333; } -#HTMLReporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; } -#HTMLReporter.showDetails .summaryMenuItem:hover { text-decoration: underline; } -#HTMLReporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; } -#HTMLReporter.showDetails .summary { display: none; } -#HTMLReporter.showDetails #details { display: block; } -#HTMLReporter .summaryMenuItem { font-weight: bold; text-decoration: underline; } -#HTMLReporter .summary { margin-top: 14px; } -#HTMLReporter .summary .suite .suite, #HTMLReporter .summary .specSummary { margin-left: 14px; } -#HTMLReporter .summary .specSummary.passed a { color: #5e7d00; } -#HTMLReporter .summary .specSummary.failed a { color: #b03911; } -#HTMLReporter .description + .suite { margin-top: 0; } -#HTMLReporter .suite { margin-top: 14px; } -#HTMLReporter .suite a { color: #333333; } -#HTMLReporter #details .specDetail { margin-bottom: 28px; } -#HTMLReporter #details .specDetail .description { display: block; color: white; background-color: #b03911; } -#HTMLReporter .resultMessage { padding-top: 14px; color: #333333; } -#HTMLReporter .resultMessage span.result { display: block; } -#HTMLReporter .stackTrace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; } - -#TrivialReporter { padding: 8px 13px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; overflow-y: scroll; background-color: white; font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; /*.resultMessage {*/ /*white-space: pre;*/ /*}*/ } -#TrivialReporter a:visited, #TrivialReporter a { color: #303; } -#TrivialReporter a:hover, #TrivialReporter a:active { color: blue; } -#TrivialReporter .run_spec { float: right; padding-right: 5px; font-size: .8em; text-decoration: none; } -#TrivialReporter .banner { color: #303; background-color: #fef; padding: 5px; } -#TrivialReporter .logo { float: left; font-size: 1.1em; padding-left: 5px; } -#TrivialReporter .logo .version { font-size: .6em; padding-left: 1em; } -#TrivialReporter .runner.running { background-color: yellow; } -#TrivialReporter .options { text-align: right; font-size: .8em; } -#TrivialReporter .suite { border: 1px outset gray; margin: 5px 0; padding-left: 1em; } -#TrivialReporter .suite .suite { margin: 5px; } -#TrivialReporter .suite.passed { background-color: #dfd; } -#TrivialReporter .suite.failed { background-color: #fdd; } -#TrivialReporter .spec { margin: 5px; padding-left: 1em; clear: both; } -#TrivialReporter .spec.failed, #TrivialReporter .spec.passed, #TrivialReporter .spec.skipped { padding-bottom: 5px; border: 1px solid gray; } -#TrivialReporter .spec.failed { background-color: #fbb; border-color: red; } -#TrivialReporter .spec.passed { background-color: #bfb; border-color: green; } -#TrivialReporter .spec.skipped { background-color: #bbb; } -#TrivialReporter .messages { border-left: 1px dashed gray; padding-left: 1em; padding-right: 1em; } -#TrivialReporter .passed { background-color: #cfc; display: none; } -#TrivialReporter .failed { background-color: #fbb; } -#TrivialReporter .skipped { color: #777; background-color: #eee; display: none; } -#TrivialReporter .resultMessage span.result { display: block; line-height: 2em; color: black; } -#TrivialReporter .resultMessage .mismatch { color: black; } -#TrivialReporter .stackTrace { white-space: pre; font-size: .8em; margin-left: 10px; max-height: 5em; overflow: auto; border: 1px inset red; padding: 1em; background: #eef; } -#TrivialReporter .finished-at { padding-left: 1em; font-size: .6em; } -#TrivialReporter.show-passed .passed, #TrivialReporter.show-skipped .skipped { display: block; } -#TrivialReporter #jasmine_content { position: fixed; right: 100%; } -#TrivialReporter .runner { border: 1px solid gray; display: block; margin: 5px 0; padding: 2px 0 2px 10px; } diff --git a/test/jasmine/lib/jasmine-1.3.1/jasmine.js b/test/jasmine/lib/jasmine-1.3.1/jasmine.js deleted file mode 100644 index 6b3459b..0000000 --- a/test/jasmine/lib/jasmine-1.3.1/jasmine.js +++ /dev/null @@ -1,2600 +0,0 @@ -var isCommonJS = typeof window == "undefined" && typeof exports == "object"; - -/** - * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework. - * - * @namespace - */ -var jasmine = {}; -if (isCommonJS) exports.jasmine = jasmine; -/** - * @private - */ -jasmine.unimplementedMethod_ = function() { - throw new Error("unimplemented method"); -}; - -/** - * Use jasmine.undefined instead of undefined, since undefined is just - * a plain old variable and may be redefined by somebody else. - * - * @private - */ -jasmine.undefined = jasmine.___undefined___; - -/** - * Show diagnostic messages in the console if set to true - * - */ -jasmine.VERBOSE = false; - -/** - * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed. - * - */ -jasmine.DEFAULT_UPDATE_INTERVAL = 250; - -/** - * Maximum levels of nesting that will be included when an object is pretty-printed - */ -jasmine.MAX_PRETTY_PRINT_DEPTH = 40; - -/** - * Default timeout interval in milliseconds for waitsFor() blocks. - */ -jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; - -/** - * By default exceptions thrown in the context of a test are caught by jasmine so that it can run the remaining tests in the suite. - * Set to false to let the exception bubble up in the browser. - * - */ -jasmine.CATCH_EXCEPTIONS = true; - -jasmine.getGlobal = function() { - function getGlobal() { - return this; - } - - return getGlobal(); -}; - -/** - * Allows for bound functions to be compared. Internal use only. - * - * @ignore - * @private - * @param base {Object} bound 'this' for the function - * @param name {Function} function to find - */ -jasmine.bindOriginal_ = function(base, name) { - var original = base[name]; - if (original.apply) { - return function() { - return original.apply(base, arguments); - }; - } else { - // IE support - return jasmine.getGlobal()[name]; - } -}; - -jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout'); -jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout'); -jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval'); -jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval'); - -jasmine.MessageResult = function(values) { - this.type = 'log'; - this.values = values; - this.trace = new Error(); // todo: test better -}; - -jasmine.MessageResult.prototype.toString = function() { - var text = ""; - for (var i = 0; i < this.values.length; i++) { - if (i > 0) text += " "; - if (jasmine.isString_(this.values[i])) { - text += this.values[i]; - } else { - text += jasmine.pp(this.values[i]); - } - } - return text; -}; - -jasmine.ExpectationResult = function(params) { - this.type = 'expect'; - this.matcherName = params.matcherName; - this.passed_ = params.passed; - this.expected = params.expected; - this.actual = params.actual; - this.message = this.passed_ ? 'Passed.' : params.message; - - var trace = (params.trace || new Error(this.message)); - this.trace = this.passed_ ? '' : trace; -}; - -jasmine.ExpectationResult.prototype.toString = function () { - return this.message; -}; - -jasmine.ExpectationResult.prototype.passed = function () { - return this.passed_; -}; - -/** - * Getter for the Jasmine environment. Ensures one gets created - */ -jasmine.getEnv = function() { - var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env(); - return env; -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isArray_ = function(value) { - return jasmine.isA_("Array", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isString_ = function(value) { - return jasmine.isA_("String", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isNumber_ = function(value) { - return jasmine.isA_("Number", value); -}; - -/** - * @ignore - * @private - * @param {String} typeName - * @param value - * @returns {Boolean} - */ -jasmine.isA_ = function(typeName, value) { - return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; -}; - -/** - * Pretty printer for expecations. Takes any object and turns it into a human-readable string. - * - * @param value {Object} an object to be outputted - * @returns {String} - */ -jasmine.pp = function(value) { - var stringPrettyPrinter = new jasmine.StringPrettyPrinter(); - stringPrettyPrinter.format(value); - return stringPrettyPrinter.string; -}; - -/** - * Returns true if the object is a DOM Node. - * - * @param {Object} obj object to check - * @returns {Boolean} - */ -jasmine.isDomNode = function(obj) { - return obj.nodeType > 0; -}; - -/** - * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter. - * - * @example - * // don't care about which function is passed in, as long as it's a function - * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function)); - * - * @param {Class} clazz - * @returns matchable object of the type clazz - */ -jasmine.any = function(clazz) { - return new jasmine.Matchers.Any(clazz); -}; - -/** - * Returns a matchable subset of a JSON object. For use in expectations when you don't care about all of the - * attributes on the object. - * - * @example - * // don't care about any other attributes than foo. - * expect(mySpy).toHaveBeenCalledWith(jasmine.objectContaining({foo: "bar"}); - * - * @param sample {Object} sample - * @returns matchable object for the sample - */ -jasmine.objectContaining = function (sample) { - return new jasmine.Matchers.ObjectContaining(sample); -}; - -/** - * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. - * - * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine - * expectation syntax. Spies can be checked if they were called or not and what the calling params were. - * - * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs). - * - * Spies are torn down at the end of every spec. - * - * Note: Do not call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj. - * - * @example - * // a stub - * var myStub = jasmine.createSpy('myStub'); // can be used anywhere - * - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // actual foo.not will not be called, execution stops - * spyOn(foo, 'not'); - - // foo.not spied upon, execution will continue to implementation - * spyOn(foo, 'not').andCallThrough(); - * - * // fake example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // foo.not(val) will return val - * spyOn(foo, 'not').andCallFake(function(value) {return value;}); - * - * // mock example - * foo.not(7 == 7); - * expect(foo.not).toHaveBeenCalled(); - * expect(foo.not).toHaveBeenCalledWith(true); - * - * @constructor - * @see spyOn, jasmine.createSpy, jasmine.createSpyObj - * @param {String} name - */ -jasmine.Spy = function(name) { - /** - * The name of the spy, if provided. - */ - this.identity = name || 'unknown'; - /** - * Is this Object a spy? - */ - this.isSpy = true; - /** - * The actual function this spy stubs. - */ - this.plan = function() { - }; - /** - * Tracking of the most recent call to the spy. - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy.mostRecentCall.args = [1, 2]; - */ - this.mostRecentCall = {}; - - /** - * Holds arguments for each call to the spy, indexed by call count - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy(7, 8); - * mySpy.mostRecentCall.args = [7, 8]; - * mySpy.argsForCall[0] = [1, 2]; - * mySpy.argsForCall[1] = [7, 8]; - */ - this.argsForCall = []; - this.calls = []; -}; - -/** - * Tells a spy to call through to the actual implemenatation. - * - * @example - * var foo = { - * bar: function() { // do some stuff } - * } - * - * // defining a spy on an existing property: foo.bar - * spyOn(foo, 'bar').andCallThrough(); - */ -jasmine.Spy.prototype.andCallThrough = function() { - this.plan = this.originalValue; - return this; -}; - -/** - * For setting the return value of a spy. - * - * @example - * // defining a spy from scratch: foo() returns 'baz' - * var foo = jasmine.createSpy('spy on foo').andReturn('baz'); - * - * // defining a spy on an existing property: foo.bar() returns 'baz' - * spyOn(foo, 'bar').andReturn('baz'); - * - * @param {Object} value - */ -jasmine.Spy.prototype.andReturn = function(value) { - this.plan = function() { - return value; - }; - return this; -}; - -/** - * For throwing an exception when a spy is called. - * - * @example - * // defining a spy from scratch: foo() throws an exception w/ message 'ouch' - * var foo = jasmine.createSpy('spy on foo').andThrow('baz'); - * - * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch' - * spyOn(foo, 'bar').andThrow('baz'); - * - * @param {String} exceptionMsg - */ -jasmine.Spy.prototype.andThrow = function(exceptionMsg) { - this.plan = function() { - throw exceptionMsg; - }; - return this; -}; - -/** - * Calls an alternate implementation when a spy is called. - * - * @example - * var baz = function() { - * // do some stuff, return something - * } - * // defining a spy from scratch: foo() calls the function baz - * var foo = jasmine.createSpy('spy on foo').andCall(baz); - * - * // defining a spy on an existing property: foo.bar() calls an anonymnous function - * spyOn(foo, 'bar').andCall(function() { return 'baz';} ); - * - * @param {Function} fakeFunc - */ -jasmine.Spy.prototype.andCallFake = function(fakeFunc) { - this.plan = fakeFunc; - return this; -}; - -/** - * Resets all of a spy's the tracking variables so that it can be used again. - * - * @example - * spyOn(foo, 'bar'); - * - * foo.bar(); - * - * expect(foo.bar.callCount).toEqual(1); - * - * foo.bar.reset(); - * - * expect(foo.bar.callCount).toEqual(0); - */ -jasmine.Spy.prototype.reset = function() { - this.wasCalled = false; - this.callCount = 0; - this.argsForCall = []; - this.calls = []; - this.mostRecentCall = {}; -}; - -jasmine.createSpy = function(name) { - - var spyObj = function() { - spyObj.wasCalled = true; - spyObj.callCount++; - var args = jasmine.util.argsToArray(arguments); - spyObj.mostRecentCall.object = this; - spyObj.mostRecentCall.args = args; - spyObj.argsForCall.push(args); - spyObj.calls.push({object: this, args: args}); - return spyObj.plan.apply(this, arguments); - }; - - var spy = new jasmine.Spy(name); - - for (var prop in spy) { - spyObj[prop] = spy[prop]; - } - - spyObj.reset(); - - return spyObj; -}; - -/** - * Determines whether an object is a spy. - * - * @param {jasmine.Spy|Object} putativeSpy - * @returns {Boolean} - */ -jasmine.isSpy = function(putativeSpy) { - return putativeSpy && putativeSpy.isSpy; -}; - -/** - * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something - * large in one call. - * - * @param {String} baseName name of spy class - * @param {Array} methodNames array of names of methods to make spies - */ -jasmine.createSpyObj = function(baseName, methodNames) { - if (!jasmine.isArray_(methodNames) || methodNames.length === 0) { - throw new Error('createSpyObj requires a non-empty array of method names to create spies for'); - } - var obj = {}; - for (var i = 0; i < methodNames.length; i++) { - obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]); - } - return obj; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the current spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.log = function() { - var spec = jasmine.getEnv().currentSpec; - spec.log.apply(spec, arguments); -}; - -/** - * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy. - * - * @example - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops - * - * @see jasmine.createSpy - * @param obj - * @param methodName - * @return {jasmine.Spy} a Jasmine spy that can be chained with all spy methods - */ -var spyOn = function(obj, methodName) { - return jasmine.getEnv().currentSpec.spyOn(obj, methodName); -}; -if (isCommonJS) exports.spyOn = spyOn; - -/** - * Creates a Jasmine spec that will be added to the current suite. - * - * // TODO: pending tests - * - * @example - * it('should be true', function() { - * expect(true).toEqual(true); - * }); - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var it = function(desc, func) { - return jasmine.getEnv().it(desc, func); -}; -if (isCommonJS) exports.it = it; - -/** - * Creates a disabled Jasmine spec. - * - * A convenience method that allows existing specs to be disabled temporarily during development. - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var xit = function(desc, func) { - return jasmine.getEnv().xit(desc, func); -}; -if (isCommonJS) exports.xit = xit; - -/** - * Starts a chain for a Jasmine expectation. - * - * It is passed an Object that is the actual value and should chain to one of the many - * jasmine.Matchers functions. - * - * @param {Object} actual Actual value to test against and expected value - * @return {jasmine.Matchers} - */ -var expect = function(actual) { - return jasmine.getEnv().currentSpec.expect(actual); -}; -if (isCommonJS) exports.expect = expect; - -/** - * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs. - * - * @param {Function} func Function that defines part of a jasmine spec. - */ -var runs = function(func) { - jasmine.getEnv().currentSpec.runs(func); -}; -if (isCommonJS) exports.runs = runs; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -var waits = function(timeout) { - jasmine.getEnv().currentSpec.waits(timeout); -}; -if (isCommonJS) exports.waits = waits; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); -}; -if (isCommonJS) exports.waitsFor = waitsFor; - -/** - * A function that is called before each spec in a suite. - * - * Used for spec setup, including validating assumptions. - * - * @param {Function} beforeEachFunction - */ -var beforeEach = function(beforeEachFunction) { - jasmine.getEnv().beforeEach(beforeEachFunction); -}; -if (isCommonJS) exports.beforeEach = beforeEach; - -/** - * A function that is called after each spec in a suite. - * - * Used for restoring any state that is hijacked during spec execution. - * - * @param {Function} afterEachFunction - */ -var afterEach = function(afterEachFunction) { - jasmine.getEnv().afterEach(afterEachFunction); -}; -if (isCommonJS) exports.afterEach = afterEach; - -/** - * Defines a suite of specifications. - * - * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared - * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization - * of setup in some tests. - * - * @example - * // TODO: a simple suite - * - * // TODO: a simple suite with a nested describe block - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var describe = function(description, specDefinitions) { - return jasmine.getEnv().describe(description, specDefinitions); -}; -if (isCommonJS) exports.describe = describe; - -/** - * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development. - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var xdescribe = function(description, specDefinitions) { - return jasmine.getEnv().xdescribe(description, specDefinitions); -}; -if (isCommonJS) exports.xdescribe = xdescribe; - - -// Provide the XMLHttpRequest class for IE 5.x-6.x: -jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() { - function tryIt(f) { - try { - return f(); - } catch(e) { - } - return null; - } - - var xhr = tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.6.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.3.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP"); - }) || - tryIt(function() { - return new ActiveXObject("Microsoft.XMLHTTP"); - }); - - if (!xhr) throw new Error("This browser does not support XMLHttpRequest."); - - return xhr; -} : XMLHttpRequest; -/** - * @namespace - */ -jasmine.util = {}; - -/** - * Declare that a child class inherit it's prototype from the parent class. - * - * @private - * @param {Function} childClass - * @param {Function} parentClass - */ -jasmine.util.inherit = function(childClass, parentClass) { - /** - * @private - */ - var subclass = function() { - }; - subclass.prototype = parentClass.prototype; - childClass.prototype = new subclass(); -}; - -jasmine.util.formatException = function(e) { - var lineNumber; - if (e.line) { - lineNumber = e.line; - } - else if (e.lineNumber) { - lineNumber = e.lineNumber; - } - - var file; - - if (e.sourceURL) { - file = e.sourceURL; - } - else if (e.fileName) { - file = e.fileName; - } - - var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString(); - - if (file && lineNumber) { - message += ' in ' + file + ' (line ' + lineNumber + ')'; - } - - return message; -}; - -jasmine.util.htmlEscape = function(str) { - if (!str) return str; - return str.replace(/&/g, '&') - .replace(//g, '>'); -}; - -jasmine.util.argsToArray = function(args) { - var arrayOfArgs = []; - for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]); - return arrayOfArgs; -}; - -jasmine.util.extend = function(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; -}; - -/** - * Environment for Jasmine - * - * @constructor - */ -jasmine.Env = function() { - this.currentSpec = null; - this.currentSuite = null; - this.currentRunner_ = new jasmine.Runner(this); - - this.reporter = new jasmine.MultiReporter(); - - this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; - this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; - this.lastUpdate = 0; - this.specFilter = function() { - return true; - }; - - this.nextSpecId_ = 0; - this.nextSuiteId_ = 0; - this.equalityTesters_ = []; - - // wrap matchers - this.matchersClass = function() { - jasmine.Matchers.apply(this, arguments); - }; - jasmine.util.inherit(this.matchersClass, jasmine.Matchers); - - jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); -}; - - -jasmine.Env.prototype.setTimeout = jasmine.setTimeout; -jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; -jasmine.Env.prototype.setInterval = jasmine.setInterval; -jasmine.Env.prototype.clearInterval = jasmine.clearInterval; - -/** - * @returns an object containing jasmine version build info, if set. - */ -jasmine.Env.prototype.version = function () { - if (jasmine.version_) { - return jasmine.version_; - } else { - throw new Error('Version not set'); - } -}; - -/** - * @returns string containing jasmine version build info, if set. - */ -jasmine.Env.prototype.versionString = function() { - if (!jasmine.version_) { - return "version unknown"; - } - - var version = this.version(); - var versionString = version.major + "." + version.minor + "." + version.build; - if (version.release_candidate) { - versionString += ".rc" + version.release_candidate; - } - versionString += " revision " + version.revision; - return versionString; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSpecId = function () { - return this.nextSpecId_++; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSuiteId = function () { - return this.nextSuiteId_++; -}; - -/** - * Register a reporter to receive status updates from Jasmine. - * @param {jasmine.Reporter} reporter An object which will receive status updates. - */ -jasmine.Env.prototype.addReporter = function(reporter) { - this.reporter.addReporter(reporter); -}; - -jasmine.Env.prototype.execute = function() { - this.currentRunner_.execute(); -}; - -jasmine.Env.prototype.describe = function(description, specDefinitions) { - var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); - - var parentSuite = this.currentSuite; - if (parentSuite) { - parentSuite.add(suite); - } else { - this.currentRunner_.add(suite); - } - - this.currentSuite = suite; - - var declarationError = null; - try { - specDefinitions.call(suite); - } catch(e) { - declarationError = e; - } - - if (declarationError) { - this.it("encountered a declaration exception", function() { - throw declarationError; - }); - } - - this.currentSuite = parentSuite; - - return suite; -}; - -jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { - if (this.currentSuite) { - this.currentSuite.beforeEach(beforeEachFunction); - } else { - this.currentRunner_.beforeEach(beforeEachFunction); - } -}; - -jasmine.Env.prototype.currentRunner = function () { - return this.currentRunner_; -}; - -jasmine.Env.prototype.afterEach = function(afterEachFunction) { - if (this.currentSuite) { - this.currentSuite.afterEach(afterEachFunction); - } else { - this.currentRunner_.afterEach(afterEachFunction); - } - -}; - -jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { - return { - execute: function() { - } - }; -}; - -jasmine.Env.prototype.it = function(description, func) { - var spec = new jasmine.Spec(this, this.currentSuite, description); - this.currentSuite.add(spec); - this.currentSpec = spec; - - if (func) { - spec.runs(func); - } - - return spec; -}; - -jasmine.Env.prototype.xit = function(desc, func) { - return { - id: this.nextSpecId(), - runs: function() { - } - }; -}; - -jasmine.Env.prototype.compareRegExps_ = function(a, b, mismatchKeys, mismatchValues) { - if (a.source != b.source) - mismatchValues.push("expected pattern /" + b.source + "/ is not equal to the pattern /" + a.source + "/"); - - if (a.ignoreCase != b.ignoreCase) - mismatchValues.push("expected modifier i was" + (b.ignoreCase ? " " : " not ") + "set and does not equal the origin modifier"); - - if (a.global != b.global) - mismatchValues.push("expected modifier g was" + (b.global ? " " : " not ") + "set and does not equal the origin modifier"); - - if (a.multiline != b.multiline) - mismatchValues.push("expected modifier m was" + (b.multiline ? " " : " not ") + "set and does not equal the origin modifier"); - - if (a.sticky != b.sticky) - mismatchValues.push("expected modifier y was" + (b.sticky ? " " : " not ") + "set and does not equal the origin modifier"); - - return (mismatchValues.length === 0); -}; - -jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { - if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { - return true; - } - - a.__Jasmine_been_here_before__ = b; - b.__Jasmine_been_here_before__ = a; - - var hasKey = function(obj, keyName) { - return obj !== null && obj[keyName] !== jasmine.undefined; - }; - - for (var property in b) { - if (!hasKey(a, property) && hasKey(b, property)) { - mismatchKeys.push("expected has key '" + property + "', but missing from actual."); - } - } - for (property in a) { - if (!hasKey(b, property) && hasKey(a, property)) { - mismatchKeys.push("expected missing key '" + property + "', but present in actual."); - } - } - for (property in b) { - if (property == '__Jasmine_been_here_before__') continue; - if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { - mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); - } - } - - if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { - mismatchValues.push("arrays were not the same length"); - } - - delete a.__Jasmine_been_here_before__; - delete b.__Jasmine_been_here_before__; - return (mismatchKeys.length === 0 && mismatchValues.length === 0); -}; - -jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { - mismatchKeys = mismatchKeys || []; - mismatchValues = mismatchValues || []; - - for (var i = 0; i < this.equalityTesters_.length; i++) { - var equalityTester = this.equalityTesters_[i]; - var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); - if (result !== jasmine.undefined) return result; - } - - if (a === b) return true; - - if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { - return (a == jasmine.undefined && b == jasmine.undefined); - } - - if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { - return a === b; - } - - if (a instanceof Date && b instanceof Date) { - return a.getTime() == b.getTime(); - } - - if (a.jasmineMatches) { - return a.jasmineMatches(b); - } - - if (b.jasmineMatches) { - return b.jasmineMatches(a); - } - - if (a instanceof jasmine.Matchers.ObjectContaining) { - return a.matches(b); - } - - if (b instanceof jasmine.Matchers.ObjectContaining) { - return b.matches(a); - } - - if (jasmine.isString_(a) && jasmine.isString_(b)) { - return (a == b); - } - - if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { - return (a == b); - } - - if (a instanceof RegExp && b instanceof RegExp) { - return this.compareRegExps_(a, b, mismatchKeys, mismatchValues); - } - - if (typeof a === "object" && typeof b === "object") { - return this.compareObjects_(a, b, mismatchKeys, mismatchValues); - } - - //Straight check - return (a === b); -}; - -jasmine.Env.prototype.contains_ = function(haystack, needle) { - if (jasmine.isArray_(haystack)) { - for (var i = 0; i < haystack.length; i++) { - if (this.equals_(haystack[i], needle)) return true; - } - return false; - } - return haystack.indexOf(needle) >= 0; -}; - -jasmine.Env.prototype.addEqualityTester = function(equalityTester) { - this.equalityTesters_.push(equalityTester); -}; -/** No-op base class for Jasmine reporters. - * - * @constructor - */ -jasmine.Reporter = function() { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerStarting = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerResults = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecStarting = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecResults = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.log = function(str) { -}; - -/** - * Blocks are functions with executable code that make up a spec. - * - * @constructor - * @param {jasmine.Env} env - * @param {Function} func - * @param {jasmine.Spec} spec - */ -jasmine.Block = function(env, func, spec) { - this.env = env; - this.func = func; - this.spec = spec; -}; - -jasmine.Block.prototype.execute = function(onComplete) { - if (!jasmine.CATCH_EXCEPTIONS) { - this.func.apply(this.spec); - } - else { - try { - this.func.apply(this.spec); - } catch (e) { - this.spec.fail(e); - } - } - onComplete(); -}; -/** JavaScript API reporter. - * - * @constructor - */ -jasmine.JsApiReporter = function() { - this.started = false; - this.finished = false; - this.suites_ = []; - this.results_ = {}; -}; - -jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) { - this.started = true; - var suites = runner.topLevelSuites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - this.suites_.push(this.summarize_(suite)); - } -}; - -jasmine.JsApiReporter.prototype.suites = function() { - return this.suites_; -}; - -jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) { - var isSuite = suiteOrSpec instanceof jasmine.Suite; - var summary = { - id: suiteOrSpec.id, - name: suiteOrSpec.description, - type: isSuite ? 'suite' : 'spec', - children: [] - }; - - if (isSuite) { - var children = suiteOrSpec.children(); - for (var i = 0; i < children.length; i++) { - summary.children.push(this.summarize_(children[i])); - } - } - return summary; -}; - -jasmine.JsApiReporter.prototype.results = function() { - return this.results_; -}; - -jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) { - return this.results_[specId]; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) { - this.finished = true; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) { - this.results_[spec.id] = { - messages: spec.results().getItems(), - result: spec.results().failedCount > 0 ? "failed" : "passed" - }; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.log = function(str) { -}; - -jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){ - var results = {}; - for (var i = 0; i < specIds.length; i++) { - var specId = specIds[i]; - results[specId] = this.summarizeResult_(this.results_[specId]); - } - return results; -}; - -jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ - var summaryMessages = []; - var messagesLength = result.messages.length; - for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) { - var resultMessage = result.messages[messageIndex]; - summaryMessages.push({ - text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined, - passed: resultMessage.passed ? resultMessage.passed() : true, - type: resultMessage.type, - message: resultMessage.message, - trace: { - stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined - } - }); - } - - return { - result : result.result, - messages : summaryMessages - }; -}; - -/** - * @constructor - * @param {jasmine.Env} env - * @param actual - * @param {jasmine.Spec} spec - */ -jasmine.Matchers = function(env, actual, spec, opt_isNot) { - this.env = env; - this.actual = actual; - this.spec = spec; - this.isNot = opt_isNot || false; - this.reportWasCalled_ = false; -}; - -// todo: @deprecated as of Jasmine 0.11, remove soon [xw] -jasmine.Matchers.pp = function(str) { - throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!"); -}; - -// todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw] -jasmine.Matchers.prototype.report = function(result, failing_message, details) { - throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs"); -}; - -jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) { - for (var methodName in prototype) { - if (methodName == 'report') continue; - var orig = prototype[methodName]; - matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig); - } -}; - -jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { - return function() { - var matcherArgs = jasmine.util.argsToArray(arguments); - var result = matcherFunction.apply(this, arguments); - - if (this.isNot) { - result = !result; - } - - if (this.reportWasCalled_) return result; - - var message; - if (!result) { - if (this.message) { - message = this.message.apply(this, arguments); - if (jasmine.isArray_(message)) { - message = message[this.isNot ? 1 : 0]; - } - } else { - var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); - message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate; - if (matcherArgs.length > 0) { - for (var i = 0; i < matcherArgs.length; i++) { - if (i > 0) message += ","; - message += " " + jasmine.pp(matcherArgs[i]); - } - } - message += "."; - } - } - var expectationResult = new jasmine.ExpectationResult({ - matcherName: matcherName, - passed: result, - expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0], - actual: this.actual, - message: message - }); - this.spec.addMatcherResult(expectationResult); - return jasmine.undefined; - }; -}; - - - - -/** - * toBe: compares the actual to the expected using === - * @param expected - */ -jasmine.Matchers.prototype.toBe = function(expected) { - return this.actual === expected; -}; - -/** - * toNotBe: compares the actual to the expected using !== - * @param expected - * @deprecated as of 1.0. Use not.toBe() instead. - */ -jasmine.Matchers.prototype.toNotBe = function(expected) { - return this.actual !== expected; -}; - -/** - * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc. - * - * @param expected - */ -jasmine.Matchers.prototype.toEqual = function(expected) { - return this.env.equals_(this.actual, expected); -}; - -/** - * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual - * @param expected - * @deprecated as of 1.0. Use not.toEqual() instead. - */ -jasmine.Matchers.prototype.toNotEqual = function(expected) { - return !this.env.equals_(this.actual, expected); -}; - -/** - * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes - * a pattern or a String. - * - * @param expected - */ -jasmine.Matchers.prototype.toMatch = function(expected) { - return new RegExp(expected).test(this.actual); -}; - -/** - * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch - * @param expected - * @deprecated as of 1.0. Use not.toMatch() instead. - */ -jasmine.Matchers.prototype.toNotMatch = function(expected) { - return !(new RegExp(expected).test(this.actual)); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeDefined = function() { - return (this.actual !== jasmine.undefined); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeUndefined = function() { - return (this.actual === jasmine.undefined); -}; - -/** - * Matcher that compares the actual to null. - */ -jasmine.Matchers.prototype.toBeNull = function() { - return (this.actual === null); -}; - -/** - * Matcher that compares the actual to NaN. - */ -jasmine.Matchers.prototype.toBeNaN = function() { - this.message = function() { - return [ "Expected " + jasmine.pp(this.actual) + " to be NaN." ]; - }; - - return (this.actual !== this.actual); -}; - -/** - * Matcher that boolean not-nots the actual. - */ -jasmine.Matchers.prototype.toBeTruthy = function() { - return !!this.actual; -}; - - -/** - * Matcher that boolean nots the actual. - */ -jasmine.Matchers.prototype.toBeFalsy = function() { - return !this.actual; -}; - - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called. - */ -jasmine.Matchers.prototype.toHaveBeenCalled = function() { - if (arguments.length > 0) { - throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to have been called.", - "Expected spy " + this.actual.identity + " not to have been called." - ]; - }; - - return this.actual.wasCalled; -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalled() instead */ -jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was not called. - * - * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead - */ -jasmine.Matchers.prototype.wasNotCalled = function() { - if (arguments.length > 0) { - throw new Error('wasNotCalled does not take arguments'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to not have been called.", - "Expected spy " + this.actual.identity + " to have been called." - ]; - }; - - return !this.actual.wasCalled; -}; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters. - * - * @example - * - */ -jasmine.Matchers.prototype.toHaveBeenCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - this.message = function() { - var invertedMessage = "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was."; - var positiveMessage = ""; - if (this.actual.callCount === 0) { - positiveMessage = "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called."; - } else { - positiveMessage = "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but actual calls were " + jasmine.pp(this.actual.argsForCall).replace(/^\[ | \]$/g, '') - } - return [positiveMessage, invertedMessage]; - }; - - return this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith; - -/** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasNotCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was", - "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was" - ]; - }; - - return !this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** - * Matcher that checks that the expected item is an element in the actual Array. - * - * @param {Object} expected - */ -jasmine.Matchers.prototype.toContain = function(expected) { - return this.env.contains_(this.actual, expected); -}; - -/** - * Matcher that checks that the expected item is NOT an element in the actual Array. - * - * @param {Object} expected - * @deprecated as of 1.0. Use not.toContain() instead. - */ -jasmine.Matchers.prototype.toNotContain = function(expected) { - return !this.env.contains_(this.actual, expected); -}; - -jasmine.Matchers.prototype.toBeLessThan = function(expected) { - return this.actual < expected; -}; - -jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { - return this.actual > expected; -}; - -/** - * Matcher that checks that the expected item is equal to the actual item - * up to a given level of decimal precision (default 2). - * - * @param {Number} expected - * @param {Number} precision, as number of decimal places - */ -jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) { - if (!(precision === 0)) { - precision = precision || 2; - } - return Math.abs(expected - this.actual) < (Math.pow(10, -precision) / 2); -}; - -/** - * Matcher that checks that the expected exception was thrown by the actual. - * - * @param {String} [expected] - */ -jasmine.Matchers.prototype.toThrow = function(expected) { - var result = false; - var exception; - if (typeof this.actual != 'function') { - throw new Error('Actual is not a function'); - } - try { - this.actual(); - } catch (e) { - exception = e; - } - if (exception) { - result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); - } - - var not = this.isNot ? "not " : ""; - - this.message = function() { - if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) { - return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' '); - } else { - return "Expected function to throw an exception."; - } - }; - - return result; -}; - -jasmine.Matchers.Any = function(expectedClass) { - this.expectedClass = expectedClass; -}; - -jasmine.Matchers.Any.prototype.jasmineMatches = function(other) { - if (this.expectedClass == String) { - return typeof other == 'string' || other instanceof String; - } - - if (this.expectedClass == Number) { - return typeof other == 'number' || other instanceof Number; - } - - if (this.expectedClass == Function) { - return typeof other == 'function' || other instanceof Function; - } - - if (this.expectedClass == Object) { - return typeof other == 'object'; - } - - return other instanceof this.expectedClass; -}; - -jasmine.Matchers.Any.prototype.jasmineToString = function() { - return ''; -}; - -jasmine.Matchers.ObjectContaining = function (sample) { - this.sample = sample; -}; - -jasmine.Matchers.ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) { - mismatchKeys = mismatchKeys || []; - mismatchValues = mismatchValues || []; - - var env = jasmine.getEnv(); - - var hasKey = function(obj, keyName) { - return obj != null && obj[keyName] !== jasmine.undefined; - }; - - for (var property in this.sample) { - if (!hasKey(other, property) && hasKey(this.sample, property)) { - mismatchKeys.push("expected has key '" + property + "', but missing from actual."); - } - else if (!env.equals_(this.sample[property], other[property], mismatchKeys, mismatchValues)) { - mismatchValues.push("'" + property + "' was '" + (other[property] ? jasmine.util.htmlEscape(other[property].toString()) : other[property]) + "' in expected, but was '" + (this.sample[property] ? jasmine.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in actual."); - } - } - - return (mismatchKeys.length === 0 && mismatchValues.length === 0); -}; - -jasmine.Matchers.ObjectContaining.prototype.jasmineToString = function () { - return ""; -}; -// Mock setTimeout, clearTimeout -// Contributed by Pivotal Computer Systems, www.pivotalsf.com - -jasmine.FakeTimer = function() { - this.reset(); - - var self = this; - self.setTimeout = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false); - return self.timeoutsMade; - }; - - self.setInterval = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true); - return self.timeoutsMade; - }; - - self.clearTimeout = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - - self.clearInterval = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - -}; - -jasmine.FakeTimer.prototype.reset = function() { - this.timeoutsMade = 0; - this.scheduledFunctions = {}; - this.nowMillis = 0; -}; - -jasmine.FakeTimer.prototype.tick = function(millis) { - var oldMillis = this.nowMillis; - var newMillis = oldMillis + millis; - this.runFunctionsWithinRange(oldMillis, newMillis); - this.nowMillis = newMillis; -}; - -jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) { - var scheduledFunc; - var funcsToRun = []; - for (var timeoutKey in this.scheduledFunctions) { - scheduledFunc = this.scheduledFunctions[timeoutKey]; - if (scheduledFunc != jasmine.undefined && - scheduledFunc.runAtMillis >= oldMillis && - scheduledFunc.runAtMillis <= nowMillis) { - funcsToRun.push(scheduledFunc); - this.scheduledFunctions[timeoutKey] = jasmine.undefined; - } - } - - if (funcsToRun.length > 0) { - funcsToRun.sort(function(a, b) { - return a.runAtMillis - b.runAtMillis; - }); - for (var i = 0; i < funcsToRun.length; ++i) { - try { - var funcToRun = funcsToRun[i]; - this.nowMillis = funcToRun.runAtMillis; - funcToRun.funcToCall(); - if (funcToRun.recurring) { - this.scheduleFunction(funcToRun.timeoutKey, - funcToRun.funcToCall, - funcToRun.millis, - true); - } - } catch(e) { - } - } - this.runFunctionsWithinRange(oldMillis, nowMillis); - } -}; - -jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) { - this.scheduledFunctions[timeoutKey] = { - runAtMillis: this.nowMillis + millis, - funcToCall: funcToCall, - recurring: recurring, - timeoutKey: timeoutKey, - millis: millis - }; -}; - -/** - * @namespace - */ -jasmine.Clock = { - defaultFakeTimer: new jasmine.FakeTimer(), - - reset: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.reset(); - }, - - tick: function(millis) { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.tick(millis); - }, - - runFunctionsWithinRange: function(oldMillis, nowMillis) { - jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis); - }, - - scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) { - jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring); - }, - - useMock: function() { - if (!jasmine.Clock.isInstalled()) { - var spec = jasmine.getEnv().currentSpec; - spec.after(jasmine.Clock.uninstallMock); - - jasmine.Clock.installMock(); - } - }, - - installMock: function() { - jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer; - }, - - uninstallMock: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.installed = jasmine.Clock.real; - }, - - real: { - setTimeout: jasmine.getGlobal().setTimeout, - clearTimeout: jasmine.getGlobal().clearTimeout, - setInterval: jasmine.getGlobal().setInterval, - clearInterval: jasmine.getGlobal().clearInterval - }, - - assertInstalled: function() { - if (!jasmine.Clock.isInstalled()) { - throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()"); - } - }, - - isInstalled: function() { - return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer; - }, - - installed: null -}; -jasmine.Clock.installed = jasmine.Clock.real; - -//else for IE support -jasmine.getGlobal().setTimeout = function(funcToCall, millis) { - if (jasmine.Clock.installed.setTimeout.apply) { - return jasmine.Clock.installed.setTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.setTimeout(funcToCall, millis); - } -}; - -jasmine.getGlobal().setInterval = function(funcToCall, millis) { - if (jasmine.Clock.installed.setInterval.apply) { - return jasmine.Clock.installed.setInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.setInterval(funcToCall, millis); - } -}; - -jasmine.getGlobal().clearTimeout = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearTimeout(timeoutKey); - } -}; - -jasmine.getGlobal().clearInterval = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearInterval(timeoutKey); - } -}; - -/** - * @constructor - */ -jasmine.MultiReporter = function() { - this.subReporters_ = []; -}; -jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter); - -jasmine.MultiReporter.prototype.addReporter = function(reporter) { - this.subReporters_.push(reporter); -}; - -(function() { - var functionNames = [ - "reportRunnerStarting", - "reportRunnerResults", - "reportSuiteResults", - "reportSpecStarting", - "reportSpecResults", - "log" - ]; - for (var i = 0; i < functionNames.length; i++) { - var functionName = functionNames[i]; - jasmine.MultiReporter.prototype[functionName] = (function(functionName) { - return function() { - for (var j = 0; j < this.subReporters_.length; j++) { - var subReporter = this.subReporters_[j]; - if (subReporter[functionName]) { - subReporter[functionName].apply(subReporter, arguments); - } - } - }; - })(functionName); - } -})(); -/** - * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults - * - * @constructor - */ -jasmine.NestedResults = function() { - /** - * The total count of results - */ - this.totalCount = 0; - /** - * Number of passed results - */ - this.passedCount = 0; - /** - * Number of failed results - */ - this.failedCount = 0; - /** - * Was this suite/spec skipped? - */ - this.skipped = false; - /** - * @ignore - */ - this.items_ = []; -}; - -/** - * Roll up the result counts. - * - * @param result - */ -jasmine.NestedResults.prototype.rollupCounts = function(result) { - this.totalCount += result.totalCount; - this.passedCount += result.passedCount; - this.failedCount += result.failedCount; -}; - -/** - * Adds a log message. - * @param values Array of message parts which will be concatenated later. - */ -jasmine.NestedResults.prototype.log = function(values) { - this.items_.push(new jasmine.MessageResult(values)); -}; - -/** - * Getter for the results: message & results. - */ -jasmine.NestedResults.prototype.getItems = function() { - return this.items_; -}; - -/** - * Adds a result, tracking counts (total, passed, & failed) - * @param {jasmine.ExpectationResult|jasmine.NestedResults} result - */ -jasmine.NestedResults.prototype.addResult = function(result) { - if (result.type != 'log') { - if (result.items_) { - this.rollupCounts(result); - } else { - this.totalCount++; - if (result.passed()) { - this.passedCount++; - } else { - this.failedCount++; - } - } - } - this.items_.push(result); -}; - -/** - * @returns {Boolean} True if everything below passed - */ -jasmine.NestedResults.prototype.passed = function() { - return this.passedCount === this.totalCount; -}; -/** - * Base class for pretty printing for expectation results. - */ -jasmine.PrettyPrinter = function() { - this.ppNestLevel_ = 0; -}; - -/** - * Formats a value in a nice, human-readable string. - * - * @param value - */ -jasmine.PrettyPrinter.prototype.format = function(value) { - this.ppNestLevel_++; - try { - if (value === jasmine.undefined) { - this.emitScalar('undefined'); - } else if (value === null) { - this.emitScalar('null'); - } else if (value === jasmine.getGlobal()) { - this.emitScalar(''); - } else if (value.jasmineToString) { - this.emitScalar(value.jasmineToString()); - } else if (typeof value === 'string') { - this.emitString(value); - } else if (jasmine.isSpy(value)) { - this.emitScalar("spy on " + value.identity); - } else if (value instanceof RegExp) { - this.emitScalar(value.toString()); - } else if (typeof value === 'function') { - this.emitScalar('Function'); - } else if (typeof value.nodeType === 'number') { - this.emitScalar('HTMLNode'); - } else if (value instanceof Date) { - this.emitScalar('Date(' + value + ')'); - } else if (value.__Jasmine_been_here_before__) { - this.emitScalar(''); - } else if (jasmine.isArray_(value) || typeof value == 'object') { - value.__Jasmine_been_here_before__ = true; - if (jasmine.isArray_(value)) { - this.emitArray(value); - } else { - this.emitObject(value); - } - delete value.__Jasmine_been_here_before__; - } else { - this.emitScalar(value.toString()); - } - } finally { - this.ppNestLevel_--; - } -}; - -jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) { - for (var property in obj) { - if (!obj.hasOwnProperty(property)) continue; - if (property == '__Jasmine_been_here_before__') continue; - fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined && - obj.__lookupGetter__(property) !== null) : false); - } -}; - -jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_; - -jasmine.StringPrettyPrinter = function() { - jasmine.PrettyPrinter.call(this); - - this.string = ''; -}; -jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter); - -jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) { - this.append(value); -}; - -jasmine.StringPrettyPrinter.prototype.emitString = function(value) { - this.append("'" + value + "'"); -}; - -jasmine.StringPrettyPrinter.prototype.emitArray = function(array) { - if (this.ppNestLevel_ > jasmine.MAX_PRETTY_PRINT_DEPTH) { - this.append("Array"); - return; - } - - this.append('[ '); - for (var i = 0; i < array.length; i++) { - if (i > 0) { - this.append(', '); - } - this.format(array[i]); - } - this.append(' ]'); -}; - -jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) { - if (this.ppNestLevel_ > jasmine.MAX_PRETTY_PRINT_DEPTH) { - this.append("Object"); - return; - } - - var self = this; - this.append('{ '); - var first = true; - - this.iterateObject(obj, function(property, isGetter) { - if (first) { - first = false; - } else { - self.append(', '); - } - - self.append(property); - self.append(' : '); - if (isGetter) { - self.append(''); - } else { - self.format(obj[property]); - } - }); - - this.append(' }'); -}; - -jasmine.StringPrettyPrinter.prototype.append = function(value) { - this.string += value; -}; -jasmine.Queue = function(env) { - this.env = env; - - // parallel to blocks. each true value in this array means the block will - // get executed even if we abort - this.ensured = []; - this.blocks = []; - this.running = false; - this.index = 0; - this.offset = 0; - this.abort = false; -}; - -jasmine.Queue.prototype.addBefore = function(block, ensure) { - if (ensure === jasmine.undefined) { - ensure = false; - } - - this.blocks.unshift(block); - this.ensured.unshift(ensure); -}; - -jasmine.Queue.prototype.add = function(block, ensure) { - if (ensure === jasmine.undefined) { - ensure = false; - } - - this.blocks.push(block); - this.ensured.push(ensure); -}; - -jasmine.Queue.prototype.insertNext = function(block, ensure) { - if (ensure === jasmine.undefined) { - ensure = false; - } - - this.ensured.splice((this.index + this.offset + 1), 0, ensure); - this.blocks.splice((this.index + this.offset + 1), 0, block); - this.offset++; -}; - -jasmine.Queue.prototype.start = function(onComplete) { - this.running = true; - this.onComplete = onComplete; - this.next_(); -}; - -jasmine.Queue.prototype.isRunning = function() { - return this.running; -}; - -jasmine.Queue.LOOP_DONT_RECURSE = true; - -jasmine.Queue.prototype.next_ = function() { - var self = this; - var goAgain = true; - - while (goAgain) { - goAgain = false; - - if (self.index < self.blocks.length && !(this.abort && !this.ensured[self.index])) { - var calledSynchronously = true; - var completedSynchronously = false; - - var onComplete = function () { - if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) { - completedSynchronously = true; - return; - } - - if (self.blocks[self.index].abort) { - self.abort = true; - } - - self.offset = 0; - self.index++; - - var now = new Date().getTime(); - if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) { - self.env.lastUpdate = now; - self.env.setTimeout(function() { - self.next_(); - }, 0); - } else { - if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) { - goAgain = true; - } else { - self.next_(); - } - } - }; - self.blocks[self.index].execute(onComplete); - - calledSynchronously = false; - if (completedSynchronously) { - onComplete(); - } - - } else { - self.running = false; - if (self.onComplete) { - self.onComplete(); - } - } - } -}; - -jasmine.Queue.prototype.results = function() { - var results = new jasmine.NestedResults(); - for (var i = 0; i < this.blocks.length; i++) { - if (this.blocks[i].results) { - results.addResult(this.blocks[i].results()); - } - } - return results; -}; - - -/** - * Runner - * - * @constructor - * @param {jasmine.Env} env - */ -jasmine.Runner = function(env) { - var self = this; - self.env = env; - self.queue = new jasmine.Queue(env); - self.before_ = []; - self.after_ = []; - self.suites_ = []; -}; - -jasmine.Runner.prototype.execute = function() { - var self = this; - if (self.env.reporter.reportRunnerStarting) { - self.env.reporter.reportRunnerStarting(this); - } - self.queue.start(function () { - self.finishCallback(); - }); -}; - -jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.splice(0,0,beforeEachFunction); -}; - -jasmine.Runner.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.splice(0,0,afterEachFunction); -}; - - -jasmine.Runner.prototype.finishCallback = function() { - this.env.reporter.reportRunnerResults(this); -}; - -jasmine.Runner.prototype.addSuite = function(suite) { - this.suites_.push(suite); -}; - -jasmine.Runner.prototype.add = function(block) { - if (block instanceof jasmine.Suite) { - this.addSuite(block); - } - this.queue.add(block); -}; - -jasmine.Runner.prototype.specs = function () { - var suites = this.suites(); - var specs = []; - for (var i = 0; i < suites.length; i++) { - specs = specs.concat(suites[i].specs()); - } - return specs; -}; - -jasmine.Runner.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Runner.prototype.topLevelSuites = function() { - var topLevelSuites = []; - for (var i = 0; i < this.suites_.length; i++) { - if (!this.suites_[i].parentSuite) { - topLevelSuites.push(this.suites_[i]); - } - } - return topLevelSuites; -}; - -jasmine.Runner.prototype.results = function() { - return this.queue.results(); -}; -/** - * Internal representation of a Jasmine specification, or test. - * - * @constructor - * @param {jasmine.Env} env - * @param {jasmine.Suite} suite - * @param {String} description - */ -jasmine.Spec = function(env, suite, description) { - if (!env) { - throw new Error('jasmine.Env() required'); - } - if (!suite) { - throw new Error('jasmine.Suite() required'); - } - var spec = this; - spec.id = env.nextSpecId ? env.nextSpecId() : null; - spec.env = env; - spec.suite = suite; - spec.description = description; - spec.queue = new jasmine.Queue(env); - - spec.afterCallbacks = []; - spec.spies_ = []; - - spec.results_ = new jasmine.NestedResults(); - spec.results_.description = description; - spec.matchersClass = null; -}; - -jasmine.Spec.prototype.getFullName = function() { - return this.suite.getFullName() + ' ' + this.description + '.'; -}; - - -jasmine.Spec.prototype.results = function() { - return this.results_; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.Spec.prototype.log = function() { - return this.results_.log(arguments); -}; - -jasmine.Spec.prototype.runs = function (func) { - var block = new jasmine.Block(this.env, func, this); - this.addToQueue(block); - return this; -}; - -jasmine.Spec.prototype.addToQueue = function (block) { - if (this.queue.isRunning()) { - this.queue.insertNext(block); - } else { - this.queue.add(block); - } -}; - -/** - * @param {jasmine.ExpectationResult} result - */ -jasmine.Spec.prototype.addMatcherResult = function(result) { - this.results_.addResult(result); -}; - -jasmine.Spec.prototype.expect = function(actual) { - var positive = new (this.getMatchersClass_())(this.env, actual, this); - positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); - return positive; -}; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -jasmine.Spec.prototype.waits = function(timeout) { - var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this); - this.addToQueue(waitsFunc); - return this; -}; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - var latchFunction_ = null; - var optional_timeoutMessage_ = null; - var optional_timeout_ = null; - - for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i]; - switch (typeof arg) { - case 'function': - latchFunction_ = arg; - break; - case 'string': - optional_timeoutMessage_ = arg; - break; - case 'number': - optional_timeout_ = arg; - break; - } - } - - var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this); - this.addToQueue(waitsForFunc); - return this; -}; - -jasmine.Spec.prototype.fail = function (e) { - var expectationResult = new jasmine.ExpectationResult({ - passed: false, - message: e ? jasmine.util.formatException(e) : 'Exception', - trace: { stack: e.stack } - }); - this.results_.addResult(expectationResult); -}; - -jasmine.Spec.prototype.getMatchersClass_ = function() { - return this.matchersClass || this.env.matchersClass; -}; - -jasmine.Spec.prototype.addMatchers = function(matchersPrototype) { - var parent = this.getMatchersClass_(); - var newMatchersClass = function() { - parent.apply(this, arguments); - }; - jasmine.util.inherit(newMatchersClass, parent); - jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass); - this.matchersClass = newMatchersClass; -}; - -jasmine.Spec.prototype.finishCallback = function() { - this.env.reporter.reportSpecResults(this); -}; - -jasmine.Spec.prototype.finish = function(onComplete) { - this.removeAllSpies(); - this.finishCallback(); - if (onComplete) { - onComplete(); - } -}; - -jasmine.Spec.prototype.after = function(doAfter) { - if (this.queue.isRunning()) { - this.queue.add(new jasmine.Block(this.env, doAfter, this), true); - } else { - this.afterCallbacks.unshift(doAfter); - } -}; - -jasmine.Spec.prototype.execute = function(onComplete) { - var spec = this; - if (!spec.env.specFilter(spec)) { - spec.results_.skipped = true; - spec.finish(onComplete); - return; - } - - this.env.reporter.reportSpecStarting(this); - - spec.env.currentSpec = spec; - - spec.addBeforesAndAftersToQueue(); - - spec.queue.start(function () { - spec.finish(onComplete); - }); -}; - -jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() { - var runner = this.env.currentRunner(); - var i; - - for (var suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)); - } - } - for (i = 0; i < runner.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)); - } - for (i = 0; i < this.afterCallbacks.length; i++) { - this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this), true); - } - for (suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, suite.after_[i], this), true); - } - } - for (i = 0; i < runner.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, runner.after_[i], this), true); - } -}; - -jasmine.Spec.prototype.explodes = function() { - throw 'explodes function should not have been called'; -}; - -jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) { - if (obj == jasmine.undefined) { - throw "spyOn could not find an object to spy upon for " + methodName + "()"; - } - - if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) { - throw methodName + '() method does not exist'; - } - - if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) { - throw new Error(methodName + ' has already been spied upon'); - } - - var spyObj = jasmine.createSpy(methodName); - - this.spies_.push(spyObj); - spyObj.baseObj = obj; - spyObj.methodName = methodName; - spyObj.originalValue = obj[methodName]; - - obj[methodName] = spyObj; - - return spyObj; -}; - -jasmine.Spec.prototype.removeAllSpies = function() { - for (var i = 0; i < this.spies_.length; i++) { - var spy = this.spies_[i]; - spy.baseObj[spy.methodName] = spy.originalValue; - } - this.spies_ = []; -}; - -/** - * Internal representation of a Jasmine suite. - * - * @constructor - * @param {jasmine.Env} env - * @param {String} description - * @param {Function} specDefinitions - * @param {jasmine.Suite} parentSuite - */ -jasmine.Suite = function(env, description, specDefinitions, parentSuite) { - var self = this; - self.id = env.nextSuiteId ? env.nextSuiteId() : null; - self.description = description; - self.queue = new jasmine.Queue(env); - self.parentSuite = parentSuite; - self.env = env; - self.before_ = []; - self.after_ = []; - self.children_ = []; - self.suites_ = []; - self.specs_ = []; -}; - -jasmine.Suite.prototype.getFullName = function() { - var fullName = this.description; - for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { - fullName = parentSuite.description + ' ' + fullName; - } - return fullName; -}; - -jasmine.Suite.prototype.finish = function(onComplete) { - this.env.reporter.reportSuiteResults(this); - this.finished = true; - if (typeof(onComplete) == 'function') { - onComplete(); - } -}; - -jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.unshift(beforeEachFunction); -}; - -jasmine.Suite.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.unshift(afterEachFunction); -}; - -jasmine.Suite.prototype.results = function() { - return this.queue.results(); -}; - -jasmine.Suite.prototype.add = function(suiteOrSpec) { - this.children_.push(suiteOrSpec); - if (suiteOrSpec instanceof jasmine.Suite) { - this.suites_.push(suiteOrSpec); - this.env.currentRunner().addSuite(suiteOrSpec); - } else { - this.specs_.push(suiteOrSpec); - } - this.queue.add(suiteOrSpec); -}; - -jasmine.Suite.prototype.specs = function() { - return this.specs_; -}; - -jasmine.Suite.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Suite.prototype.children = function() { - return this.children_; -}; - -jasmine.Suite.prototype.execute = function(onComplete) { - var self = this; - this.queue.start(function () { - self.finish(onComplete); - }); -}; -jasmine.WaitsBlock = function(env, timeout, spec) { - this.timeout = timeout; - jasmine.Block.call(this, env, null, spec); -}; - -jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block); - -jasmine.WaitsBlock.prototype.execute = function (onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...'); - } - this.env.setTimeout(function () { - onComplete(); - }, this.timeout); -}; -/** - * A block which waits for some condition to become true, with timeout. - * - * @constructor - * @extends jasmine.Block - * @param {jasmine.Env} env The Jasmine environment. - * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true. - * @param {Function} latchFunction A function which returns true when the desired condition has been met. - * @param {String} message The message to display if the desired condition hasn't been met within the given time period. - * @param {jasmine.Spec} spec The Jasmine spec. - */ -jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) { - this.timeout = timeout || env.defaultTimeoutInterval; - this.latchFunction = latchFunction; - this.message = message; - this.totalTimeSpentWaitingForLatch = 0; - jasmine.Block.call(this, env, null, spec); -}; -jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block); - -jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10; - -jasmine.WaitsForBlock.prototype.execute = function(onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')); - } - var latchFunctionResult; - try { - latchFunctionResult = this.latchFunction.apply(this.spec); - } catch (e) { - this.spec.fail(e); - onComplete(); - return; - } - - if (latchFunctionResult) { - onComplete(); - } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) { - var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen'); - this.spec.fail({ - name: 'timeout', - message: message - }); - - this.abort = true; - onComplete(); - } else { - this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT; - var self = this; - this.env.setTimeout(function() { - self.execute(onComplete); - }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT); - } -}; - -jasmine.version_= { - "major": 1, - "minor": 3, - "build": 1, - "revision": 1354556913 -}; diff --git a/test/jasmine/lib/jasmine-jsreporter.js b/test/jasmine/lib/jasmine-jsreporter.js deleted file mode 100644 index 3d43b2b..0000000 --- a/test/jasmine/lib/jasmine-jsreporter.js +++ /dev/null @@ -1,161 +0,0 @@ -/* - This file is part of the Jasmine JSReporter project from Ivan De Marino. - - Copyright (C) 2011 Ivan De Marino (aka detro, aka detronizator), http://blog.ivandemarino.me, ivan.de.marino@gmail.com - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL IVAN DE MARINO BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -(function () { - // Ensure that Jasmine library is loaded first - if (!jasmine) { - throw new Exception("[Jasmine JSReporter] 'Jasmine' library not found"); - } - - /** - * Calculate elapsed time, in Seconds. - * @param startMs Start time in Milliseconds - * @param finishMs Finish time in Milliseconds - * @return Elapsed time in Seconds */ - function elapsedSec (startMs, finishMs) { - return (finishMs - startMs) / 1000; - } - - /** - * Round an amount to the given number of Digits. - * If no number of digits is given, than '2' is assumed. - * @param amount Amount to round - * @param numOfDecDigits Number of Digits to round to. Default value is '2'. - * @return Rounded amount */ - function round (amount, numOfDecDigits) { - numOfDecDigits = numOfDecDigits || 2; - return Math.round(amount * Math.pow(10, numOfDecDigits)) / Math.pow(10, numOfDecDigits); - } - - /** - * Collect information about a Suite, recursively, and return a JSON result. - * @param suite The Jasmine Suite to get data from - */ - function getSuiteData (suite) { - var suiteData = { - description : suite.description, - durationSec : 0, - specs: [], - suites: [], - passed: true - }, - specs = suite.specs(), - suites = suite.suites(), - i, ilen; - - // Loop over all the Suite's Specs - for (i = 0, ilen = specs.length; i < ilen; ++i) { - suiteData.specs[i] = { - description : specs[i].description, - durationSec : specs[i].durationSec, - passed : specs[i].results().passedCount === specs[i].results().totalCount, - skipped : specs[i].results().skipped, - passedCount : specs[i].results().passedCount, - failedCount : specs[i].results().failedCount, - totalCount : specs[i].results().totalCount - }; - suiteData.passed = !suiteData.specs[i].passed ? false : suiteData.passed; - suiteData.durationSec += suiteData.specs[i].durationSec; - } - - // Loop over all the Suite's sub-Suites - for (i = 0, ilen = suites.length; i < ilen; ++i) { - suiteData.suites[i] = getSuiteData(suites[i]); //< recursive population - suiteData.passed = !suiteData.suites[i].passed ? false : suiteData.passed; - suiteData.durationSec += suiteData.suites[i].durationSec; - } - - // Rounding duration numbers to 3 decimal digits - suiteData.durationSec = round(suiteData.durationSec, 4); - - return suiteData; - } - - var JSReporter = function () { - }; - - JSReporter.prototype = { - reportRunnerStarting: function (runner) { - // Nothing to do - }, - - reportSpecStarting: function (spec) { - // Start timing this spec - spec.startedAt = new Date(); - }, - - reportSpecResults: function (spec) { - // Finish timing this spec and calculate duration/delta (in sec) - spec.finishedAt = new Date(); - spec.durationSec = elapsedSec(spec.startedAt.getTime(), spec.finishedAt.getTime()); - }, - - reportSuiteResults: function (suite) { - // Nothing to do - }, - - reportRunnerResults: function (runner) { - var suites = runner.suites(), - i, ilen; - - // Attach results to the "jasmine" object to make those results easy to scrap/find - jasmine.runnerResults = { - suites: [], - durationSec : 0, - passed : true - }; - - // Loop over all the Suites - for (i = 0, ilen = suites.length; i < ilen; ++i) { - if (suites[i].parentSuite === null) { - jasmine.runnerResults.suites[i] = getSuiteData(suites[i]); - // If 1 suite fails, the whole runner fails - jasmine.runnerResults.passed = !jasmine.runnerResults.suites[i].passed ? false : jasmine.runnerResults.passed; - // Add up all the durations - jasmine.runnerResults.durationSec += jasmine.runnerResults.suites[i].durationSec; - } - } - - // Decorate the 'jasmine' object with getters - jasmine.getJSReport = function () { - if (jasmine.runnerResults) { - return jasmine.runnerResults; - } - return null; - }; - jasmine.getJSReportAsString = function () { - return JSON.stringify(jasmine.getJSReport()); - }; - } - }; - - // export public - jasmine.JSReporter = JSReporter; -})(); - diff --git a/test/runner.js b/test/runner.js deleted file mode 100755 index fe6ac3a..0000000 --- a/test/runner.js +++ /dev/null @@ -1,205 +0,0 @@ -var browsers = [ - { - 'os' : 'Windows', - 'os_version' : '7', - 'resolution' : '1024x768', - 'browser' : 'Firefox', - 'browser_version': '14' - }, - { - 'os' : 'Windows', - 'os_version' : '7', - 'resolution' : '1024x768', - 'browser' : 'Firefox', - 'browser_version': '26' - }, - { - 'os' : 'Windows', - 'os_version' : '7', - 'resolution' : '1024x768', - 'browser' : 'Chrome', - 'browser_version': '19' - }, - { - 'os' : 'Windows', - 'os_version' : '7', - 'resolution' : '1024x768', - 'browser' : 'Chrome', - 'browser_version': '31' - }, - { - 'os' : 'Windows', - 'os_version' : '7', - 'resolution' : '1024x768', - 'browser' : 'IE', - 'browser_version': '9' - }, - { - 'os' : 'Windows', - 'os_version' : '8.1', - 'resolution' : '1024x768', - 'browser' : 'IE', - 'browser_version': '11' - }, - { - 'os' : 'OS X', - 'os_version' : 'Lion', - 'resolution' : '1024x768', - 'browser' : 'Safari', - 'browser_version' : '6.0' - }, - { - 'os' : 'OS X', - 'os_version' : 'Mavericks', - 'resolution' : '1024x768', - 'browser' : 'Safari', - 'browser_version' : '7.0' - }, - /* - { // fails 37 specs, DOMComponentsLoaded does not fire - 'browserName' : 'iPhone', - 'platform' : 'MAC', - 'device' : 'iPhone 4S' - }, - { // fails - 'browserName' : 'iPad', - 'platform' : 'MAC', - 'device' : 'iPad 2 (5.0)' - }, - { - // android 4.0, fails - //x-tag using testbox should allow a custom prototype to be used. - //x-tag using testbox should be able to extend existing elements. - - 'browserName' : 'android', - 'platform' : 'ANDROID', - 'device' : 'Samsung Galaxy Nexus' - }, - { // android 4.1 fails - 'browserName' : 'android', - 'platform' : 'ANDROID', - 'device' : 'Samsung Galaxy S III' - }, - { // android 4.2 , fails - 'browserName' : 'android', - 'platform' : 'ANDROID', - 'device' : 'LG Nexus 4' - }*/ -]; - - -var extend = require('util')._extend, - async = require('async'), - webdriver = require('browserstack-webdriver'), - By = webdriver.By, - spawn = require('child_process').spawn, - connect = spawn('grunt',['connect:test']), - java = null; - -connect.stdout.setEncoding('utf8'); -connect.stderr.setEncoding('utf8'); -connect.stdout.on('data', function(d){ - console.log('connect:', d); -}); -connect.stderr.on('data', function (data) { - console.log('connect-err:' + data); -}); - - -setTimeout(function(){ - java = spawn('java',['-jar', - process.cwd() +'/test/tools/BrowserStackTunnel.jar', - process.env.DEV_KEY, 'localhost,9000,0']); - - java.stdout.setEncoding('utf8'); - java.stdout.on('data', function(d){ - d = d.replace(process.env.DEV_KEY,'[secret]'); - console.log('java:', d); - if (~d.indexOf('http://localhost:9000')) { - console.log('starting webdriver'); -try { - runWebDriver(function(err){ - console.log('completed... shutting down'); - connect.kill(); - java.kill(); - process.exit((err||'').length); - }); -} catch(e) { - console.log(e); - connect.kill(); - java.kill(); - process.exit(99); -} - - } - }); - java.stderr.on('data', function (data) { - console.log('java-err:' + data); - }); - -}, 3000); - - - - - -function runWebDriver(callback){ - async.eachLimit(browsers, 1, function(browser, cb){ - var webdriverConfig = extend({},browser); - webdriverConfig['browserstack.tunnel'] = 'true'; - webdriverConfig['browserstack.user'] = process.env.DEV_ID; - webdriverConfig['browserstack.key'] = process.env.DEV_KEY; - - var driver = new webdriver.Builder(). - usingServer('http://hub.browserstack.com/wd/hub'). - withCapabilities(webdriverConfig). - build(); - - var nodeNotFound = function(err){ - console.log(JSON.stringify(browser),'->', err); - driver.quit(); - cb(); - } - - driver.get('http://localhost:9000/test/index.html'); - - driver.getTitle().then(function(title) { - //console.log(JSON.stringify(browser), '--', title); - setTimeout(function(){ - driver.isElementPresent(By.className('passingAlert')).then(function(passed){ - if (passed){ - driver.findElement(By.className('passingAlert')).then(function(node){ - node.getText().then(function(txt){ - console.log(JSON.stringify(browser),'--',txt); - driver.quit(); - cb(); - }); - }, nodeNotFound); - } else { - driver.findElement(By.className('failingAlert')).then(function(node){ - node.getText().then(function(txt){ - console.log(JSON.stringify(browser),'--', txt); - driver.findElements(By.css('.specDetail.failed > a.description')).then(function(nodes){ - async.each(nodes, function(n, completed){ - n.getText().then(function(t){ - console.log(JSON.stringify(browser),'--', t); - completed(); - }); - }, function(){ - driver.quit(); - cb(txt); - }); - }); - }); - }, nodeNotFound); - } - }, nodeNotFound); - }, 10000); // wait for all tests to run - }); - }, callback); -} - -process.on('exit', function() { - connect.kill(); - if(java) java.kill(); -}); diff --git a/test/shadow.html b/test/shadow.html deleted file mode 100644 index 546dfab..0000000 --- a/test/shadow.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - X-Tag: Jasmine Spec Runner - - - - - - - - - - - - - - - - - - - - -
- - - - diff --git a/test/v2.html b/test/v2.html deleted file mode 100644 index 2635402..0000000 --- a/test/v2.html +++ /dev/null @@ -1,50 +0,0 @@ - - - - - X-Tag: Jasmine Spec Runner - - - - - - - - - - - diff --git a/tests/core/assets/bitcoin.png b/tests/core/assets/bitcoin.png new file mode 100644 index 0000000..7018c83 Binary files /dev/null and b/tests/core/assets/bitcoin.png differ diff --git a/tests/core/index.html b/tests/core/index.html new file mode 100644 index 0000000..270916b --- /dev/null +++ b/tests/core/index.html @@ -0,0 +1,44 @@ + + + + + X-Tag: Jasmine Spec Runner + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/core/spec.js b/tests/core/spec.js new file mode 100644 index 0000000..21974f9 --- /dev/null +++ b/tests/core/spec.js @@ -0,0 +1,509 @@ + +describe("X-Tag's setup should", function() { + + it("import its globals into the environment", function() { + expect(xtag).toBeDefined(); + expect(XTagElement).toBeDefined(); + }); + +}); + +describe("X-Tag extension API should", function() { + + it("load global extensions when included in component declarations via string reference", function() { + + count = 0; + xtag.extensions.foo = { + mixin: (base) => class extends base { + bar(){ + count++; + } + }, + onParse (){ + count++; + }, + onCompiled (){ + count++; + }, + onConstruct (){ + count++; + } + } + + var component = xtag.create(class extends XTagElement.extensions('foo') { + 'baz::foo'(){ count++; } + }); + + defineTestElement(component); + + var node = new component(); + node.bar(); + node.baz(); + + expect(count).toBe(6); + + delete xtag.extensions.foo; + }); + + it("load local extensions when included in component declarations directly", function() { + + count = 0; + var foo = { + name: 'foo', + mixin: (base) => class extends base { + bar(){ + count++; + } + }, + onParse (){ + count++; + }, + onCompiled (){ + count++; + }, + onConstruct (){ + count++; + } + } + + var baz = { + name: 'baz', + mixin: (base) => class extends base { + boo(){ + count++; + } + } + } + + var _comp = class extends XTagElement.extensions(foo, baz) { + 'zul::foo'(){ count++; } + } + + var component = xtag.create(_comp); + + defineTestElement(component); + + var node = new component(); + node.bar(); + node.zul(); + node.boo(); + + expect(count).toBe(7); + }); + +}); + +describe("X-Tag's attr extension should", function() { + + it("correctly parse keys and set descriptors", function() { + + var count = 0; + var component = xtag.create(class extends XTagElement { + set 'one::attr'(val){ count++; } + set 'two::attr'(val){ count++; } + get 'three::attr'(){ count++; } + }); + + defineTestElement(component); + + expect('one' in component.prototype).toBe(true); + expect('two' in component.prototype).toBe(true); + expect('three' in component.prototype).toBe(true); + + var node = new component(); + node.one = 'test'; + node.two = 'test'; + var three = node.three; + + expect(count).toBe(3); + + }); + + it("call all descriptor variants", function() { + + var count = 0; + var component = xtag.create(class extends XTagElement { + set 'one::attr'(val){ count++; } + set 'two::attr'(val){ count++; } + get 'three::attr'(){ count++; } + set 'four::attr'(val){ count++; } + get 'four::attr'(){ count++; } + set 'five::attr'(val){ count++; } + get 'five::attr'(){ count++; } + get 'six::attr'(){ + return Number(this.getAttribute('six')); + } + }); + + defineTestElement(component); + + var node = new component(); + node.one = 'test'; + node.two = 'test'; + node.three; + node.four = 'test'; + node.four; + node.five = 'test'; + node.five; + expect(node.three).toBe(null); + expect(node.four).toBe('test'); + expect(node.five).toBe('test'); + node.six = 6; + + expect(count).toBe(10); + expect(node.one).toBe('test'); + expect(node.getAttribute('one')).toBe('test'); + expect(node.two).toBe('test'); + expect(node.getAttribute('two')).toBe('test'); + expect(node.getAttribute('three')).toBe(null); + expect(node.getAttribute('four')).toBe('test'); + expect(node.getAttribute('five')).toBe('test'); + expect(node.six).toBe(6); + expect(node.getAttribute('six')).toBe('6'); + + }); + + it("correctly handles boolean attributes", function() { + + var count = 0; + var component = xtag.create(class extends XTagElement { + set 'one::attr(boolean)'(val){ count++; } + set 'two::attr(boolean)'(val){ + count++; + return 'bar'; + } + get 'three::attr(boolean)'(){ count++; } + }); + + defineTestElement(component); + + var node = new component(); + node.one = 'test'; + node.two = 'test'; + node.three = 'test'; + node.three; + + expect(count).toBe(3); + expect(node.hasAttribute('one')).toBe(true); + expect(node.getAttribute('one')).toBe(''); + expect(node.hasAttribute('two')).toBe(true); + expect(node.getAttribute('two')).toBe(''); + expect(node.hasAttribute('three')).toBe(true); + expect(node.getAttribute('three')).toBe(''); + + }); + +}); + +describe("X-Tag's event extension should", function() { + + it("attach all subevents", function(done) { + + var count = 0; + xtag.events.loaded = { + attach: ['load'], + onFilter (node, event, data, resolve) { + if (event.type == 'load') { + count++; + resolve(); + } + } + } + + xtag.pseudos.foo = { + onInvoke: function(){ + count++; + } + } + + var component = xtag.create(class extends XTagElement { + constructor(){ + super(); + var img = document.createElement('img'); + img.src = 'assets/bitcoin.png'; + this.appendChild(img); + } + 'loaded::event:foo'(){ + count++; + } + }); + + var inDOM = defineTestElement(component); + + var node = new component(); + + var outer, inner; + node.addEventListener('loaded', function(){ + outer = true; + if (inner) { + expect(count).toBe(6); + done(); + delete xtag.events.loaded; + } + }); + + inDOM.addEventListener('loaded', function(){ + inner = true; + if (outer) { + expect(count).toBe(6); + done(); + delete xtag.events.loaded; + } + }); + }); + + it("allow custom events to attache events of the same name", function(done) { + + var count = 0; + + xtag.events.click = { + attach: ['mousedown'] + }; + + var component = xtag.create(class extends XTagElement { + 'click::event'(e){ + count++; + if (count == 3) { + expect(count).toBe(3); + done(); + } + } + }); + + defineTestElement(component); + + var node = new component(); + + node.addEventListener('click', function(e){ + count++; + if (count == 3) { + expect(count).toBe(3); + done(); + } + }); + + xtag.addEvent(node, 'click', function(e){ + count++; + if (count == 3) { + expect(count).toBe(3); + done(); + } + }); + + node.click(); + }); + +}); + +describe("X-Tag's template extension should", function() { + + it("attach unnamed template properties as default", function() { + + var count = 0; + var component = xtag.create(class extends XTagElement { + '::template'(){ + return `

title1

content1

`; + } + }); + + defineTestElement(component); + + var node = new component(); + node.render(); + expect(node.firstElementChild.textContent).toBe('title1'); + expect(node.lastElementChild.textContent).toBe('content1'); + }); + + it("auto-render templates marked with the option", function(done) { + + var count = 7; + + var component1 = xtag.create(class extends XTagElement { + '::template(ready)'(){ + return `

title auto 1

content auto 1

`; + } + }); + + var component2 = xtag.create(class extends XTagElement { + 'foo::template(ready)'(){ + return `

title auto 2

content auto 2

`; + } + 'bar::template'(){ + return `

swap

swapped

`; + } + }); + + defineTestElement(component1); + + var node1 = new component1(); + node1.rxn('ready', function(){ + expect(node1.firstElementChild.textContent).toBe('title auto 1'); + expect(node1.lastElementChild.textContent).toBe('content auto 1'); + --count; + if (!count) done(); + }) + + defineTestElement(component2); + + var node2 = new component2(); + document.body.appendChild(node2); + node2.rxn('firstpaint', function(){ + expect(node2.firstElementChild.textContent).toBe('title auto 2'); + expect(node2.lastElementChild.textContent).toBe('content auto 2'); + --count; + if (!count) done(); + requestAnimationFrame(() => { + --count; + }); + node2.render('bar', { throttle: 'frame' }).then(() => { + expect(node2.firstElementChild.textContent).toBe('swap'); + expect(node2.lastElementChild.textContent).toBe('swapped'); + --count; + if (!count) done(); + }) + }); + + + xtag.create("x-test", class extends XTagElement { + set 'inSource::attr' (val){ + --count; + } + '::template(firstpaint)'(){ + return `

title auto 2

content auto 2

`; + } + }); + + customElements.whenDefined('x-test').then(() => { + --count; + if (!count) done(); + }); + + document.querySelector('x-test').rxn('ready', function(){ + --count; + if (!count) done(); + }); + + }); + + it("attach a named template and render when referenced", function(done) { + + var component = xtag.create(class extends XTagElement { + 'foo::template'(){ + return `

title2

content2

`; + } + }); + + defineTestElement(component); + + var node = new component(); + node.render('foo').then(() => { + expect(node.firstElementChild.textContent).toBe('title2'); + expect(node.lastElementChild.textContent).toBe('content2'); + done(); + }); + + }); + + it("include the right values when a template is rendered", function() { + + var count = 0; + + var component = xtag.create(class extends XTagElement { + get 'foo::attr'(){} + 'bar'(){ return 'bar' } + '::template'(){ + return `

${this.foo}

${this.bar()}

`; + } + }); + + defineTestElement(component); + + var node = new component(); + node.setAttribute('foo', 'foo'); + node.render(); + expect(node.firstElementChild.textContent).toBe('foo'); + expect(node.lastElementChild.textContent).toBe('bar'); + }); + +}); + +describe("X-Tag pseudos should", function() { + + it("be parsed correctly and called when invoked", function() { + + var count = 0; + + xtag.pseudos.foo = { + onInvoke(){ + count++; + } + } + + var component = xtag.create(class extends XTagElement { + 'one:foo'(){ count++; } + set 'two::attr:foo'(val){ count++; } + 'three::event:foo'(){ count++; } + }); + + defineTestElement(component); + + var node = new component(); + node.one(); + node.two = 2; + xtag.fireEvent(node, 'three'); + + expect(count).toBe(6); + + }); + +}); + +describe("X-Tag events should", function() { + + it("be compatible with all types of elements", function() { + + var count = 0; + + var component = xtag.create(class extends XTagElement { + 'click::event'(){ count++; } + }); + + defineTestElement(component); + + var node = new component(); + node.click(); + var div = document.createElement('div'); + xtag.addEvent(div, 'click', function(){ + count++; + }); + div.click(); + + expect(count).toBe(2); + + }); + + it("allow for use of pseudos on all types of elements", function() { + + var count = 0; + + var component = xtag.create(class extends XTagElement { + 'click::event:delegate(div)'(){ count++; } + }); + + defineTestElement(component); + + var custom = new component(); + var customChild = custom.appendChild(document.createElement('div')); + customChild.click(); + var native = document.createElement('div'); + var nativeChild = custom.appendChild(document.createElement('div')); + xtag.addEvent(native, 'click:delegate(div)', function(){ + count++; + }); + nativeChild.click(); + + expect(count).toBe(2); + + }); + +}); \ No newline at end of file diff --git a/tests/jasmine/boot.js b/tests/jasmine/boot.js new file mode 100644 index 0000000..a99774d --- /dev/null +++ b/tests/jasmine/boot.js @@ -0,0 +1,130 @@ +/** + Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js` and `jasmine_html.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. + + If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. + + The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. + + [jasmine-gem]: http://github.com/pivotal/jasmine-gem + */ + +(function() { + + /** + * ## Require & Instantiate + * + * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. + */ + window.jasmine = jasmineRequire.core(jasmineRequire); + + /** + * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. + */ + jasmineRequire.html(jasmine); + + /** + * Create the Jasmine environment. This is used to run all specs in a project. + */ + var env = jasmine.getEnv(); + + /** + * ## The Global Interface + * + * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. + */ + var jasmineInterface = jasmineRequire.interface(jasmine, env); + + /** + * Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. + */ + extend(window, jasmineInterface); + + /** + * ## Runner Parameters + * + * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. + */ + + var queryString = new jasmine.QueryString({ + getWindowLocation: function() { return window.location; } + }); + + var catchingExceptions = queryString.getParam("catch"); + env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions); + + var throwingExpectationFailures = queryString.getParam("throwFailures"); + env.throwOnExpectationFailure(throwingExpectationFailures); + + var random = queryString.getParam("random"); + env.randomizeTests(random); + + var seed = queryString.getParam("seed"); + if (seed) { + env.seed(seed); + } + + /** + * ## Reporters + * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). + */ + var htmlReporter = new jasmine.HtmlReporter({ + env: env, + onRaiseExceptionsClick: function() { queryString.navigateWithNewParam("catch", !env.catchingExceptions()); }, + onThrowExpectationsClick: function() { queryString.navigateWithNewParam("throwFailures", !env.throwingExpectationFailures()); }, + onRandomClick: function() { queryString.navigateWithNewParam("random", !env.randomTests()); }, + addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); }, + getContainer: function() { return document.body; }, + createElement: function() { return document.createElement.apply(document, arguments); }, + createTextNode: function() { return document.createTextNode.apply(document, arguments); }, + timer: new jasmine.Timer() + }); + + /** + * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. + */ + env.addReporter(jasmineInterface.jsApiReporter); + env.addReporter(htmlReporter); + + /** + * Filter which specs will be run by matching the start of the full name against the `spec` query param. + */ + var specFilter = new jasmine.HtmlSpecFilter({ + filterString: function() { return queryString.getParam("spec"); } + }); + + env.specFilter = function(spec) { + return specFilter.matches(spec.getFullName()); + }; + + /** + * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. + */ + window.setTimeout = window.setTimeout; + window.setInterval = window.setInterval; + window.clearTimeout = window.clearTimeout; + window.clearInterval = window.clearInterval; + + /** + * ## Execution + * + * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. + */ + var currentWindowOnload = window.onload; + + window.onload = function() { + if (currentWindowOnload) { + currentWindowOnload(); + } + htmlReporter.initialize(); + env.execute(); + }; + + /** + * Helper function for readability above. + */ + function extend(destination, source) { + for (var property in source) destination[property] = source[property]; + return destination; + } + +}()); diff --git a/tests/jasmine/console.js b/tests/jasmine/console.js new file mode 100644 index 0000000..cbc4f93 --- /dev/null +++ b/tests/jasmine/console.js @@ -0,0 +1,190 @@ +/* +Copyright (c) 2008-2016 Pivotal Labs + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +function getJasmineRequireObj() { + if (typeof module !== 'undefined' && module.exports) { + return exports; + } else { + window.jasmineRequire = window.jasmineRequire || {}; + return window.jasmineRequire; + } +} + +getJasmineRequireObj().console = function(jRequire, j$) { + j$.ConsoleReporter = jRequire.ConsoleReporter(); +}; + +getJasmineRequireObj().ConsoleReporter = function() { + + var noopTimer = { + start: function(){}, + elapsed: function(){ return 0; } + }; + + function ConsoleReporter(options) { + var print = options.print, + showColors = options.showColors || false, + onComplete = options.onComplete || function() {}, + timer = options.timer || noopTimer, + specCount, + failureCount, + failedSpecs = [], + pendingCount, + ansi = { + green: '\x1B[32m', + red: '\x1B[31m', + yellow: '\x1B[33m', + none: '\x1B[0m' + }, + failedSuites = []; + + print('ConsoleReporter is deprecated and will be removed in a future version.'); + + this.jasmineStarted = function() { + specCount = 0; + failureCount = 0; + pendingCount = 0; + print('Started'); + printNewline(); + timer.start(); + }; + + this.jasmineDone = function() { + printNewline(); + for (var i = 0; i < failedSpecs.length; i++) { + specFailureDetails(failedSpecs[i]); + } + + if(specCount > 0) { + printNewline(); + + var specCounts = specCount + ' ' + plural('spec', specCount) + ', ' + + failureCount + ' ' + plural('failure', failureCount); + + if (pendingCount) { + specCounts += ', ' + pendingCount + ' pending ' + plural('spec', pendingCount); + } + + print(specCounts); + } else { + print('No specs found'); + } + + printNewline(); + var seconds = timer.elapsed() / 1000; + print('Finished in ' + seconds + ' ' + plural('second', seconds)); + printNewline(); + + for(i = 0; i < failedSuites.length; i++) { + suiteFailureDetails(failedSuites[i]); + } + + onComplete(failureCount === 0); + }; + + this.specDone = function(result) { + specCount++; + + if (result.status == 'pending') { + pendingCount++; + print(colored('yellow', '*')); + return; + } + + if (result.status == 'passed') { + print(colored('green', '.')); + return; + } + + if (result.status == 'failed') { + failureCount++; + failedSpecs.push(result); + print(colored('red', 'F')); + } + }; + + this.suiteDone = function(result) { + if (result.failedExpectations && result.failedExpectations.length > 0) { + failureCount++; + failedSuites.push(result); + } + }; + + return this; + + function printNewline() { + print('\n'); + } + + function colored(color, str) { + return showColors ? (ansi[color] + str + ansi.none) : str; + } + + function plural(str, count) { + return count == 1 ? str : str + 's'; + } + + function repeat(thing, times) { + var arr = []; + for (var i = 0; i < times; i++) { + arr.push(thing); + } + return arr; + } + + function indent(str, spaces) { + var lines = (str || '').split('\n'); + var newArr = []; + for (var i = 0; i < lines.length; i++) { + newArr.push(repeat(' ', spaces).join('') + lines[i]); + } + return newArr.join('\n'); + } + + function specFailureDetails(result) { + printNewline(); + print(result.fullName); + + for (var i = 0; i < result.failedExpectations.length; i++) { + var failedExpectation = result.failedExpectations[i]; + printNewline(); + print(indent(failedExpectation.message, 2)); + print(indent(failedExpectation.stack, 2)); + } + + printNewline(); + } + + function suiteFailureDetails(result) { + for (var i = 0; i < result.failedExpectations.length; i++) { + printNewline(); + print(colored('red', 'An error was thrown in an afterAll')); + printNewline(); + print(colored('red', 'AfterAll ' + result.failedExpectations[i].message)); + + } + printNewline(); + } + } + + return ConsoleReporter; +}; diff --git a/tests/jasmine/jasmine-html.js b/tests/jasmine/jasmine-html.js new file mode 100644 index 0000000..233c982 --- /dev/null +++ b/tests/jasmine/jasmine-html.js @@ -0,0 +1,481 @@ +/* +Copyright (c) 2008-2016 Pivotal Labs + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +jasmineRequire.html = function(j$) { + j$.ResultsNode = jasmineRequire.ResultsNode(); + j$.HtmlReporter = jasmineRequire.HtmlReporter(j$); + j$.QueryString = jasmineRequire.QueryString(); + j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter(); +}; + +jasmineRequire.HtmlReporter = function(j$) { + + var noopTimer = { + start: function() {}, + elapsed: function() { return 0; } + }; + + function HtmlReporter(options) { + var env = options.env || {}, + getContainer = options.getContainer, + createElement = options.createElement, + createTextNode = options.createTextNode, + onRaiseExceptionsClick = options.onRaiseExceptionsClick || function() {}, + onThrowExpectationsClick = options.onThrowExpectationsClick || function() {}, + onRandomClick = options.onRandomClick || function() {}, + addToExistingQueryString = options.addToExistingQueryString || defaultQueryString, + timer = options.timer || noopTimer, + results = [], + specsExecuted = 0, + failureCount = 0, + pendingSpecCount = 0, + htmlReporterMain, + symbols, + failedSuites = []; + + this.initialize = function() { + clearPrior(); + htmlReporterMain = createDom('div', {className: 'jasmine_html-reporter'}, + createDom('div', {className: 'jasmine-banner'}, + createDom('a', {className: 'jasmine-title', href: 'http://jasmine.github.io/', target: '_blank'}), + createDom('span', {className: 'jasmine-version'}, j$.version) + ), + createDom('ul', {className: 'jasmine-symbol-summary'}), + createDom('div', {className: 'jasmine-alert'}), + createDom('div', {className: 'jasmine-results'}, + createDom('div', {className: 'jasmine-failures'}) + ) + ); + getContainer().appendChild(htmlReporterMain); + }; + + var totalSpecsDefined; + this.jasmineStarted = function(options) { + totalSpecsDefined = options.totalSpecsDefined || 0; + timer.start(); + }; + + var summary = createDom('div', {className: 'jasmine-summary'}); + + var topResults = new j$.ResultsNode({}, '', null), + currentParent = topResults; + + this.suiteStarted = function(result) { + currentParent.addChild(result, 'suite'); + currentParent = currentParent.last(); + }; + + this.suiteDone = function(result) { + if (result.status == 'failed') { + failedSuites.push(result); + } + + if (currentParent == topResults) { + return; + } + + currentParent = currentParent.parent; + }; + + this.specStarted = function(result) { + currentParent.addChild(result, 'spec'); + }; + + var failures = []; + this.specDone = function(result) { + if(noExpectations(result) && typeof console !== 'undefined' && typeof console.error !== 'undefined') { + console.error('Spec \'' + result.fullName + '\' has no expectations.'); + } + + if (result.status != 'disabled') { + specsExecuted++; + } + + if (!symbols){ + symbols = find('.jasmine-symbol-summary'); + } + + symbols.appendChild(createDom('li', { + className: noExpectations(result) ? 'jasmine-empty' : 'jasmine-' + result.status, + id: 'spec_' + result.id, + title: result.fullName + } + )); + + if (result.status == 'failed') { + failureCount++; + + var failure = + createDom('div', {className: 'jasmine-spec-detail jasmine-failed'}, + createDom('div', {className: 'jasmine-description'}, + createDom('a', {title: result.fullName, href: specHref(result)}, result.fullName) + ), + createDom('div', {className: 'jasmine-messages'}) + ); + var messages = failure.childNodes[1]; + + for (var i = 0; i < result.failedExpectations.length; i++) { + var expectation = result.failedExpectations[i]; + messages.appendChild(createDom('div', {className: 'jasmine-result-message'}, expectation.message)); + messages.appendChild(createDom('div', {className: 'jasmine-stack-trace'}, expectation.stack)); + } + + failures.push(failure); + } + + if (result.status == 'pending') { + pendingSpecCount++; + } + }; + + this.jasmineDone = function(doneResult) { + var banner = find('.jasmine-banner'); + var alert = find('.jasmine-alert'); + var order = doneResult && doneResult.order; + alert.appendChild(createDom('span', {className: 'jasmine-duration'}, 'finished in ' + timer.elapsed() / 1000 + 's')); + + banner.appendChild( + createDom('div', { className: 'jasmine-run-options' }, + createDom('span', { className: 'jasmine-trigger' }, 'Options'), + createDom('div', { className: 'jasmine-payload' }, + createDom('div', { className: 'jasmine-exceptions' }, + createDom('input', { + className: 'jasmine-raise', + id: 'jasmine-raise-exceptions', + type: 'checkbox' + }), + createDom('label', { className: 'jasmine-label', 'for': 'jasmine-raise-exceptions' }, 'raise exceptions')), + createDom('div', { className: 'jasmine-throw-failures' }, + createDom('input', { + className: 'jasmine-throw', + id: 'jasmine-throw-failures', + type: 'checkbox' + }), + createDom('label', { className: 'jasmine-label', 'for': 'jasmine-throw-failures' }, 'stop spec on expectation failure')), + createDom('div', { className: 'jasmine-random-order' }, + createDom('input', { + className: 'jasmine-random', + id: 'jasmine-random-order', + type: 'checkbox' + }), + createDom('label', { className: 'jasmine-label', 'for': 'jasmine-random-order' }, 'run tests in random order')) + ) + )); + + var raiseCheckbox = find('#jasmine-raise-exceptions'); + + raiseCheckbox.checked = !env.catchingExceptions(); + raiseCheckbox.onclick = onRaiseExceptionsClick; + + var throwCheckbox = find('#jasmine-throw-failures'); + throwCheckbox.checked = env.throwingExpectationFailures(); + throwCheckbox.onclick = onThrowExpectationsClick; + + var randomCheckbox = find('#jasmine-random-order'); + randomCheckbox.checked = env.randomTests(); + randomCheckbox.onclick = onRandomClick; + + var optionsMenu = find('.jasmine-run-options'), + optionsTrigger = optionsMenu.querySelector('.jasmine-trigger'), + optionsPayload = optionsMenu.querySelector('.jasmine-payload'), + isOpen = /\bjasmine-open\b/; + + optionsTrigger.onclick = function() { + if (isOpen.test(optionsPayload.className)) { + optionsPayload.className = optionsPayload.className.replace(isOpen, ''); + } else { + optionsPayload.className += ' jasmine-open'; + } + }; + + if (specsExecuted < totalSpecsDefined) { + var skippedMessage = 'Ran ' + specsExecuted + ' of ' + totalSpecsDefined + ' specs - run all'; + var skippedLink = order && order.random ? '?random=true' : '?'; + alert.appendChild( + createDom('span', {className: 'jasmine-bar jasmine-skipped'}, + createDom('a', {href: skippedLink, title: 'Run all specs'}, skippedMessage) + ) + ); + } + var statusBarMessage = ''; + var statusBarClassName = 'jasmine-bar '; + + if (totalSpecsDefined > 0) { + statusBarMessage += pluralize('spec', specsExecuted) + ', ' + pluralize('failure', failureCount); + if (pendingSpecCount) { statusBarMessage += ', ' + pluralize('pending spec', pendingSpecCount); } + statusBarClassName += (failureCount > 0) ? 'jasmine-failed' : 'jasmine-passed'; + } else { + statusBarClassName += 'jasmine-skipped'; + statusBarMessage += 'No specs found'; + } + + var seedBar; + if (order && order.random) { + seedBar = createDom('span', {className: 'jasmine-seed-bar'}, + ', randomized with seed ', + createDom('a', {title: 'randomized with seed ' + order.seed, href: seedHref(order.seed)}, order.seed) + ); + } + + alert.appendChild(createDom('span', {className: statusBarClassName}, statusBarMessage, seedBar)); + + var errorBarClassName = 'jasmine-bar jasmine-errored'; + var errorBarMessagePrefix = 'AfterAll '; + + for(var i = 0; i < failedSuites.length; i++) { + var failedSuite = failedSuites[i]; + for(var j = 0; j < failedSuite.failedExpectations.length; j++) { + alert.appendChild(createDom('span', {className: errorBarClassName}, errorBarMessagePrefix + failedSuite.failedExpectations[j].message)); + } + } + + var globalFailures = (doneResult && doneResult.failedExpectations) || []; + for(i = 0; i < globalFailures.length; i++) { + var failure = globalFailures[i]; + alert.appendChild(createDom('span', {className: errorBarClassName}, errorBarMessagePrefix + failure.message)); + } + + var results = find('.jasmine-results'); + results.appendChild(summary); + + summaryList(topResults, summary); + + function summaryList(resultsTree, domParent) { + var specListNode; + for (var i = 0; i < resultsTree.children.length; i++) { + var resultNode = resultsTree.children[i]; + if (resultNode.type == 'suite') { + var suiteListNode = createDom('ul', {className: 'jasmine-suite', id: 'suite-' + resultNode.result.id}, + createDom('li', {className: 'jasmine-suite-detail'}, + createDom('a', {href: specHref(resultNode.result)}, resultNode.result.description) + ) + ); + + summaryList(resultNode, suiteListNode); + domParent.appendChild(suiteListNode); + } + if (resultNode.type == 'spec') { + if (domParent.getAttribute('class') != 'jasmine-specs') { + specListNode = createDom('ul', {className: 'jasmine-specs'}); + domParent.appendChild(specListNode); + } + var specDescription = resultNode.result.description; + if(noExpectations(resultNode.result)) { + specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription; + } + if(resultNode.result.status === 'pending' && resultNode.result.pendingReason !== '') { + specDescription = specDescription + ' PENDING WITH MESSAGE: ' + resultNode.result.pendingReason; + } + specListNode.appendChild( + createDom('li', { + className: 'jasmine-' + resultNode.result.status, + id: 'spec-' + resultNode.result.id + }, + createDom('a', {href: specHref(resultNode.result)}, specDescription) + ) + ); + } + } + } + + if (failures.length) { + alert.appendChild( + createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-spec-list'}, + createDom('span', {}, 'Spec List | '), + createDom('a', {className: 'jasmine-failures-menu', href: '#'}, 'Failures'))); + alert.appendChild( + createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-failure-list'}, + createDom('a', {className: 'jasmine-spec-list-menu', href: '#'}, 'Spec List'), + createDom('span', {}, ' | Failures '))); + + find('.jasmine-failures-menu').onclick = function() { + setMenuModeTo('jasmine-failure-list'); + }; + find('.jasmine-spec-list-menu').onclick = function() { + setMenuModeTo('jasmine-spec-list'); + }; + + setMenuModeTo('jasmine-failure-list'); + + var failureNode = find('.jasmine-failures'); + for (i = 0; i < failures.length; i++) { + failureNode.appendChild(failures[i]); + } + } + }; + + return this; + + function find(selector) { + return getContainer().querySelector('.jasmine_html-reporter ' + selector); + } + + function clearPrior() { + // return the reporter + var oldReporter = find(''); + + if(oldReporter) { + getContainer().removeChild(oldReporter); + } + } + + function createDom(type, attrs, childrenVarArgs) { + var el = createElement(type); + + for (var i = 2; i < arguments.length; i++) { + var child = arguments[i]; + + if (typeof child === 'string') { + el.appendChild(createTextNode(child)); + } else { + if (child) { + el.appendChild(child); + } + } + } + + for (var attr in attrs) { + if (attr == 'className') { + el[attr] = attrs[attr]; + } else { + el.setAttribute(attr, attrs[attr]); + } + } + + return el; + } + + function pluralize(singular, count) { + var word = (count == 1 ? singular : singular + 's'); + + return '' + count + ' ' + word; + } + + function specHref(result) { + return addToExistingQueryString('spec', result.fullName); + } + + function seedHref(seed) { + return addToExistingQueryString('seed', seed); + } + + function defaultQueryString(key, value) { + return '?' + key + '=' + value; + } + + function setMenuModeTo(mode) { + htmlReporterMain.setAttribute('class', 'jasmine_html-reporter ' + mode); + } + + function noExpectations(result) { + return (result.failedExpectations.length + result.passedExpectations.length) === 0 && + result.status === 'passed'; + } + } + + return HtmlReporter; +}; + +jasmineRequire.HtmlSpecFilter = function() { + function HtmlSpecFilter(options) { + var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); + var filterPattern = new RegExp(filterString); + + this.matches = function(specName) { + return filterPattern.test(specName); + }; + } + + return HtmlSpecFilter; +}; + +jasmineRequire.ResultsNode = function() { + function ResultsNode(result, type, parent) { + this.result = result; + this.type = type; + this.parent = parent; + + this.children = []; + + this.addChild = function(result, type) { + this.children.push(new ResultsNode(result, type, this)); + }; + + this.last = function() { + return this.children[this.children.length - 1]; + }; + } + + return ResultsNode; +}; + +jasmineRequire.QueryString = function() { + function QueryString(options) { + + this.navigateWithNewParam = function(key, value) { + options.getWindowLocation().search = this.fullStringWithNewParam(key, value); + }; + + this.fullStringWithNewParam = function(key, value) { + var paramMap = queryStringToParamMap(); + paramMap[key] = value; + return toQueryString(paramMap); + }; + + this.getParam = function(key) { + return queryStringToParamMap()[key]; + }; + + return this; + + function toQueryString(paramMap) { + var qStrPairs = []; + for (var prop in paramMap) { + qStrPairs.push(encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop])); + } + return '?' + qStrPairs.join('&'); + } + + function queryStringToParamMap() { + var paramStr = options.getWindowLocation().search.substring(1), + params = [], + paramMap = {}; + + if (paramStr.length > 0) { + params = paramStr.split('&'); + for (var i = 0; i < params.length; i++) { + var p = params[i].split('='); + var value = decodeURIComponent(p[1]); + if (value === 'true' || value === 'false') { + value = JSON.parse(value); + } + paramMap[decodeURIComponent(p[0])] = value; + } + } + + return paramMap; + } + + } + + return QueryString; +}; diff --git a/tests/jasmine/jasmine.css b/tests/jasmine/jasmine.css new file mode 100644 index 0000000..6319982 --- /dev/null +++ b/tests/jasmine/jasmine.css @@ -0,0 +1,58 @@ +body { overflow-y: scroll; } + +.jasmine_html-reporter { background-color: #eee; padding: 5px; margin: -8px; font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333; } +.jasmine_html-reporter a { text-decoration: none; } +.jasmine_html-reporter a:hover { text-decoration: underline; } +.jasmine_html-reporter p, .jasmine_html-reporter h1, .jasmine_html-reporter h2, .jasmine_html-reporter h3, .jasmine_html-reporter h4, .jasmine_html-reporter h5, .jasmine_html-reporter h6 { margin: 0; line-height: 14px; } +.jasmine_html-reporter .jasmine-banner, .jasmine_html-reporter .jasmine-symbol-summary, .jasmine_html-reporter .jasmine-summary, .jasmine_html-reporter .jasmine-result-message, .jasmine_html-reporter .jasmine-spec .jasmine-description, .jasmine_html-reporter .jasmine-spec-detail .jasmine-description, .jasmine_html-reporter .jasmine-alert .jasmine-bar, .jasmine_html-reporter .jasmine-stack-trace { padding-left: 9px; padding-right: 9px; } +.jasmine_html-reporter .jasmine-banner { position: relative; } +.jasmine_html-reporter .jasmine-banner .jasmine-title { background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAAAZCAMAAACGusnyAAACdlBMVEX/////AP+AgICqVaqAQICZM5mAVYCSSZKAQICOOY6ATYCLRouAQICJO4mSSYCIRIiPQICHPIeOR4CGQ4aMQICGPYaLRoCFQ4WKQICPPYWJRYCOQoSJQICNPoSIRICMQoSHQICHRICKQoOHQICKPoOJO4OJQYOMQICMQ4CIQYKLQICIPoKLQ4CKQICNPoKJQISMQ4KJQoSLQYKJQISLQ4KIQoSKQYKIQICIQISMQoSKQYKLQIOLQoOJQYGLQIOKQIOMQoGKQYOLQYGKQIOLQoGJQYOJQIOKQYGJQIOKQoGKQIGLQIKLQ4KKQoGLQYKJQIGKQYKJQIGKQIKJQoGKQYKLQIGKQYKLQIOJQoKKQoOJQYKKQIOJQoKKQoOKQIOLQoKKQYOLQYKJQIOKQoKKQYKKQoKJQYOKQYKLQIOKQoKLQYOKQYKLQIOJQoGKQYKJQYGJQoGKQYKLQoGLQYGKQoGJQYKKQYGJQIKKQoGJQYKLQIKKQYGLQYKKQYGKQYGKQYKJQYOKQoKJQYOKQYKLQYOLQYOKQYKLQYOKQoKKQYKKQYOKQYOJQYKKQYKLQYKKQIKKQoKKQYKKQYKKQoKJQIKKQYKLQYKKQYKKQIKKQYKKQYKKQYKKQIKKQYKJQYGLQYGKQYKKQYKKQYGKQIKKQYGKQYOJQoKKQYOLQYKKQYOKQoKKQYKKQoKKQYKKQYKJQYKLQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKJQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKLQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKmIDpEAAAA0XRSTlMAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAiIyQlJycoKissLS4wMTQ1Njc4OTo7PDw+P0BCQ0RISUpLTE1OUFNUVVdYWFlaW15fYGFiY2ZnaGlqa2xtb3BxcnN0dnh5ent8fX5/gIGChIWIioyNjo+QkZOUlZaYmZqbnJ2eoKGio6WmqKmsra6vsLGztre4ubq7vL2+wMHDxMjJysvNzs/Q0dLU1tfY2dvc3t/g4eLj5ebn6Onq6+zt7u/w8vP09fb3+Pn6+/z9/vkVQXAAAAMaSURBVHhe5dXxV1N1GMfxz2ABbDgIAm5VDJOyVDIJLUMaVpBWUZUaGbmqoGpZRSiGiRWp6KoZ5AB0ZY50RImZQIlahKkMYXv/R90dBvET/rJfOr3Ouc8v99zPec59zvf56j+vYKlViSf7250X4Mr3O29Tgq08BdGB4DhcekEJ5YkQKFsgWZdtj9JpV+I8xPjLFqkrsEIqO8PHSpis36jWazcqjEsfJjkvRssVU37SdIOu4XCf5vEJPsnwJpnRNU9JmxhMk8l1gehIrq7hTFjzOD+Vf88629qKMJVNltInFeRexRQyJlNeqd1iGDlSzrIUIyXbyFfm3RYprcQRe7lqtWyGYbfc6dT0R2vmdOOkX3u55C1rP37ftiH+tDby4r/RBT0w8TyEkr+epB9XgPDmSYYWbrhCuFYaIyw3fDQAXTnSkh+ANofiHmWf9l+FY1I90FdQTetstO00o23novzVsJ7uB3/C5TkbjRwZ5JerwV4iRWq9HFbFMaK/d0TYqayRiQPuIxxS3Bu8JWU90/60tKi7vkhaznez0a/TbVOKj5CaOZh6fWG6/Lyv9B/ZLR1gw/S/fpbeVD3MCW1li6SvWDOn65tr99/uvWtBS0XDm4s1t+sOHpG0kpBKx/l77wOSnxLpcx6TXmXLTPQOKYOf9Q1dfr8/SJ2mFdCvl1Yl93DiHUZvXeLJbGSzYu5gVJ2slbSakOR8dxCq5adQ2oFLqsE9Ex3L4qQO0eOPeU5x56bypXp4onSEb5OkICX6lDat55TeoztNKQcJaakrz9KCb95oD69IKq+yKW4XPjknaS52V0TZqE2cTtXjcHSCRmUO88e+85hj3EP74i9p8pylw7lxgMDyyl6OV7ZejnjNMfatu87LxRbH0IS35gt2a4ZjmGpVBdKK3Wr6INk8jWWSGqbA55CKgjBRC6E9w78ydTg3ABS3AFV1QN0Y4Aa2pgEjWnQURj9L0ayK6R2ysEqxHUKzYnLvvyU+i9KM2JHJzE4vyZOyDcOwOsySajeLPc8sNvPJkFlyJd20wpqAzZeAfZ3oWybxd+P/3j+SG3uSBdf2VQAAAABJRU5ErkJggg==') no-repeat; background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iCiAgIHhtbG5zOmNjPSJodHRwOi8vY3JlYXRpdmVjb21tb25zLm9yZy9ucyMiCiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIKICAgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICB3aWR0aD0iNjgxLjk2MjUyIgogICBoZWlnaHQ9IjE4Ny41IgogICBpZD0ic3ZnMiIKICAgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+PG1ldGFkYXRhCiAgICAgaWQ9Im1ldGFkYXRhOCI+PHJkZjpSREY+PGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPjxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PjxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz48L2NjOldvcms+PC9yZGY6UkRGPjwvbWV0YWRhdGE+PGRlZnMKICAgICBpZD0iZGVmczYiPjxjbGlwUGF0aAogICAgICAgaWQ9ImNsaXBQYXRoMTgiPjxwYXRoCiAgICAgICAgIGQ9Ik0gMCwxNTAwIDAsMCBsIDU0NTUuNzQsMCAwLDE1MDAgTCAwLDE1MDAgeiIKICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgaWQ9InBhdGgyMCIgLz48L2NsaXBQYXRoPjwvZGVmcz48ZwogICAgIHRyYW5zZm9ybT0ibWF0cml4KDEuMjUsMCwwLC0xLjI1LDAsMTg3LjUpIgogICAgIGlkPSJnMTAiPjxnCiAgICAgICB0cmFuc2Zvcm09InNjYWxlKDAuMSwwLjEpIgogICAgICAgaWQ9ImcxMiI+PGcKICAgICAgICAgaWQ9ImcxNCI+PGcKICAgICAgICAgICBjbGlwLXBhdGg9InVybCgjY2xpcFBhdGgxOCkiCiAgICAgICAgICAgaWQ9ImcxNiI+PHBhdGgKICAgICAgICAgICAgIGQ9Im0gMTU0NCw1OTkuNDM0IGMgMC45MiwtNDAuMzUyIDI1LjY4LC04MS42MDIgNzEuNTMsLTgxLjYwMiAyNy41MSwwIDQ3LjY4LDEyLjgzMiA2MS40NCwzNS43NTQgMTIuODMsMjIuOTMgMTIuODMsNTYuODUyIDEyLjgzLDgyLjUyNyBsIDAsMzI5LjE4NCAtNzEuNTIsMCAwLDEwNC41NDMgMjY2LjgzLDAgMCwtMTA0LjU0MyAtNzAuNiwwIDAsLTM0NC43NyBjIDAsLTU4LjY5MSAtMy42OCwtMTA0LjUzMSAtNDQuOTMsLTE1Mi4yMTggLTM2LjY4LC00Mi4xOCAtOTYuMjgsLTY2LjAyIC0xNTMuMTQsLTY2LjAyIC0xMTcuMzcsMCAtMjA3LjI0LDc3Ljk0MSAtMjAyLjY0LDE5Ny4xNDUgbCAxMzAuMiwwIgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoMjIiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDIzMDEuNCw2NjIuNjk1IGMgMCw4MC43MDMgLTY2Ljk0LDE0NS44MTMgLTE0Ny42MywxNDUuODEzIC04My40NCwwIC0xNDcuNjMsLTY4Ljc4MSAtMTQ3LjYzLC0xNTEuMzAxIDAsLTc5Ljc4NSA2Ni45NCwtMTQ1LjgwMSAxNDUuOCwtMTQ1LjgwMSA4NC4zNSwwIDE0OS40Niw2Ny44NTIgMTQ5LjQ2LDE1MS4yODkgeiBtIC0xLjgzLC0xODEuNTQ3IGMgLTM1Ljc3LC01NC4wOTcgLTkzLjUzLC03OC44NTkgLTE1Ny43MiwtNzguODU5IC0xNDAuMywwIC0yNTEuMjQsMTE2LjQ0OSAtMjUxLjI0LDI1NC45MTggMCwxNDIuMTI5IDExMy43LDI2MC40MSAyNTYuNzQsMjYwLjQxIDYzLjI3LDAgMTE4LjI5LC0yOS4zMzYgMTUyLjIyLC04Mi41MjMgbCAwLDY5LjY4NyAxNzUuMTQsMCAwLC0xMDQuNTI3IC02MS40NCwwIDAsLTI4MC41OTggNjEuNDQsMCAwLC0xMDQuNTI3IC0xNzUuMTQsMCAwLDY2LjAxOSIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDI0IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSAyNjIyLjMzLDU1Ny4yNTggYyAzLjY3LC00NC4wMTYgMzMuMDEsLTczLjM0OCA3OC44NiwtNzMuMzQ4IDMzLjkzLDAgNjYuOTMsMjMuODI0IDY2LjkzLDYwLjUwNCAwLDQ4LjYwNiAtNDUuODQsNTYuODU2IC04My40NCw2Ni45NDEgLTg1LjI4LDIyLjAwNCAtMTc4LjgxLDQ4LjYwNiAtMTc4LjgxLDE1NS44NzkgMCw5My41MzYgNzguODYsMTQ3LjYzMyAxNjUuOTgsMTQ3LjYzMyA0NCwwIDgzLjQzLC05LjE3NiAxMTAuOTQsLTQ0LjAwOCBsIDAsMzMuOTIyIDgyLjUzLDAgMCwtMTMyLjk2NSAtMTA4LjIxLDAgYyAtMS44MywzNC44NTYgLTI4LjQyLDU3Ljc3NCAtNjMuMjYsNTcuNzc0IC0zMC4yNiwwIC02Mi4zNSwtMTcuNDIyIC02Mi4zNSwtNTEuMzQ4IDAsLTQ1Ljg0NyA0NC45MywtNTUuOTMgODAuNjksLTY0LjE4IDg4LjAyLC0yMC4xNzUgMTgyLjQ3LC00Ny42OTUgMTgyLjQ3LC0xNTcuNzM0IDAsLTk5LjAyNyAtODMuNDQsLTE1NC4wMzkgLTE3NS4xMywtMTU0LjAzOSAtNDkuNTMsMCAtOTQuNDYsMTUuNTgyIC0xMjYuNTUsNTMuMTggbCAwLC00MC4zNCAtODUuMjcsMCAwLDE0Mi4xMjkgMTE0LjYyLDAiCiAgICAgICAgICAgICBpbmtzY2FwZTpjb25uZWN0b3ItY3VydmF0dXJlPSIwIgogICAgICAgICAgICAgaWQ9InBhdGgyNiIKICAgICAgICAgICAgIHN0eWxlPSJmaWxsOiM4YTQxODI7ZmlsbC1vcGFjaXR5OjE7ZmlsbC1ydWxlOm5vbnplcm87c3Ryb2tlOm5vbmUiIC8+PHBhdGgKICAgICAgICAgICAgIGQ9Im0gMjk4OC4xOCw4MDAuMjU0IC02My4yNiwwIDAsMTA0LjUyNyAxNjUuMDUsMCAwLC03My4zNTUgYyAzMS4xOCw1MS4zNDcgNzguODYsODUuMjc3IDE0MS4yMSw4NS4yNzcgNjcuODUsMCAxMjQuNzEsLTQxLjI1OCAxNTIuMjEsLTEwMi42OTkgMjYuNiw2Mi4zNTEgOTIuNjIsMTAyLjY5OSAxNjAuNDcsMTAyLjY5OSA1My4xOSwwIDEwNS40NiwtMjIgMTQxLjIxLC02Mi4zNTEgMzguNTIsLTQ0LjkzOCAzOC41MiwtOTMuNTMyIDM4LjUyLC0xNDkuNDU3IGwgMCwtMTg1LjIzOSA2My4yNywwIDAsLTEwNC41MjcgLTIzOC40MiwwIDAsMTA0LjUyNyA2My4yOCwwIDAsMTU3LjcxNSBjIDAsMzIuMTAyIDAsNjAuNTI3IC0xNC42Nyw4OC45NTcgLTE4LjM0LDI2LjU4MiAtNDguNjEsNDAuMzQ0IC03OS43Nyw0MC4zNDQgLTMwLjI2LDAgLTYzLjI4LC0xMi44NDQgLTgyLjUzLC0zNi42NzIgLTIyLjkzLC0yOS4zNTUgLTIyLjkzLC01Ni44NjMgLTIyLjkzLC05Mi42MjkgbCAwLC0xNTcuNzE1IDYzLjI3LDAgMCwtMTA0LjUyNyAtMjM4LjQxLDAgMCwxMDQuNTI3IDYzLjI4LDAgMCwxNTAuMzgzIGMgMCwyOS4zNDggMCw2Ni4wMjMgLTE0LjY3LDkxLjY5OSAtMTUuNTksMjkuMzM2IC00Ny42OSw0NC45MzQgLTgwLjcsNDQuOTM0IC0zMS4xOCwwIC01Ny43NywtMTEuMDA4IC03Ny45NCwtMzUuNzc0IC0yNC43NywtMzAuMjUzIC0yNi42LC02Mi4zNDMgLTI2LjYsLTk5Ljk0MSBsIDAsLTE1MS4zMDEgNjMuMjcsMCAwLC0xMDQuNTI3IC0yMzguNCwwIDAsMTA0LjUyNyA2My4yNiwwIDAsMjgwLjU5OCIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDI4IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSAzOTk4LjY2LDk1MS41NDcgLTExMS44NywwIDAsMTE4LjI5MyAxMTEuODcsMCAwLC0xMTguMjkzIHogbSAwLC00MzEuODkxIDYzLjI3LDAgMCwtMTA0LjUyNyAtMjM5LjMzLDAgMCwxMDQuNTI3IDY0LjE5LDAgMCwyODAuNTk4IC02My4yNywwIDAsMTA0LjUyNyAxNzUuMTQsMCAwLC0zODUuMTI1IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoMzAiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDQxNTkuMTIsODAwLjI1NCAtNjMuMjcsMCAwLDEwNC41MjcgMTc1LjE0LDAgMCwtNjkuNjg3IGMgMjkuMzUsNTQuMTAxIDg0LjM2LDgwLjY5OSAxNDQuODcsODAuNjk5IDUzLjE5LDAgMTA1LjQ1LC0yMi4wMTYgMTQxLjIyLC02MC41MjcgNDAuMzQsLTQ0LjkzNCA0MS4yNiwtODguMDMyIDQxLjI2LC0xNDMuOTU3IGwgMCwtMTkxLjY1MyA2My4yNywwIDAsLTEwNC41MjcgLTIzOC40LDAgMCwxMDQuNTI3IDYzLjI2LDAgMCwxNTguNjM3IGMgMCwzMC4yNjIgMCw2MS40MzQgLTE5LjI2LDg4LjAzNSAtMjAuMTcsMjYuNTgyIC01My4xOCwzOS40MTQgLTg2LjE5LDM5LjQxNCAtMzMuOTMsMCAtNjguNzcsLTEzLjc1IC04OC45NCwtNDEuMjUgLTIxLjA5LC0yNy41IC0yMS4wOSwtNjkuNjg3IC0yMS4wOSwtMTAyLjcwNyBsIDAsLTE0Mi4xMjkgNjMuMjYsMCAwLC0xMDQuNTI3IC0yMzguNCwwIDAsMTA0LjUyNyA2My4yNywwIDAsMjgwLjU5OCIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDMyIgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA1MDgyLjQ4LDcwMy45NjUgYyAtMTkuMjQsNzAuNjA1IC04MS42LDExNS41NDcgLTE1NC4wNCwxMTUuNTQ3IC02Ni4wNCwwIC0xMjkuMywtNTEuMzQ4IC0xNDMuMDUsLTExNS41NDcgbCAyOTcuMDksMCB6IG0gODUuMjcsLTE0NC44ODMgYyAtMzguNTEsLTkzLjUyMyAtMTI5LjI3LC0xNTYuNzkzIC0yMzEuMDUsLTE1Ni43OTMgLTE0My4wNywwIC0yNTcuNjgsMTExLjg3MSAtMjU3LjY4LDI1NS44MzYgMCwxNDQuODgzIDEwOS4xMiwyNjEuMzI4IDI1NC45MSwyNjEuMzI4IDY3Ljg3LDAgMTM1LjcyLC0zMC4yNTggMTgzLjM5LC03OC44NjMgNDguNjIsLTUxLjM0NCA2OC43OSwtMTEzLjY5NSA2OC43OSwtMTgzLjM4MyBsIC0zLjY3LC0zOS40MzQgLTM5Ni4xMywwIGMgMTQuNjcsLTY3Ljg2MyA3Ny4wMywtMTE3LjM2MyAxNDYuNzIsLTExNy4zNjMgNDguNTksMCA5MC43NiwxOC4zMjggMTE4LjI4LDU4LjY3MiBsIDExNi40NCwwIgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoMzQiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDY5MC44OTUsODUwLjcwMyA5MC43NSwwIDIyLjU0MywzMS4wMzUgMCwyNDMuMTIyIC0xMzUuODI5LDAgMCwtMjQzLjE0MSAyMi41MzYsLTMxLjAxNiIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDM2IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA2MzIuMzk1LDc0Mi4yNTggMjguMDM5LDg2LjMwNCAtMjIuNTUxLDMxLjA0IC0yMzEuMjIzLDc1LjEyOCAtNDEuOTc2LC0xMjkuMTgzIDIzMS4yNTcsLTc1LjEzNyAzNi40NTQsMTEuODQ4IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoMzgiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDcxNy40NDksNjUzLjEwNSAtNzMuNDEsNTMuMzYgLTM2LjQ4OCwtMTEuODc1IC0xNDIuOTAzLC0xOTYuNjkyIDEwOS44ODMsLTc5LjgyOCAxNDIuOTE4LDE5Ni43MDMgMCwzOC4zMzIiCiAgICAgICAgICAgICBpbmtzY2FwZTpjb25uZWN0b3ItY3VydmF0dXJlPSIwIgogICAgICAgICAgICAgaWQ9InBhdGg0MCIKICAgICAgICAgICAgIHN0eWxlPSJmaWxsOiM4YTQxODI7ZmlsbC1vcGFjaXR5OjE7ZmlsbC1ydWxlOm5vbnplcm87c3Ryb2tlOm5vbmUiIC8+PHBhdGgKICAgICAgICAgICAgIGQ9Im0gODI4LjUyLDcwNi40NjUgLTczLjQyNiwtNTMuMzQgMC4wMTEsLTM4LjM1OSBMIDg5OC4wMDQsNDE4LjA3IDEwMDcuOSw0OTcuODk4IDg2NC45NzMsNjk0LjYwOSA4MjguNTIsNzA2LjQ2NSIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDQyIgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA4MTIuMDg2LDgyOC41ODYgMjguMDU1LC04Ni4zMiAzNi40ODQsLTExLjgzNiAyMzEuMjI1LDc1LjExNyAtNDEuOTcsMTI5LjE4MyAtMjMxLjIzOSwtNzUuMTQgLTIyLjU1NSwtMzEuMDA0IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoNDQiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDczNi4zMDEsMTMzNS44OCBjIC0zMjMuMDQ3LDAgLTU4NS44NzUsLTI2Mi43OCAtNTg1Ljg3NSwtNTg1Ljc4MiAwLC0zMjMuMTE4IDI2Mi44MjgsLTU4NS45NzcgNTg1Ljg3NSwtNTg1Ljk3NyAzMjMuMDE5LDAgNTg1LjgwOSwyNjIuODU5IDU4NS44MDksNTg1Ljk3NyAwLDMyMy4wMDIgLTI2Mi43OSw1ODUuNzgyIC01ODUuODA5LDU4NS43ODIgbCAwLDAgeiBtIDAsLTExOC42MSBjIDI1Ny45NzIsMCA0NjcuMTg5LC0yMDkuMTMgNDY3LjE4OSwtNDY3LjE3MiAwLC0yNTguMTI5IC0yMDkuMjE3LC00NjcuMzQ4IC00NjcuMTg5LC00NjcuMzQ4IC0yNTguMDc0LDAgLTQ2Ny4yNTQsMjA5LjIxOSAtNDY3LjI1NCw0NjcuMzQ4IDAsMjU4LjA0MiAyMDkuMTgsNDY3LjE3MiA0NjcuMjU0LDQ2Ny4xNzIiCiAgICAgICAgICAgICBpbmtzY2FwZTpjb25uZWN0b3ItY3VydmF0dXJlPSIwIgogICAgICAgICAgICAgaWQ9InBhdGg0NiIKICAgICAgICAgICAgIHN0eWxlPSJmaWxsOiM4YTQxODI7ZmlsbC1vcGFjaXR5OjE7ZmlsbC1ydWxlOm5vbnplcm87c3Ryb2tlOm5vbmUiIC8+PHBhdGgKICAgICAgICAgICAgIGQ9Im0gMTA5MS4xMyw2MTkuODgzIC0xNzUuNzcxLDU3LjEyMSAxMS42MjksMzUuODA4IDE3NS43NjIsLTU3LjEyMSAtMTEuNjIsLTM1LjgwOCIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDQ4IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0iTSA4NjYuOTU3LDkwMi4wNzQgODM2LjUsOTI0LjE5OSA5NDUuMTIxLDEwNzMuNzMgOTc1LjU4NiwxMDUxLjYxIDg2Ni45NTcsOTAyLjA3NCIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDUwIgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0iTSA2MDcuNDY1LDkwMy40NDUgNDk4Ljg1NSwxMDUyLjk3IDUyOS4zMiwxMDc1LjEgNjM3LjkzLDkyNS41NjYgNjA3LjQ2NSw5MDMuNDQ1IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoNTIiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDM4MC42ODgsNjIyLjEyOSAtMTEuNjI2LDM1LjgwMSAxNzUuNzU4LDU3LjA5IDExLjYyMSwtMzUuODAxIC0xNzUuNzUzLC01Ny4wOSIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDU0IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA3MTYuMjg5LDM3Ni41OSAzNy42NDA2LDAgMCwxODQuODE2IC0zNy42NDA2LDAgMCwtMTg0LjgxNiB6IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoNTYiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjwvZz48L2c+PC9nPjwvZz48L3N2Zz4=') no-repeat, none; -moz-background-size: 100%; -o-background-size: 100%; -webkit-background-size: 100%; background-size: 100%; display: block; float: left; width: 90px; height: 25px; } +.jasmine_html-reporter .jasmine-banner .jasmine-version { margin-left: 14px; position: relative; top: 6px; } +.jasmine_html-reporter #jasmine_content { position: fixed; right: 100%; } +.jasmine_html-reporter .jasmine-version { color: #aaa; } +.jasmine_html-reporter .jasmine-banner { margin-top: 14px; } +.jasmine_html-reporter .jasmine-duration { color: #fff; float: right; line-height: 28px; padding-right: 9px; } +.jasmine_html-reporter .jasmine-symbol-summary { overflow: hidden; *zoom: 1; margin: 14px 0; } +.jasmine_html-reporter .jasmine-symbol-summary li { display: inline-block; height: 10px; width: 14px; font-size: 16px; } +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-passed { font-size: 14px; } +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-passed:before { color: #007069; content: "\02022"; } +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-failed { line-height: 9px; } +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-failed:before { color: #ca3a11; content: "\d7"; font-weight: bold; margin-left: -1px; } +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-disabled { font-size: 14px; } +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-disabled:before { color: #bababa; content: "\02022"; } +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-pending { line-height: 17px; } +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-pending:before { color: #ba9d37; content: "*"; } +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-empty { font-size: 14px; } +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-empty:before { color: #ba9d37; content: "\02022"; } +.jasmine_html-reporter .jasmine-run-options { float: right; margin-right: 5px; border: 1px solid #8a4182; color: #8a4182; position: relative; line-height: 20px; } +.jasmine_html-reporter .jasmine-run-options .jasmine-trigger { cursor: pointer; padding: 8px 16px; } +.jasmine_html-reporter .jasmine-run-options .jasmine-payload { position: absolute; display: none; right: -1px; border: 1px solid #8a4182; background-color: #eee; white-space: nowrap; padding: 4px 8px; } +.jasmine_html-reporter .jasmine-run-options .jasmine-payload.jasmine-open { display: block; } +.jasmine_html-reporter .jasmine-bar { line-height: 28px; font-size: 14px; display: block; color: #eee; } +.jasmine_html-reporter .jasmine-bar.jasmine-failed { background-color: #ca3a11; } +.jasmine_html-reporter .jasmine-bar.jasmine-passed { background-color: #007069; } +.jasmine_html-reporter .jasmine-bar.jasmine-skipped { background-color: #bababa; } +.jasmine_html-reporter .jasmine-bar.jasmine-errored { background-color: #ca3a11; } +.jasmine_html-reporter .jasmine-bar.jasmine-menu { background-color: #fff; color: #aaa; } +.jasmine_html-reporter .jasmine-bar.jasmine-menu a { color: #333; } +.jasmine_html-reporter .jasmine-bar a { color: white; } +.jasmine_html-reporter.jasmine-spec-list .jasmine-bar.jasmine-menu.jasmine-failure-list, .jasmine_html-reporter.jasmine-spec-list .jasmine-results .jasmine-failures { display: none; } +.jasmine_html-reporter.jasmine-failure-list .jasmine-bar.jasmine-menu.jasmine-spec-list, .jasmine_html-reporter.jasmine-failure-list .jasmine-summary { display: none; } +.jasmine_html-reporter .jasmine-results { margin-top: 14px; } +.jasmine_html-reporter .jasmine-summary { margin-top: 14px; } +.jasmine_html-reporter .jasmine-summary ul { list-style-type: none; margin-left: 14px; padding-top: 0; padding-left: 0; } +.jasmine_html-reporter .jasmine-summary ul.jasmine-suite { margin-top: 7px; margin-bottom: 7px; } +.jasmine_html-reporter .jasmine-summary li.jasmine-passed a { color: #007069; } +.jasmine_html-reporter .jasmine-summary li.jasmine-failed a { color: #ca3a11; } +.jasmine_html-reporter .jasmine-summary li.jasmine-empty a { color: #ba9d37; } +.jasmine_html-reporter .jasmine-summary li.jasmine-pending a { color: #ba9d37; } +.jasmine_html-reporter .jasmine-summary li.jasmine-disabled a { color: #bababa; } +.jasmine_html-reporter .jasmine-description + .jasmine-suite { margin-top: 0; } +.jasmine_html-reporter .jasmine-suite { margin-top: 14px; } +.jasmine_html-reporter .jasmine-suite a { color: #333; } +.jasmine_html-reporter .jasmine-failures .jasmine-spec-detail { margin-bottom: 28px; } +.jasmine_html-reporter .jasmine-failures .jasmine-spec-detail .jasmine-description { background-color: #ca3a11; } +.jasmine_html-reporter .jasmine-failures .jasmine-spec-detail .jasmine-description a { color: white; } +.jasmine_html-reporter .jasmine-result-message { padding-top: 14px; color: #333; white-space: pre; } +.jasmine_html-reporter .jasmine-result-message span.jasmine-result { display: block; } +.jasmine_html-reporter .jasmine-stack-trace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666; border: 1px solid #ddd; background: white; white-space: pre; } diff --git a/tests/jasmine/jasmine.js b/tests/jasmine/jasmine.js new file mode 100644 index 0000000..7cab7e0 --- /dev/null +++ b/tests/jasmine/jasmine.js @@ -0,0 +1,3655 @@ +/* +Copyright (c) 2008-2016 Pivotal Labs + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +var getJasmineRequireObj = (function (jasmineGlobal) { + var jasmineRequire; + + if (typeof module !== 'undefined' && module.exports && typeof exports !== 'undefined') { + if (typeof global !== 'undefined') { + jasmineGlobal = global; + } else { + jasmineGlobal = {}; + } + jasmineRequire = exports; + } else { + if (typeof window !== 'undefined' && typeof window.toString === 'function' && window.toString() === '[object GjsGlobal]') { + jasmineGlobal = window; + } + jasmineRequire = jasmineGlobal.jasmineRequire = jasmineGlobal.jasmineRequire || {}; + } + + function getJasmineRequire() { + return jasmineRequire; + } + + getJasmineRequire().core = function(jRequire) { + var j$ = {}; + + jRequire.base(j$, jasmineGlobal); + j$.util = jRequire.util(); + j$.errors = jRequire.errors(); + j$.formatErrorMsg = jRequire.formatErrorMsg(); + j$.Any = jRequire.Any(j$); + j$.Anything = jRequire.Anything(j$); + j$.CallTracker = jRequire.CallTracker(j$); + j$.MockDate = jRequire.MockDate(); + j$.Clock = jRequire.Clock(); + j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler(); + j$.Env = jRequire.Env(j$); + j$.ExceptionFormatter = jRequire.ExceptionFormatter(); + j$.Expectation = jRequire.Expectation(); + j$.buildExpectationResult = jRequire.buildExpectationResult(); + j$.JsApiReporter = jRequire.JsApiReporter(); + j$.matchersUtil = jRequire.matchersUtil(j$); + j$.ObjectContaining = jRequire.ObjectContaining(j$); + j$.ArrayContaining = jRequire.ArrayContaining(j$); + j$.pp = jRequire.pp(j$); + j$.QueueRunner = jRequire.QueueRunner(j$); + j$.ReportDispatcher = jRequire.ReportDispatcher(); + j$.Spec = jRequire.Spec(j$); + j$.SpyRegistry = jRequire.SpyRegistry(j$); + j$.SpyStrategy = jRequire.SpyStrategy(j$); + j$.StringMatching = jRequire.StringMatching(j$); + j$.Suite = jRequire.Suite(j$); + j$.Timer = jRequire.Timer(); + j$.TreeProcessor = jRequire.TreeProcessor(); + j$.version = jRequire.version(); + j$.Order = jRequire.Order(); + + j$.matchers = jRequire.requireMatchers(jRequire, j$); + + return j$; + }; + + return getJasmineRequire; +})(this); + +getJasmineRequireObj().requireMatchers = function(jRequire, j$) { + var availableMatchers = [ + 'toBe', + 'toBeCloseTo', + 'toBeDefined', + 'toBeFalsy', + 'toBeGreaterThan', + 'toBeGreaterThanOrEqual', + 'toBeLessThanOrEqual', + 'toBeLessThan', + 'toBeNaN', + 'toBeNull', + 'toBeTruthy', + 'toBeUndefined', + 'toContain', + 'toEqual', + 'toHaveBeenCalled', + 'toHaveBeenCalledWith', + 'toHaveBeenCalledTimes', + 'toMatch', + 'toThrow', + 'toThrowError' + ], + matchers = {}; + + for (var i = 0; i < availableMatchers.length; i++) { + var name = availableMatchers[i]; + matchers[name] = jRequire[name](j$); + } + + return matchers; +}; + +getJasmineRequireObj().base = function(j$, jasmineGlobal) { + j$.unimplementedMethod_ = function() { + throw new Error('unimplemented method'); + }; + + j$.MAX_PRETTY_PRINT_DEPTH = 40; + j$.MAX_PRETTY_PRINT_ARRAY_LENGTH = 100; + j$.DEFAULT_TIMEOUT_INTERVAL = 5000; + + j$.getGlobal = function() { + return jasmineGlobal; + }; + + j$.getEnv = function(options) { + var env = j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options); + //jasmine. singletons in here (setTimeout blah blah). + return env; + }; + + j$.isArray_ = function(value) { + return j$.isA_('Array', value); + }; + + j$.isString_ = function(value) { + return j$.isA_('String', value); + }; + + j$.isNumber_ = function(value) { + return j$.isA_('Number', value); + }; + + j$.isFunction_ = function(value) { + return j$.isA_('Function', value); + }; + + j$.isA_ = function(typeName, value) { + return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; + }; + + j$.isDomNode = function(obj) { + return obj.nodeType > 0; + }; + + j$.fnNameFor = function(func) { + if (func.name) { + return func.name; + } + + var matches = func.toString().match(/^\s*function\s*(\w*)\s*\(/); + return matches ? matches[1] : ''; + }; + + j$.any = function(clazz) { + return new j$.Any(clazz); + }; + + j$.anything = function() { + return new j$.Anything(); + }; + + j$.objectContaining = function(sample) { + return new j$.ObjectContaining(sample); + }; + + j$.stringMatching = function(expected) { + return new j$.StringMatching(expected); + }; + + j$.arrayContaining = function(sample) { + return new j$.ArrayContaining(sample); + }; + + j$.createSpy = function(name, originalFn) { + + var spyStrategy = new j$.SpyStrategy({ + name: name, + fn: originalFn, + getSpy: function() { return spy; } + }), + callTracker = new j$.CallTracker(), + spy = function() { + var callData = { + object: this, + args: Array.prototype.slice.apply(arguments) + }; + + callTracker.track(callData); + var returnValue = spyStrategy.exec.apply(this, arguments); + callData.returnValue = returnValue; + + return returnValue; + }; + + for (var prop in originalFn) { + if (prop === 'and' || prop === 'calls') { + throw new Error('Jasmine spies would overwrite the \'and\' and \'calls\' properties on the object being spied upon'); + } + + spy[prop] = originalFn[prop]; + } + + spy.and = spyStrategy; + spy.calls = callTracker; + + return spy; + }; + + j$.isSpy = function(putativeSpy) { + if (!putativeSpy) { + return false; + } + return putativeSpy.and instanceof j$.SpyStrategy && + putativeSpy.calls instanceof j$.CallTracker; + }; + + j$.createSpyObj = function(baseName, methodNames) { + if (j$.isArray_(baseName) && j$.util.isUndefined(methodNames)) { + methodNames = baseName; + baseName = 'unknown'; + } + + if (!j$.isArray_(methodNames) || methodNames.length === 0) { + throw 'createSpyObj requires a non-empty array of method names to create spies for'; + } + var obj = {}; + for (var i = 0; i < methodNames.length; i++) { + obj[methodNames[i]] = j$.createSpy(baseName + '.' + methodNames[i]); + } + return obj; + }; +}; + +getJasmineRequireObj().util = function() { + + var util = {}; + + util.inherit = function(childClass, parentClass) { + var Subclass = function() { + }; + Subclass.prototype = parentClass.prototype; + childClass.prototype = new Subclass(); + }; + + util.htmlEscape = function(str) { + if (!str) { + return str; + } + return str.replace(/&/g, '&') + .replace(//g, '>'); + }; + + util.argsToArray = function(args) { + var arrayOfArgs = []; + for (var i = 0; i < args.length; i++) { + arrayOfArgs.push(args[i]); + } + return arrayOfArgs; + }; + + util.isUndefined = function(obj) { + return obj === void 0; + }; + + util.arrayContains = function(array, search) { + var i = array.length; + while (i--) { + if (array[i] === search) { + return true; + } + } + return false; + }; + + util.clone = function(obj) { + if (Object.prototype.toString.apply(obj) === '[object Array]') { + return obj.slice(); + } + + var cloned = {}; + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + cloned[prop] = obj[prop]; + } + } + + return cloned; + }; + + return util; +}; + +getJasmineRequireObj().Spec = function(j$) { + function Spec(attrs) { + this.expectationFactory = attrs.expectationFactory; + this.resultCallback = attrs.resultCallback || function() {}; + this.id = attrs.id; + this.description = attrs.description || ''; + this.queueableFn = attrs.queueableFn; + this.beforeAndAfterFns = attrs.beforeAndAfterFns || function() { return {befores: [], afters: []}; }; + this.userContext = attrs.userContext || function() { return {}; }; + this.onStart = attrs.onStart || function() {}; + this.getSpecName = attrs.getSpecName || function() { return ''; }; + this.expectationResultFactory = attrs.expectationResultFactory || function() { }; + this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; + this.catchingExceptions = attrs.catchingExceptions || function() { return true; }; + this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; + + if (!this.queueableFn.fn) { + this.pend(); + } + + this.result = { + id: this.id, + description: this.description, + fullName: this.getFullName(), + failedExpectations: [], + passedExpectations: [], + pendingReason: '' + }; + } + + Spec.prototype.addExpectationResult = function(passed, data, isError) { + var expectationResult = this.expectationResultFactory(data); + if (passed) { + this.result.passedExpectations.push(expectationResult); + } else { + this.result.failedExpectations.push(expectationResult); + + if (this.throwOnExpectationFailure && !isError) { + throw new j$.errors.ExpectationFailed(); + } + } + }; + + Spec.prototype.expect = function(actual) { + return this.expectationFactory(actual, this); + }; + + Spec.prototype.execute = function(onComplete, enabled) { + var self = this; + + this.onStart(this); + + if (!this.isExecutable() || this.markedPending || enabled === false) { + complete(enabled); + return; + } + + var fns = this.beforeAndAfterFns(); + var allFns = fns.befores.concat(this.queueableFn).concat(fns.afters); + + this.queueRunnerFactory({ + queueableFns: allFns, + onException: function() { self.onException.apply(self, arguments); }, + onComplete: complete, + userContext: this.userContext() + }); + + function complete(enabledAgain) { + self.result.status = self.status(enabledAgain); + self.resultCallback(self.result); + + if (onComplete) { + onComplete(); + } + } + }; + + Spec.prototype.onException = function onException(e) { + if (Spec.isPendingSpecException(e)) { + this.pend(extractCustomPendingMessage(e)); + return; + } + + if (e instanceof j$.errors.ExpectationFailed) { + return; + } + + this.addExpectationResult(false, { + matcherName: '', + passed: false, + expected: '', + actual: '', + error: e + }, true); + }; + + Spec.prototype.disable = function() { + this.disabled = true; + }; + + Spec.prototype.pend = function(message) { + this.markedPending = true; + if (message) { + this.result.pendingReason = message; + } + }; + + Spec.prototype.getResult = function() { + this.result.status = this.status(); + return this.result; + }; + + Spec.prototype.status = function(enabled) { + if (this.disabled || enabled === false) { + return 'disabled'; + } + + if (this.markedPending) { + return 'pending'; + } + + if (this.result.failedExpectations.length > 0) { + return 'failed'; + } else { + return 'passed'; + } + }; + + Spec.prototype.isExecutable = function() { + return !this.disabled; + }; + + Spec.prototype.getFullName = function() { + return this.getSpecName(this); + }; + + var extractCustomPendingMessage = function(e) { + var fullMessage = e.toString(), + boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), + boilerplateEnd = boilerplateStart + Spec.pendingSpecExceptionMessage.length; + + return fullMessage.substr(boilerplateEnd); + }; + + Spec.pendingSpecExceptionMessage = '=> marked Pending'; + + Spec.isPendingSpecException = function(e) { + return !!(e && e.toString && e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1); + }; + + return Spec; +}; + +if (typeof window == void 0 && typeof exports == 'object') { + exports.Spec = jasmineRequire.Spec; +} + +/*jshint bitwise: false*/ + +getJasmineRequireObj().Order = function() { + function Order(options) { + this.random = 'random' in options ? options.random : true; + var seed = this.seed = options.seed || generateSeed(); + this.sort = this.random ? randomOrder : naturalOrder; + + function naturalOrder(items) { + return items; + } + + function randomOrder(items) { + var copy = items.slice(); + copy.sort(function(a, b) { + return jenkinsHash(seed + a.id) - jenkinsHash(seed + b.id); + }); + return copy; + } + + function generateSeed() { + return String(Math.random()).slice(-5); + } + + // Bob Jenkins One-at-a-Time Hash algorithm is a non-cryptographic hash function + // used to get a different output when the key changes slighly. + // We use your return to sort the children randomly in a consistent way when + // used in conjunction with a seed + + function jenkinsHash(key) { + var hash, i; + for(hash = i = 0; i < key.length; ++i) { + hash += key.charCodeAt(i); + hash += (hash << 10); + hash ^= (hash >> 6); + } + hash += (hash << 3); + hash ^= (hash >> 11); + hash += (hash << 15); + return hash; + } + + } + + return Order; +}; + +getJasmineRequireObj().Env = function(j$) { + function Env(options) { + options = options || {}; + + var self = this; + var global = options.global || j$.getGlobal(); + + var totalSpecsDefined = 0; + + var catchExceptions = true; + + var realSetTimeout = j$.getGlobal().setTimeout; + var realClearTimeout = j$.getGlobal().clearTimeout; + this.clock = new j$.Clock(global, function () { return new j$.DelayedFunctionScheduler(); }, new j$.MockDate(global)); + + var runnableResources = {}; + + var currentSpec = null; + var currentlyExecutingSuites = []; + var currentDeclarationSuite = null; + var throwOnExpectationFailure = false; + var random = false; + var seed = null; + + var currentSuite = function() { + return currentlyExecutingSuites[currentlyExecutingSuites.length - 1]; + }; + + var currentRunnable = function() { + return currentSpec || currentSuite(); + }; + + var reporter = new j$.ReportDispatcher([ + 'jasmineStarted', + 'jasmineDone', + 'suiteStarted', + 'suiteDone', + 'specStarted', + 'specDone' + ]); + + this.specFilter = function() { + return true; + }; + + this.addCustomEqualityTester = function(tester) { + if(!currentRunnable()) { + throw new Error('Custom Equalities must be added in a before function or a spec'); + } + runnableResources[currentRunnable().id].customEqualityTesters.push(tester); + }; + + this.addMatchers = function(matchersToAdd) { + if(!currentRunnable()) { + throw new Error('Matchers must be added in a before function or a spec'); + } + var customMatchers = runnableResources[currentRunnable().id].customMatchers; + for (var matcherName in matchersToAdd) { + customMatchers[matcherName] = matchersToAdd[matcherName]; + } + }; + + j$.Expectation.addCoreMatchers(j$.matchers); + + var nextSpecId = 0; + var getNextSpecId = function() { + return 'spec' + nextSpecId++; + }; + + var nextSuiteId = 0; + var getNextSuiteId = function() { + return 'suite' + nextSuiteId++; + }; + + var expectationFactory = function(actual, spec) { + return j$.Expectation.Factory({ + util: j$.matchersUtil, + customEqualityTesters: runnableResources[spec.id].customEqualityTesters, + customMatchers: runnableResources[spec.id].customMatchers, + actual: actual, + addExpectationResult: addExpectationResult + }); + + function addExpectationResult(passed, result) { + return spec.addExpectationResult(passed, result); + } + }; + + var defaultResourcesForRunnable = function(id, parentRunnableId) { + var resources = {spies: [], customEqualityTesters: [], customMatchers: {}}; + + if(runnableResources[parentRunnableId]){ + resources.customEqualityTesters = j$.util.clone(runnableResources[parentRunnableId].customEqualityTesters); + resources.customMatchers = j$.util.clone(runnableResources[parentRunnableId].customMatchers); + } + + runnableResources[id] = resources; + }; + + var clearResourcesForRunnable = function(id) { + spyRegistry.clearSpies(); + delete runnableResources[id]; + }; + + var beforeAndAfterFns = function(suite) { + return function() { + var befores = [], + afters = []; + + while(suite) { + befores = befores.concat(suite.beforeFns); + afters = afters.concat(suite.afterFns); + + suite = suite.parentSuite; + } + + return { + befores: befores.reverse(), + afters: afters + }; + }; + }; + + var getSpecName = function(spec, suite) { + var fullName = [spec.description], + suiteFullName = suite.getFullName(); + + if (suiteFullName !== '') { + fullName.unshift(suiteFullName); + } + return fullName.join(' '); + }; + + // TODO: we may just be able to pass in the fn instead of wrapping here + var buildExpectationResult = j$.buildExpectationResult, + exceptionFormatter = new j$.ExceptionFormatter(), + expectationResultFactory = function(attrs) { + attrs.messageFormatter = exceptionFormatter.message; + attrs.stackFormatter = exceptionFormatter.stack; + + return buildExpectationResult(attrs); + }; + + // TODO: fix this naming, and here's where the value comes in + this.catchExceptions = function(value) { + catchExceptions = !!value; + return catchExceptions; + }; + + this.catchingExceptions = function() { + return catchExceptions; + }; + + var maximumSpecCallbackDepth = 20; + var currentSpecCallbackDepth = 0; + + function clearStack(fn) { + currentSpecCallbackDepth++; + if (currentSpecCallbackDepth >= maximumSpecCallbackDepth) { + currentSpecCallbackDepth = 0; + realSetTimeout(fn, 0); + } else { + fn(); + } + } + + var catchException = function(e) { + return j$.Spec.isPendingSpecException(e) || catchExceptions; + }; + + this.throwOnExpectationFailure = function(value) { + throwOnExpectationFailure = !!value; + }; + + this.throwingExpectationFailures = function() { + return throwOnExpectationFailure; + }; + + this.randomizeTests = function(value) { + random = !!value; + }; + + this.randomTests = function() { + return random; + }; + + this.seed = function(value) { + if (value) { + seed = value; + } + return seed; + }; + + var queueRunnerFactory = function(options) { + options.catchException = catchException; + options.clearStack = options.clearStack || clearStack; + options.timeout = {setTimeout: realSetTimeout, clearTimeout: realClearTimeout}; + options.fail = self.fail; + + new j$.QueueRunner(options).execute(); + }; + + var topSuite = new j$.Suite({ + env: this, + id: getNextSuiteId(), + description: 'Jasmine__TopLevel__Suite', + expectationFactory: expectationFactory, + expectationResultFactory: expectationResultFactory + }); + defaultResourcesForRunnable(topSuite.id); + currentDeclarationSuite = topSuite; + + this.topSuite = function() { + return topSuite; + }; + + this.execute = function(runnablesToRun) { + if(!runnablesToRun) { + if (focusedRunnables.length) { + runnablesToRun = focusedRunnables; + } else { + runnablesToRun = [topSuite.id]; + } + } + + var order = new j$.Order({ + random: random, + seed: seed + }); + + var processor = new j$.TreeProcessor({ + tree: topSuite, + runnableIds: runnablesToRun, + queueRunnerFactory: queueRunnerFactory, + nodeStart: function(suite) { + currentlyExecutingSuites.push(suite); + defaultResourcesForRunnable(suite.id, suite.parentSuite.id); + reporter.suiteStarted(suite.result); + }, + nodeComplete: function(suite, result) { + if (!suite.disabled) { + clearResourcesForRunnable(suite.id); + } + currentlyExecutingSuites.pop(); + reporter.suiteDone(result); + }, + orderChildren: function(node) { + return order.sort(node.children); + } + }); + + if(!processor.processTree().valid) { + throw new Error('Invalid order: would cause a beforeAll or afterAll to be run multiple times'); + } + + reporter.jasmineStarted({ + totalSpecsDefined: totalSpecsDefined + }); + + currentlyExecutingSuites.push(topSuite); + + processor.execute(function() { + clearResourcesForRunnable(topSuite.id); + currentlyExecutingSuites.pop(); + + reporter.jasmineDone({ + order: order, + failedExpectations: topSuite.result.failedExpectations + }); + }); + }; + + this.addReporter = function(reporterToAdd) { + reporter.addReporter(reporterToAdd); + }; + + this.provideFallbackReporter = function(reporterToAdd) { + reporter.provideFallbackReporter(reporterToAdd); + }; + + this.clearReporters = function() { + reporter.clearReporters(); + }; + + var spyRegistry = new j$.SpyRegistry({currentSpies: function() { + if(!currentRunnable()) { + throw new Error('Spies must be created in a before function or a spec'); + } + return runnableResources[currentRunnable().id].spies; + }}); + + this.allowRespy = function(allow){ + spyRegistry.allowRespy(allow); + }; + + this.spyOn = function() { + return spyRegistry.spyOn.apply(spyRegistry, arguments); + }; + + var suiteFactory = function(description) { + var suite = new j$.Suite({ + env: self, + id: getNextSuiteId(), + description: description, + parentSuite: currentDeclarationSuite, + expectationFactory: expectationFactory, + expectationResultFactory: expectationResultFactory, + throwOnExpectationFailure: throwOnExpectationFailure + }); + + return suite; + }; + + this.describe = function(description, specDefinitions) { + var suite = suiteFactory(description); + if (specDefinitions.length > 0) { + throw new Error('describe does not expect any arguments'); + } + if (currentDeclarationSuite.markedPending) { + suite.pend(); + } + addSpecsToSuite(suite, specDefinitions); + return suite; + }; + + this.xdescribe = function(description, specDefinitions) { + var suite = suiteFactory(description); + suite.pend(); + addSpecsToSuite(suite, specDefinitions); + return suite; + }; + + var focusedRunnables = []; + + this.fdescribe = function(description, specDefinitions) { + var suite = suiteFactory(description); + suite.isFocused = true; + + focusedRunnables.push(suite.id); + unfocusAncestor(); + addSpecsToSuite(suite, specDefinitions); + + return suite; + }; + + function addSpecsToSuite(suite, specDefinitions) { + var parentSuite = currentDeclarationSuite; + parentSuite.addChild(suite); + currentDeclarationSuite = suite; + + var declarationError = null; + try { + specDefinitions.call(suite); + } catch (e) { + declarationError = e; + } + + if (declarationError) { + self.it('encountered a declaration exception', function() { + throw declarationError; + }); + } + + currentDeclarationSuite = parentSuite; + } + + function findFocusedAncestor(suite) { + while (suite) { + if (suite.isFocused) { + return suite.id; + } + suite = suite.parentSuite; + } + + return null; + } + + function unfocusAncestor() { + var focusedAncestor = findFocusedAncestor(currentDeclarationSuite); + if (focusedAncestor) { + for (var i = 0; i < focusedRunnables.length; i++) { + if (focusedRunnables[i] === focusedAncestor) { + focusedRunnables.splice(i, 1); + break; + } + } + } + } + + var specFactory = function(description, fn, suite, timeout) { + totalSpecsDefined++; + var spec = new j$.Spec({ + id: getNextSpecId(), + beforeAndAfterFns: beforeAndAfterFns(suite), + expectationFactory: expectationFactory, + resultCallback: specResultCallback, + getSpecName: function(spec) { + return getSpecName(spec, suite); + }, + onStart: specStarted, + description: description, + expectationResultFactory: expectationResultFactory, + queueRunnerFactory: queueRunnerFactory, + userContext: function() { return suite.clonedSharedUserContext(); }, + queueableFn: { + fn: fn, + timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; } + }, + throwOnExpectationFailure: throwOnExpectationFailure + }); + + if (!self.specFilter(spec)) { + spec.disable(); + } + + return spec; + + function specResultCallback(result) { + clearResourcesForRunnable(spec.id); + currentSpec = null; + reporter.specDone(result); + } + + function specStarted(spec) { + currentSpec = spec; + defaultResourcesForRunnable(spec.id, suite.id); + reporter.specStarted(spec.result); + } + }; + + this.it = function(description, fn, timeout) { + var spec = specFactory(description, fn, currentDeclarationSuite, timeout); + if (currentDeclarationSuite.markedPending) { + spec.pend(); + } + currentDeclarationSuite.addChild(spec); + return spec; + }; + + this.xit = function() { + var spec = this.it.apply(this, arguments); + spec.pend('Temporarily disabled with xit'); + return spec; + }; + + this.fit = function(description, fn, timeout){ + var spec = specFactory(description, fn, currentDeclarationSuite, timeout); + currentDeclarationSuite.addChild(spec); + focusedRunnables.push(spec.id); + unfocusAncestor(); + return spec; + }; + + this.expect = function(actual) { + if (!currentRunnable()) { + throw new Error('\'expect\' was used when there was no current spec, this could be because an asynchronous test timed out'); + } + + return currentRunnable().expect(actual); + }; + + this.beforeEach = function(beforeEachFunction, timeout) { + currentDeclarationSuite.beforeEach({ + fn: beforeEachFunction, + timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; } + }); + }; + + this.beforeAll = function(beforeAllFunction, timeout) { + currentDeclarationSuite.beforeAll({ + fn: beforeAllFunction, + timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; } + }); + }; + + this.afterEach = function(afterEachFunction, timeout) { + currentDeclarationSuite.afterEach({ + fn: afterEachFunction, + timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; } + }); + }; + + this.afterAll = function(afterAllFunction, timeout) { + currentDeclarationSuite.afterAll({ + fn: afterAllFunction, + timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; } + }); + }; + + this.pending = function(message) { + var fullMessage = j$.Spec.pendingSpecExceptionMessage; + if(message) { + fullMessage += message; + } + throw fullMessage; + }; + + this.fail = function(error) { + var message = 'Failed'; + if (error) { + message += ': '; + message += error.message || error; + } + + currentRunnable().addExpectationResult(false, { + matcherName: '', + passed: false, + expected: '', + actual: '', + message: message, + error: error && error.message ? error : null + }); + }; + } + + return Env; +}; + +getJasmineRequireObj().JsApiReporter = function() { + + var noopTimer = { + start: function(){}, + elapsed: function(){ return 0; } + }; + + function JsApiReporter(options) { + var timer = options.timer || noopTimer, + status = 'loaded'; + + this.started = false; + this.finished = false; + this.runDetails = {}; + + this.jasmineStarted = function() { + this.started = true; + status = 'started'; + timer.start(); + }; + + var executionTime; + + this.jasmineDone = function(runDetails) { + this.finished = true; + this.runDetails = runDetails; + executionTime = timer.elapsed(); + status = 'done'; + }; + + this.status = function() { + return status; + }; + + var suites = [], + suites_hash = {}; + + this.suiteStarted = function(result) { + suites_hash[result.id] = result; + }; + + this.suiteDone = function(result) { + storeSuite(result); + }; + + this.suiteResults = function(index, length) { + return suites.slice(index, index + length); + }; + + function storeSuite(result) { + suites.push(result); + suites_hash[result.id] = result; + } + + this.suites = function() { + return suites_hash; + }; + + var specs = []; + + this.specDone = function(result) { + specs.push(result); + }; + + this.specResults = function(index, length) { + return specs.slice(index, index + length); + }; + + this.specs = function() { + return specs; + }; + + this.executionTime = function() { + return executionTime; + }; + + } + + return JsApiReporter; +}; + +getJasmineRequireObj().CallTracker = function(j$) { + + function CallTracker() { + var calls = []; + var opts = {}; + + function argCloner(context) { + var clonedArgs = []; + var argsAsArray = j$.util.argsToArray(context.args); + for(var i = 0; i < argsAsArray.length; i++) { + if(Object.prototype.toString.apply(argsAsArray[i]).match(/^\[object/)) { + clonedArgs.push(j$.util.clone(argsAsArray[i])); + } else { + clonedArgs.push(argsAsArray[i]); + } + } + context.args = clonedArgs; + } + + this.track = function(context) { + if(opts.cloneArgs) { + argCloner(context); + } + calls.push(context); + }; + + this.any = function() { + return !!calls.length; + }; + + this.count = function() { + return calls.length; + }; + + this.argsFor = function(index) { + var call = calls[index]; + return call ? call.args : []; + }; + + this.all = function() { + return calls; + }; + + this.allArgs = function() { + var callArgs = []; + for(var i = 0; i < calls.length; i++){ + callArgs.push(calls[i].args); + } + + return callArgs; + }; + + this.first = function() { + return calls[0]; + }; + + this.mostRecent = function() { + return calls[calls.length - 1]; + }; + + this.reset = function() { + calls = []; + }; + + this.saveArgumentsByValue = function() { + opts.cloneArgs = true; + }; + + } + + return CallTracker; +}; + +getJasmineRequireObj().Clock = function() { + function Clock(global, delayedFunctionSchedulerFactory, mockDate) { + var self = this, + realTimingFunctions = { + setTimeout: global.setTimeout, + clearTimeout: global.clearTimeout, + setInterval: global.setInterval, + clearInterval: global.clearInterval + }, + fakeTimingFunctions = { + setTimeout: setTimeout, + clearTimeout: clearTimeout, + setInterval: setInterval, + clearInterval: clearInterval + }, + installed = false, + delayedFunctionScheduler, + timer; + + + self.install = function() { + if(!originalTimingFunctionsIntact()) { + throw new Error('Jasmine Clock was unable to install over custom global timer functions. Is the clock already installed?'); + } + replace(global, fakeTimingFunctions); + timer = fakeTimingFunctions; + delayedFunctionScheduler = delayedFunctionSchedulerFactory(); + installed = true; + + return self; + }; + + self.uninstall = function() { + delayedFunctionScheduler = null; + mockDate.uninstall(); + replace(global, realTimingFunctions); + + timer = realTimingFunctions; + installed = false; + }; + + self.withMock = function(closure) { + this.install(); + try { + closure(); + } finally { + this.uninstall(); + } + }; + + self.mockDate = function(initialDate) { + mockDate.install(initialDate); + }; + + self.setTimeout = function(fn, delay, params) { + if (legacyIE()) { + if (arguments.length > 2) { + throw new Error('IE < 9 cannot support extra params to setTimeout without a polyfill'); + } + return timer.setTimeout(fn, delay); + } + return Function.prototype.apply.apply(timer.setTimeout, [global, arguments]); + }; + + self.setInterval = function(fn, delay, params) { + if (legacyIE()) { + if (arguments.length > 2) { + throw new Error('IE < 9 cannot support extra params to setInterval without a polyfill'); + } + return timer.setInterval(fn, delay); + } + return Function.prototype.apply.apply(timer.setInterval, [global, arguments]); + }; + + self.clearTimeout = function(id) { + return Function.prototype.call.apply(timer.clearTimeout, [global, id]); + }; + + self.clearInterval = function(id) { + return Function.prototype.call.apply(timer.clearInterval, [global, id]); + }; + + self.tick = function(millis) { + if (installed) { + delayedFunctionScheduler.tick(millis, function(millis) { mockDate.tick(millis); }); + } else { + throw new Error('Mock clock is not installed, use jasmine.clock().install()'); + } + }; + + return self; + + function originalTimingFunctionsIntact() { + return global.setTimeout === realTimingFunctions.setTimeout && + global.clearTimeout === realTimingFunctions.clearTimeout && + global.setInterval === realTimingFunctions.setInterval && + global.clearInterval === realTimingFunctions.clearInterval; + } + + function legacyIE() { + //if these methods are polyfilled, apply will be present + return !(realTimingFunctions.setTimeout || realTimingFunctions.setInterval).apply; + } + + function replace(dest, source) { + for (var prop in source) { + dest[prop] = source[prop]; + } + } + + function setTimeout(fn, delay) { + return delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2)); + } + + function clearTimeout(id) { + return delayedFunctionScheduler.removeFunctionWithId(id); + } + + function setInterval(fn, interval) { + return delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true); + } + + function clearInterval(id) { + return delayedFunctionScheduler.removeFunctionWithId(id); + } + + function argSlice(argsObj, n) { + return Array.prototype.slice.call(argsObj, n); + } + } + + return Clock; +}; + +getJasmineRequireObj().DelayedFunctionScheduler = function() { + function DelayedFunctionScheduler() { + var self = this; + var scheduledLookup = []; + var scheduledFunctions = {}; + var currentTime = 0; + var delayedFnCount = 0; + + self.tick = function(millis, tickDate) { + millis = millis || 0; + var endTime = currentTime + millis; + + runScheduledFunctions(endTime, tickDate); + currentTime = endTime; + }; + + self.scheduleFunction = function(funcToCall, millis, params, recurring, timeoutKey, runAtMillis) { + var f; + if (typeof(funcToCall) === 'string') { + /* jshint evil: true */ + f = function() { return eval(funcToCall); }; + /* jshint evil: false */ + } else { + f = funcToCall; + } + + millis = millis || 0; + timeoutKey = timeoutKey || ++delayedFnCount; + runAtMillis = runAtMillis || (currentTime + millis); + + var funcToSchedule = { + runAtMillis: runAtMillis, + funcToCall: f, + recurring: recurring, + params: params, + timeoutKey: timeoutKey, + millis: millis + }; + + if (runAtMillis in scheduledFunctions) { + scheduledFunctions[runAtMillis].push(funcToSchedule); + } else { + scheduledFunctions[runAtMillis] = [funcToSchedule]; + scheduledLookup.push(runAtMillis); + scheduledLookup.sort(function (a, b) { + return a - b; + }); + } + + return timeoutKey; + }; + + self.removeFunctionWithId = function(timeoutKey) { + for (var runAtMillis in scheduledFunctions) { + var funcs = scheduledFunctions[runAtMillis]; + var i = indexOfFirstToPass(funcs, function (func) { + return func.timeoutKey === timeoutKey; + }); + + if (i > -1) { + if (funcs.length === 1) { + delete scheduledFunctions[runAtMillis]; + deleteFromLookup(runAtMillis); + } else { + funcs.splice(i, 1); + } + + // intervals get rescheduled when executed, so there's never more + // than a single scheduled function with a given timeoutKey + break; + } + } + }; + + return self; + + function indexOfFirstToPass(array, testFn) { + var index = -1; + + for (var i = 0; i < array.length; ++i) { + if (testFn(array[i])) { + index = i; + break; + } + } + + return index; + } + + function deleteFromLookup(key) { + var value = Number(key); + var i = indexOfFirstToPass(scheduledLookup, function (millis) { + return millis === value; + }); + + if (i > -1) { + scheduledLookup.splice(i, 1); + } + } + + function reschedule(scheduledFn) { + self.scheduleFunction(scheduledFn.funcToCall, + scheduledFn.millis, + scheduledFn.params, + true, + scheduledFn.timeoutKey, + scheduledFn.runAtMillis + scheduledFn.millis); + } + + function forEachFunction(funcsToRun, callback) { + for (var i = 0; i < funcsToRun.length; ++i) { + callback(funcsToRun[i]); + } + } + + function runScheduledFunctions(endTime, tickDate) { + tickDate = tickDate || function() {}; + if (scheduledLookup.length === 0 || scheduledLookup[0] > endTime) { + tickDate(endTime - currentTime); + return; + } + + do { + var newCurrentTime = scheduledLookup.shift(); + tickDate(newCurrentTime - currentTime); + + currentTime = newCurrentTime; + + var funcsToRun = scheduledFunctions[currentTime]; + delete scheduledFunctions[currentTime]; + + forEachFunction(funcsToRun, function(funcToRun) { + if (funcToRun.recurring) { + reschedule(funcToRun); + } + }); + + forEachFunction(funcsToRun, function(funcToRun) { + funcToRun.funcToCall.apply(null, funcToRun.params || []); + }); + } while (scheduledLookup.length > 0 && + // checking first if we're out of time prevents setTimeout(0) + // scheduled in a funcToRun from forcing an extra iteration + currentTime !== endTime && + scheduledLookup[0] <= endTime); + + // ran out of functions to call, but still time left on the clock + if (currentTime !== endTime) { + tickDate(endTime - currentTime); + } + } + } + + return DelayedFunctionScheduler; +}; + +getJasmineRequireObj().ExceptionFormatter = function() { + function ExceptionFormatter() { + this.message = function(error) { + var message = ''; + + if (error.name && error.message) { + message += error.name + ': ' + error.message; + } else { + message += error.toString() + ' thrown'; + } + + if (error.fileName || error.sourceURL) { + message += ' in ' + (error.fileName || error.sourceURL); + } + + if (error.line || error.lineNumber) { + message += ' (line ' + (error.line || error.lineNumber) + ')'; + } + + return message; + }; + + this.stack = function(error) { + return error ? error.stack : null; + }; + } + + return ExceptionFormatter; +}; + +getJasmineRequireObj().Expectation = function() { + + function Expectation(options) { + this.util = options.util || { buildFailureMessage: function() {} }; + this.customEqualityTesters = options.customEqualityTesters || []; + this.actual = options.actual; + this.addExpectationResult = options.addExpectationResult || function(){}; + this.isNot = options.isNot; + + var customMatchers = options.customMatchers || {}; + for (var matcherName in customMatchers) { + this[matcherName] = Expectation.prototype.wrapCompare(matcherName, customMatchers[matcherName]); + } + } + + Expectation.prototype.wrapCompare = function(name, matcherFactory) { + return function() { + var args = Array.prototype.slice.call(arguments, 0), + expected = args.slice(0), + message = ''; + + args.unshift(this.actual); + + var matcher = matcherFactory(this.util, this.customEqualityTesters), + matcherCompare = matcher.compare; + + function defaultNegativeCompare() { + var result = matcher.compare.apply(null, args); + result.pass = !result.pass; + return result; + } + + if (this.isNot) { + matcherCompare = matcher.negativeCompare || defaultNegativeCompare; + } + + var result = matcherCompare.apply(null, args); + + if (!result.pass) { + if (!result.message) { + args.unshift(this.isNot); + args.unshift(name); + message = this.util.buildFailureMessage.apply(null, args); + } else { + if (Object.prototype.toString.apply(result.message) === '[object Function]') { + message = result.message(); + } else { + message = result.message; + } + } + } + + if (expected.length == 1) { + expected = expected[0]; + } + + // TODO: how many of these params are needed? + this.addExpectationResult( + result.pass, + { + matcherName: name, + passed: result.pass, + message: message, + actual: this.actual, + expected: expected // TODO: this may need to be arrayified/sliced + } + ); + }; + }; + + Expectation.addCoreMatchers = function(matchers) { + var prototype = Expectation.prototype; + for (var matcherName in matchers) { + var matcher = matchers[matcherName]; + prototype[matcherName] = prototype.wrapCompare(matcherName, matcher); + } + }; + + Expectation.Factory = function(options) { + options = options || {}; + + var expect = new Expectation(options); + + // TODO: this would be nice as its own Object - NegativeExpectation + // TODO: copy instead of mutate options + options.isNot = true; + expect.not = new Expectation(options); + + return expect; + }; + + return Expectation; +}; + +//TODO: expectation result may make more sense as a presentation of an expectation. +getJasmineRequireObj().buildExpectationResult = function() { + function buildExpectationResult(options) { + var messageFormatter = options.messageFormatter || function() {}, + stackFormatter = options.stackFormatter || function() {}; + + var result = { + matcherName: options.matcherName, + message: message(), + stack: stack(), + passed: options.passed + }; + + if(!result.passed) { + result.expected = options.expected; + result.actual = options.actual; + } + + return result; + + function message() { + if (options.passed) { + return 'Passed.'; + } else if (options.message) { + return options.message; + } else if (options.error) { + return messageFormatter(options.error); + } + return ''; + } + + function stack() { + if (options.passed) { + return ''; + } + + var error = options.error; + if (!error) { + try { + throw new Error(message()); + } catch (e) { + error = e; + } + } + return stackFormatter(error); + } + } + + return buildExpectationResult; +}; + +getJasmineRequireObj().MockDate = function() { + function MockDate(global) { + var self = this; + var currentTime = 0; + + if (!global || !global.Date) { + self.install = function() {}; + self.tick = function() {}; + self.uninstall = function() {}; + return self; + } + + var GlobalDate = global.Date; + + self.install = function(mockDate) { + if (mockDate instanceof GlobalDate) { + currentTime = mockDate.getTime(); + } else { + currentTime = new GlobalDate().getTime(); + } + + global.Date = FakeDate; + }; + + self.tick = function(millis) { + millis = millis || 0; + currentTime = currentTime + millis; + }; + + self.uninstall = function() { + currentTime = 0; + global.Date = GlobalDate; + }; + + createDateProperties(); + + return self; + + function FakeDate() { + switch(arguments.length) { + case 0: + return new GlobalDate(currentTime); + case 1: + return new GlobalDate(arguments[0]); + case 2: + return new GlobalDate(arguments[0], arguments[1]); + case 3: + return new GlobalDate(arguments[0], arguments[1], arguments[2]); + case 4: + return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3]); + case 5: + return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], + arguments[4]); + case 6: + return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], + arguments[4], arguments[5]); + default: + return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], + arguments[4], arguments[5], arguments[6]); + } + } + + function createDateProperties() { + FakeDate.prototype = GlobalDate.prototype; + + FakeDate.now = function() { + if (GlobalDate.now) { + return currentTime; + } else { + throw new Error('Browser does not support Date.now()'); + } + }; + + FakeDate.toSource = GlobalDate.toSource; + FakeDate.toString = GlobalDate.toString; + FakeDate.parse = GlobalDate.parse; + FakeDate.UTC = GlobalDate.UTC; + } + } + + return MockDate; +}; + +getJasmineRequireObj().pp = function(j$) { + + function PrettyPrinter() { + this.ppNestLevel_ = 0; + this.seen = []; + } + + PrettyPrinter.prototype.format = function(value) { + this.ppNestLevel_++; + try { + if (j$.util.isUndefined(value)) { + this.emitScalar('undefined'); + } else if (value === null) { + this.emitScalar('null'); + } else if (value === 0 && 1/value === -Infinity) { + this.emitScalar('-0'); + } else if (value === j$.getGlobal()) { + this.emitScalar(''); + } else if (value.jasmineToString) { + this.emitScalar(value.jasmineToString()); + } else if (typeof value === 'string') { + this.emitString(value); + } else if (j$.isSpy(value)) { + this.emitScalar('spy on ' + value.and.identity()); + } else if (value instanceof RegExp) { + this.emitScalar(value.toString()); + } else if (typeof value === 'function') { + this.emitScalar('Function'); + } else if (typeof value.nodeType === 'number') { + this.emitScalar('HTMLNode'); + } else if (value instanceof Date) { + this.emitScalar('Date(' + value + ')'); + } else if (value.toString && typeof value === 'object' && !(value instanceof Array) && value.toString !== Object.prototype.toString) { + this.emitScalar(value.toString()); + } else if (j$.util.arrayContains(this.seen, value)) { + this.emitScalar(''); + } else if (j$.isArray_(value) || j$.isA_('Object', value)) { + this.seen.push(value); + if (j$.isArray_(value)) { + this.emitArray(value); + } else { + this.emitObject(value); + } + this.seen.pop(); + } else { + this.emitScalar(value.toString()); + } + } finally { + this.ppNestLevel_--; + } + }; + + PrettyPrinter.prototype.iterateObject = function(obj, fn) { + for (var property in obj) { + if (!Object.prototype.hasOwnProperty.call(obj, property)) { continue; } + fn(property, obj.__lookupGetter__ ? (!j$.util.isUndefined(obj.__lookupGetter__(property)) && + obj.__lookupGetter__(property) !== null) : false); + } + }; + + PrettyPrinter.prototype.emitArray = j$.unimplementedMethod_; + PrettyPrinter.prototype.emitObject = j$.unimplementedMethod_; + PrettyPrinter.prototype.emitScalar = j$.unimplementedMethod_; + PrettyPrinter.prototype.emitString = j$.unimplementedMethod_; + + function StringPrettyPrinter() { + PrettyPrinter.call(this); + + this.string = ''; + } + + j$.util.inherit(StringPrettyPrinter, PrettyPrinter); + + StringPrettyPrinter.prototype.emitScalar = function(value) { + this.append(value); + }; + + StringPrettyPrinter.prototype.emitString = function(value) { + this.append('\'' + value + '\''); + }; + + StringPrettyPrinter.prototype.emitArray = function(array) { + if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { + this.append('Array'); + return; + } + var length = Math.min(array.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); + this.append('[ '); + for (var i = 0; i < length; i++) { + if (i > 0) { + this.append(', '); + } + this.format(array[i]); + } + if(array.length > length){ + this.append(', ...'); + } + + var self = this; + var first = array.length === 0; + this.iterateObject(array, function(property, isGetter) { + if (property.match(/^\d+$/)) { + return; + } + + if (first) { + first = false; + } else { + self.append(', '); + } + + self.formatProperty(array, property, isGetter); + }); + + this.append(' ]'); + }; + + StringPrettyPrinter.prototype.emitObject = function(obj) { + var constructorName = obj.constructor ? j$.fnNameFor(obj.constructor) : 'null'; + this.append(constructorName); + + if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { + return; + } + + var self = this; + this.append('({ '); + var first = true; + + this.iterateObject(obj, function(property, isGetter) { + if (first) { + first = false; + } else { + self.append(', '); + } + + self.formatProperty(obj, property, isGetter); + }); + + this.append(' })'); + }; + + StringPrettyPrinter.prototype.formatProperty = function(obj, property, isGetter) { + this.append(property); + this.append(': '); + if (isGetter) { + this.append(''); + } else { + this.format(obj[property]); + } + }; + + StringPrettyPrinter.prototype.append = function(value) { + this.string += value; + }; + + return function(value) { + var stringPrettyPrinter = new StringPrettyPrinter(); + stringPrettyPrinter.format(value); + return stringPrettyPrinter.string; + }; +}; + +getJasmineRequireObj().QueueRunner = function(j$) { + + function once(fn) { + var called = false; + return function() { + if (!called) { + called = true; + fn(); + } + return null; + }; + } + + function QueueRunner(attrs) { + this.queueableFns = attrs.queueableFns || []; + this.onComplete = attrs.onComplete || function() {}; + this.clearStack = attrs.clearStack || function(fn) {fn();}; + this.onException = attrs.onException || function() {}; + this.catchException = attrs.catchException || function() { return true; }; + this.userContext = attrs.userContext || {}; + this.timeout = attrs.timeout || {setTimeout: setTimeout, clearTimeout: clearTimeout}; + this.fail = attrs.fail || function() {}; + } + + QueueRunner.prototype.execute = function() { + this.run(this.queueableFns, 0); + }; + + QueueRunner.prototype.run = function(queueableFns, recursiveIndex) { + var length = queueableFns.length, + self = this, + iterativeIndex; + + + for(iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex++) { + var queueableFn = queueableFns[iterativeIndex]; + if (queueableFn.fn.length > 0) { + attemptAsync(queueableFn); + return; + } else { + attemptSync(queueableFn); + } + } + + var runnerDone = iterativeIndex >= length; + + if (runnerDone) { + this.clearStack(this.onComplete); + } + + function attemptSync(queueableFn) { + try { + queueableFn.fn.call(self.userContext); + } catch (e) { + handleException(e, queueableFn); + } + } + + function attemptAsync(queueableFn) { + var clearTimeout = function () { + Function.prototype.apply.apply(self.timeout.clearTimeout, [j$.getGlobal(), [timeoutId]]); + }, + next = once(function () { + clearTimeout(timeoutId); + self.run(queueableFns, iterativeIndex + 1); + }), + timeoutId; + + next.fail = function() { + self.fail.apply(null, arguments); + next(); + }; + + if (queueableFn.timeout) { + timeoutId = Function.prototype.apply.apply(self.timeout.setTimeout, [j$.getGlobal(), [function() { + var error = new Error('Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.'); + onException(error); + next(); + }, queueableFn.timeout()]]); + } + + try { + queueableFn.fn.call(self.userContext, next); + } catch (e) { + handleException(e, queueableFn); + next(); + } + } + + function onException(e) { + self.onException(e); + } + + function handleException(e, queueableFn) { + onException(e); + if (!self.catchException(e)) { + //TODO: set a var when we catch an exception and + //use a finally block to close the loop in a nice way.. + throw e; + } + } + }; + + return QueueRunner; +}; + +getJasmineRequireObj().ReportDispatcher = function() { + function ReportDispatcher(methods) { + + var dispatchedMethods = methods || []; + + for (var i = 0; i < dispatchedMethods.length; i++) { + var method = dispatchedMethods[i]; + this[method] = (function(m) { + return function() { + dispatch(m, arguments); + }; + }(method)); + } + + var reporters = []; + var fallbackReporter = null; + + this.addReporter = function(reporter) { + reporters.push(reporter); + }; + + this.provideFallbackReporter = function(reporter) { + fallbackReporter = reporter; + }; + + this.clearReporters = function() { + reporters = []; + }; + + return this; + + function dispatch(method, args) { + if (reporters.length === 0 && fallbackReporter !== null) { + reporters.push(fallbackReporter); + } + for (var i = 0; i < reporters.length; i++) { + var reporter = reporters[i]; + if (reporter[method]) { + reporter[method].apply(reporter, args); + } + } + } + } + + return ReportDispatcher; +}; + + +getJasmineRequireObj().SpyRegistry = function(j$) { + + var getErrorMsg = j$.formatErrorMsg('', 'spyOn(, )'); + + function SpyRegistry(options) { + options = options || {}; + var currentSpies = options.currentSpies || function() { return []; }; + + this.allowRespy = function(allow){ + this.respy = allow; + }; + + this.spyOn = function(obj, methodName) { + + if (j$.util.isUndefined(obj)) { + throw new Error(getErrorMsg('could not find an object to spy upon for ' + methodName + '()')); + } + + if (j$.util.isUndefined(methodName)) { + throw new Error(getErrorMsg('No method name supplied')); + } + + if (j$.util.isUndefined(obj[methodName])) { + throw new Error(getErrorMsg(methodName + '() method does not exist')); + } + + if (obj[methodName] && j$.isSpy(obj[methodName]) ) { + if ( !!this.respy ){ + return obj[methodName]; + }else { + throw new Error(getErrorMsg(methodName + ' has already been spied upon')); + } + } + + var descriptor; + try { + descriptor = Object.getOwnPropertyDescriptor(obj, methodName); + } catch(e) { + // IE 8 doesn't support `definePropery` on non-DOM nodes + } + + if (descriptor && !(descriptor.writable || descriptor.set)) { + throw new Error(getErrorMsg(methodName + ' is not declared writable or has no setter')); + } + + var originalMethod = obj[methodName], + spiedMethod = j$.createSpy(methodName, originalMethod), + restoreStrategy; + + if (Object.prototype.hasOwnProperty.call(obj, methodName)) { + restoreStrategy = function() { + obj[methodName] = originalMethod; + }; + } else { + restoreStrategy = function() { + if (!delete obj[methodName]) { + obj[methodName] = originalMethod; + } + }; + } + + currentSpies().push({ + restoreObjectToOriginalState: restoreStrategy + }); + + obj[methodName] = spiedMethod; + + return spiedMethod; + }; + + this.clearSpies = function() { + var spies = currentSpies(); + for (var i = spies.length - 1; i >= 0; i--) { + var spyEntry = spies[i]; + spyEntry.restoreObjectToOriginalState(); + } + }; + } + + return SpyRegistry; +}; + +getJasmineRequireObj().SpyStrategy = function(j$) { + + function SpyStrategy(options) { + options = options || {}; + + var identity = options.name || 'unknown', + originalFn = options.fn || function() {}, + getSpy = options.getSpy || function() {}, + plan = function() {}; + + this.identity = function() { + return identity; + }; + + this.exec = function() { + return plan.apply(this, arguments); + }; + + this.callThrough = function() { + plan = originalFn; + return getSpy(); + }; + + this.returnValue = function(value) { + plan = function() { + return value; + }; + return getSpy(); + }; + + this.returnValues = function() { + var values = Array.prototype.slice.call(arguments); + plan = function () { + return values.shift(); + }; + return getSpy(); + }; + + this.throwError = function(something) { + var error = (something instanceof Error) ? something : new Error(something); + plan = function() { + throw error; + }; + return getSpy(); + }; + + this.callFake = function(fn) { + if(!j$.isFunction_(fn)) { + throw new Error('Argument passed to callFake should be a function, got ' + fn); + } + plan = fn; + return getSpy(); + }; + + this.stub = function(fn) { + plan = function() {}; + return getSpy(); + }; + } + + return SpyStrategy; +}; + +getJasmineRequireObj().Suite = function(j$) { + function Suite(attrs) { + this.env = attrs.env; + this.id = attrs.id; + this.parentSuite = attrs.parentSuite; + this.description = attrs.description; + this.expectationFactory = attrs.expectationFactory; + this.expectationResultFactory = attrs.expectationResultFactory; + this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; + + this.beforeFns = []; + this.afterFns = []; + this.beforeAllFns = []; + this.afterAllFns = []; + this.disabled = false; + + this.children = []; + + this.result = { + id: this.id, + description: this.description, + fullName: this.getFullName(), + failedExpectations: [] + }; + } + + Suite.prototype.expect = function(actual) { + return this.expectationFactory(actual, this); + }; + + Suite.prototype.getFullName = function() { + var fullName = []; + for (var parentSuite = this; parentSuite; parentSuite = parentSuite.parentSuite) { + if (parentSuite.parentSuite) { + fullName.unshift(parentSuite.description); + } + } + return fullName.join(' '); + }; + + Suite.prototype.disable = function() { + this.disabled = true; + }; + + Suite.prototype.pend = function(message) { + this.markedPending = true; + }; + + Suite.prototype.beforeEach = function(fn) { + this.beforeFns.unshift(fn); + }; + + Suite.prototype.beforeAll = function(fn) { + this.beforeAllFns.push(fn); + }; + + Suite.prototype.afterEach = function(fn) { + this.afterFns.unshift(fn); + }; + + Suite.prototype.afterAll = function(fn) { + this.afterAllFns.push(fn); + }; + + Suite.prototype.addChild = function(child) { + this.children.push(child); + }; + + Suite.prototype.status = function() { + if (this.disabled) { + return 'disabled'; + } + + if (this.markedPending) { + return 'pending'; + } + + if (this.result.failedExpectations.length > 0) { + return 'failed'; + } else { + return 'finished'; + } + }; + + Suite.prototype.isExecutable = function() { + return !this.disabled; + }; + + Suite.prototype.canBeReentered = function() { + return this.beforeAllFns.length === 0 && this.afterAllFns.length === 0; + }; + + Suite.prototype.getResult = function() { + this.result.status = this.status(); + return this.result; + }; + + Suite.prototype.sharedUserContext = function() { + if (!this.sharedContext) { + this.sharedContext = this.parentSuite ? clone(this.parentSuite.sharedUserContext()) : {}; + } + + return this.sharedContext; + }; + + Suite.prototype.clonedSharedUserContext = function() { + return clone(this.sharedUserContext()); + }; + + Suite.prototype.onException = function() { + if (arguments[0] instanceof j$.errors.ExpectationFailed) { + return; + } + + if(isAfterAll(this.children)) { + var data = { + matcherName: '', + passed: false, + expected: '', + actual: '', + error: arguments[0] + }; + this.result.failedExpectations.push(this.expectationResultFactory(data)); + } else { + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + child.onException.apply(child, arguments); + } + } + }; + + Suite.prototype.addExpectationResult = function () { + if(isAfterAll(this.children) && isFailure(arguments)){ + var data = arguments[1]; + this.result.failedExpectations.push(this.expectationResultFactory(data)); + if(this.throwOnExpectationFailure) { + throw new j$.errors.ExpectationFailed(); + } + } else { + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + try { + child.addExpectationResult.apply(child, arguments); + } catch(e) { + // keep going + } + } + } + }; + + function isAfterAll(children) { + return children && children[0].result.status; + } + + function isFailure(args) { + return !args[0]; + } + + function clone(obj) { + var clonedObj = {}; + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + clonedObj[prop] = obj[prop]; + } + } + + return clonedObj; + } + + return Suite; +}; + +if (typeof window == void 0 && typeof exports == 'object') { + exports.Suite = jasmineRequire.Suite; +} + +getJasmineRequireObj().Timer = function() { + var defaultNow = (function(Date) { + return function() { return new Date().getTime(); }; + })(Date); + + function Timer(options) { + options = options || {}; + + var now = options.now || defaultNow, + startTime; + + this.start = function() { + startTime = now(); + }; + + this.elapsed = function() { + return now() - startTime; + }; + } + + return Timer; +}; + +getJasmineRequireObj().TreeProcessor = function() { + function TreeProcessor(attrs) { + var tree = attrs.tree, + runnableIds = attrs.runnableIds, + queueRunnerFactory = attrs.queueRunnerFactory, + nodeStart = attrs.nodeStart || function() {}, + nodeComplete = attrs.nodeComplete || function() {}, + orderChildren = attrs.orderChildren || function(node) { return node.children; }, + stats = { valid: true }, + processed = false, + defaultMin = Infinity, + defaultMax = 1 - Infinity; + + this.processTree = function() { + processNode(tree, false); + processed = true; + return stats; + }; + + this.execute = function(done) { + if (!processed) { + this.processTree(); + } + + if (!stats.valid) { + throw 'invalid order'; + } + + var childFns = wrapChildren(tree, 0); + + queueRunnerFactory({ + queueableFns: childFns, + userContext: tree.sharedUserContext(), + onException: function() { + tree.onException.apply(tree, arguments); + }, + onComplete: done + }); + }; + + function runnableIndex(id) { + for (var i = 0; i < runnableIds.length; i++) { + if (runnableIds[i] === id) { + return i; + } + } + } + + function processNode(node, parentEnabled) { + var executableIndex = runnableIndex(node.id); + + if (executableIndex !== undefined) { + parentEnabled = true; + } + + parentEnabled = parentEnabled && node.isExecutable(); + + if (!node.children) { + stats[node.id] = { + executable: parentEnabled && node.isExecutable(), + segments: [{ + index: 0, + owner: node, + nodes: [node], + min: startingMin(executableIndex), + max: startingMax(executableIndex) + }] + }; + } else { + var hasExecutableChild = false; + + var orderedChildren = orderChildren(node); + + for (var i = 0; i < orderedChildren.length; i++) { + var child = orderedChildren[i]; + + processNode(child, parentEnabled); + + if (!stats.valid) { + return; + } + + var childStats = stats[child.id]; + + hasExecutableChild = hasExecutableChild || childStats.executable; + } + + stats[node.id] = { + executable: hasExecutableChild + }; + + segmentChildren(node, orderedChildren, stats[node.id], executableIndex); + + if (!node.canBeReentered() && stats[node.id].segments.length > 1) { + stats = { valid: false }; + } + } + } + + function startingMin(executableIndex) { + return executableIndex === undefined ? defaultMin : executableIndex; + } + + function startingMax(executableIndex) { + return executableIndex === undefined ? defaultMax : executableIndex; + } + + function segmentChildren(node, orderedChildren, nodeStats, executableIndex) { + var currentSegment = { index: 0, owner: node, nodes: [], min: startingMin(executableIndex), max: startingMax(executableIndex) }, + result = [currentSegment], + lastMax = defaultMax, + orderedChildSegments = orderChildSegments(orderedChildren); + + function isSegmentBoundary(minIndex) { + return lastMax !== defaultMax && minIndex !== defaultMin && lastMax < minIndex - 1; + } + + for (var i = 0; i < orderedChildSegments.length; i++) { + var childSegment = orderedChildSegments[i], + maxIndex = childSegment.max, + minIndex = childSegment.min; + + if (isSegmentBoundary(minIndex)) { + currentSegment = {index: result.length, owner: node, nodes: [], min: defaultMin, max: defaultMax}; + result.push(currentSegment); + } + + currentSegment.nodes.push(childSegment); + currentSegment.min = Math.min(currentSegment.min, minIndex); + currentSegment.max = Math.max(currentSegment.max, maxIndex); + lastMax = maxIndex; + } + + nodeStats.segments = result; + } + + function orderChildSegments(children) { + var specifiedOrder = [], + unspecifiedOrder = []; + + for (var i = 0; i < children.length; i++) { + var child = children[i], + segments = stats[child.id].segments; + + for (var j = 0; j < segments.length; j++) { + var seg = segments[j]; + + if (seg.min === defaultMin) { + unspecifiedOrder.push(seg); + } else { + specifiedOrder.push(seg); + } + } + } + + specifiedOrder.sort(function(a, b) { + return a.min - b.min; + }); + + return specifiedOrder.concat(unspecifiedOrder); + } + + function executeNode(node, segmentNumber) { + if (node.children) { + return { + fn: function(done) { + nodeStart(node); + + queueRunnerFactory({ + onComplete: function() { + nodeComplete(node, node.getResult()); + done(); + }, + queueableFns: wrapChildren(node, segmentNumber), + userContext: node.sharedUserContext(), + onException: function() { + node.onException.apply(node, arguments); + } + }); + } + }; + } else { + return { + fn: function(done) { node.execute(done, stats[node.id].executable); } + }; + } + } + + function wrapChildren(node, segmentNumber) { + var result = [], + segmentChildren = stats[node.id].segments[segmentNumber].nodes; + + for (var i = 0; i < segmentChildren.length; i++) { + result.push(executeNode(segmentChildren[i].owner, segmentChildren[i].index)); + } + + if (!stats[node.id].executable) { + return result; + } + + return node.beforeAllFns.concat(result).concat(node.afterAllFns); + } + } + + return TreeProcessor; +}; + +getJasmineRequireObj().Any = function(j$) { + + function Any(expectedObject) { + if (typeof expectedObject === 'undefined') { + throw new TypeError( + 'jasmine.any() expects to be passed a constructor function. ' + + 'Please pass one or use jasmine.anything() to match any object.' + ); + } + this.expectedObject = expectedObject; + } + + Any.prototype.asymmetricMatch = function(other) { + if (this.expectedObject == String) { + return typeof other == 'string' || other instanceof String; + } + + if (this.expectedObject == Number) { + return typeof other == 'number' || other instanceof Number; + } + + if (this.expectedObject == Function) { + return typeof other == 'function' || other instanceof Function; + } + + if (this.expectedObject == Object) { + return typeof other == 'object'; + } + + if (this.expectedObject == Boolean) { + return typeof other == 'boolean'; + } + + return other instanceof this.expectedObject; + }; + + Any.prototype.jasmineToString = function() { + return ''; + }; + + return Any; +}; + +getJasmineRequireObj().Anything = function(j$) { + + function Anything() {} + + Anything.prototype.asymmetricMatch = function(other) { + return !j$.util.isUndefined(other) && other !== null; + }; + + Anything.prototype.jasmineToString = function() { + return ''; + }; + + return Anything; +}; + +getJasmineRequireObj().ArrayContaining = function(j$) { + function ArrayContaining(sample) { + this.sample = sample; + } + + ArrayContaining.prototype.asymmetricMatch = function(other) { + var className = Object.prototype.toString.call(this.sample); + if (className !== '[object Array]') { throw new Error('You must provide an array to arrayContaining, not \'' + this.sample + '\'.'); } + + for (var i = 0; i < this.sample.length; i++) { + var item = this.sample[i]; + if (!j$.matchersUtil.contains(other, item)) { + return false; + } + } + + return true; + }; + + ArrayContaining.prototype.jasmineToString = function () { + return ''; + }; + + return ArrayContaining; +}; + +getJasmineRequireObj().ObjectContaining = function(j$) { + + function ObjectContaining(sample) { + this.sample = sample; + } + + function getPrototype(obj) { + if (Object.getPrototypeOf) { + return Object.getPrototypeOf(obj); + } + + if (obj.constructor.prototype == obj) { + return null; + } + + return obj.constructor.prototype; + } + + function hasProperty(obj, property) { + if (!obj) { + return false; + } + + if (Object.prototype.hasOwnProperty.call(obj, property)) { + return true; + } + + return hasProperty(getPrototype(obj), property); + } + + ObjectContaining.prototype.asymmetricMatch = function(other) { + if (typeof(this.sample) !== 'object') { throw new Error('You must provide an object to objectContaining, not \''+this.sample+'\'.'); } + + for (var property in this.sample) { + if (!hasProperty(other, property) || + !j$.matchersUtil.equals(this.sample[property], other[property])) { + return false; + } + } + + return true; + }; + + ObjectContaining.prototype.jasmineToString = function() { + return ''; + }; + + return ObjectContaining; +}; + +getJasmineRequireObj().StringMatching = function(j$) { + + function StringMatching(expected) { + if (!j$.isString_(expected) && !j$.isA_('RegExp', expected)) { + throw new Error('Expected is not a String or a RegExp'); + } + + this.regexp = new RegExp(expected); + } + + StringMatching.prototype.asymmetricMatch = function(other) { + return this.regexp.test(other); + }; + + StringMatching.prototype.jasmineToString = function() { + return ''; + }; + + return StringMatching; +}; + +getJasmineRequireObj().errors = function() { + function ExpectationFailed() {} + + ExpectationFailed.prototype = new Error(); + ExpectationFailed.prototype.constructor = ExpectationFailed; + + return { + ExpectationFailed: ExpectationFailed + }; +}; +getJasmineRequireObj().formatErrorMsg = function() { + function generateErrorMsg(domain, usage) { + var usageDefinition = usage ? '\nUsage: ' + usage : ''; + + return function errorMsg(msg) { + return domain + ' : ' + msg + usageDefinition; + }; + } + + return generateErrorMsg; +}; + +getJasmineRequireObj().matchersUtil = function(j$) { + // TODO: what to do about jasmine.pp not being inject? move to JSON.stringify? gut PrettyPrinter? + + return { + equals: function(a, b, customTesters) { + customTesters = customTesters || []; + + return eq(a, b, [], [], customTesters); + }, + + contains: function(haystack, needle, customTesters) { + customTesters = customTesters || []; + + if ((Object.prototype.toString.apply(haystack) === '[object Array]') || + (!!haystack && !haystack.indexOf)) + { + for (var i = 0; i < haystack.length; i++) { + if (eq(haystack[i], needle, [], [], customTesters)) { + return true; + } + } + return false; + } + + return !!haystack && haystack.indexOf(needle) >= 0; + }, + + buildFailureMessage: function() { + var args = Array.prototype.slice.call(arguments, 0), + matcherName = args[0], + isNot = args[1], + actual = args[2], + expected = args.slice(3), + englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); + + var message = 'Expected ' + + j$.pp(actual) + + (isNot ? ' not ' : ' ') + + englishyPredicate; + + if (expected.length > 0) { + for (var i = 0; i < expected.length; i++) { + if (i > 0) { + message += ','; + } + message += ' ' + j$.pp(expected[i]); + } + } + + return message + '.'; + } + }; + + function isAsymmetric(obj) { + return obj && j$.isA_('Function', obj.asymmetricMatch); + } + + function asymmetricMatch(a, b) { + var asymmetricA = isAsymmetric(a), + asymmetricB = isAsymmetric(b); + + if (asymmetricA && asymmetricB) { + return undefined; + } + + if (asymmetricA) { + return a.asymmetricMatch(b); + } + + if (asymmetricB) { + return b.asymmetricMatch(a); + } + } + + // Equality function lovingly adapted from isEqual in + // [Underscore](http://underscorejs.org) + function eq(a, b, aStack, bStack, customTesters) { + var result = true; + + var asymmetricResult = asymmetricMatch(a, b); + if (!j$.util.isUndefined(asymmetricResult)) { + return asymmetricResult; + } + + for (var i = 0; i < customTesters.length; i++) { + var customTesterResult = customTesters[i](a, b); + if (!j$.util.isUndefined(customTesterResult)) { + return customTesterResult; + } + } + + if (a instanceof Error && b instanceof Error) { + return a.message == b.message; + } + + // Identical objects are equal. `0 === -0`, but they aren't identical. + // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + if (a === b) { return a !== 0 || 1 / a == 1 / b; } + // A strict comparison is necessary because `null == undefined`. + if (a === null || b === null) { return a === b; } + var className = Object.prototype.toString.call(a); + if (className != Object.prototype.toString.call(b)) { return false; } + switch (className) { + // Strings, numbers, dates, and booleans are compared by value. + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return a == String(b); + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for + // other numeric values. + return a != +a ? b != +b : (a === 0 ? 1 / a == 1 / b : a == +b); + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + return +a == +b; + // RegExps are compared by their source patterns and flags. + case '[object RegExp]': + return a.source == b.source && + a.global == b.global && + a.multiline == b.multiline && + a.ignoreCase == b.ignoreCase; + } + if (typeof a != 'object' || typeof b != 'object') { return false; } + + var aIsDomNode = j$.isDomNode(a); + var bIsDomNode = j$.isDomNode(b); + if (aIsDomNode && bIsDomNode) { + // At first try to use DOM3 method isEqualNode + if (a.isEqualNode) { + return a.isEqualNode(b); + } + // IE8 doesn't support isEqualNode, try to use outerHTML && innerText + var aIsElement = a instanceof Element; + var bIsElement = b instanceof Element; + if (aIsElement && bIsElement) { + return a.outerHTML == b.outerHTML; + } + if (aIsElement || bIsElement) { + return false; + } + return a.innerText == b.innerText && a.textContent == b.textContent; + } + if (aIsDomNode || bIsDomNode) { + return false; + } + + // Assume equality for cyclic structures. The algorithm for detecting cyclic + // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + if (aStack[length] == a) { return bStack[length] == b; } + } + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + var size = 0; + // Recursively compare objects and arrays. + // Compare array lengths to determine if a deep comparison is necessary. + if (className == '[object Array]') { + size = a.length; + if (size !== b.length) { + return false; + } + + while (size--) { + result = eq(a[size], b[size], aStack, bStack, customTesters); + if (!result) { + return false; + } + } + } else { + + // Objects with different constructors are not equivalent, but `Object`s + // or `Array`s from different frames are. + var aCtor = a.constructor, bCtor = b.constructor; + if (aCtor !== bCtor && !(isObjectConstructor(aCtor) && + isObjectConstructor(bCtor))) { + return false; + } + } + + // Deep compare objects. + var aKeys = keys(a, className == '[object Array]'), key; + size = aKeys.length; + + // Ensure that both objects contain the same number of properties before comparing deep equality. + if (keys(b, className == '[object Array]').length !== size) { return false; } + + while (size--) { + key = aKeys[size]; + // Deep compare each member + result = has(b, key) && eq(a[key], b[key], aStack, bStack, customTesters); + + if (!result) { + return false; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + + return result; + + function keys(obj, isArray) { + var allKeys = Object.keys ? Object.keys(obj) : + (function(o) { + var keys = []; + for (var key in o) { + if (has(o, key)) { + keys.push(key); + } + } + return keys; + })(obj); + + if (!isArray) { + return allKeys; + } + + var extraKeys = []; + if (allKeys.length === 0) { + return allKeys; + } + + for (var x = 0; x < allKeys.length; x++) { + if (!allKeys[x].match(/^[0-9]+$/)) { + extraKeys.push(allKeys[x]); + } + } + + return extraKeys; + } + } + + function has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + } + + function isFunction(obj) { + return typeof obj === 'function'; + } + + function isObjectConstructor(ctor) { + // aCtor instanceof aCtor is true for the Object and Function + // constructors (since a constructor is-a Function and a function is-a + // Object). We don't just compare ctor === Object because the constructor + // might come from a different frame with different globals. + return isFunction(ctor) && ctor instanceof ctor; + } +}; + +getJasmineRequireObj().toBe = function() { + function toBe() { + return { + compare: function(actual, expected) { + return { + pass: actual === expected + }; + } + }; + } + + return toBe; +}; + +getJasmineRequireObj().toBeCloseTo = function() { + + function toBeCloseTo() { + return { + compare: function(actual, expected, precision) { + if (precision !== 0) { + precision = precision || 2; + } + + return { + pass: Math.abs(expected - actual) < (Math.pow(10, -precision) / 2) + }; + } + }; + } + + return toBeCloseTo; +}; + +getJasmineRequireObj().toBeDefined = function() { + function toBeDefined() { + return { + compare: function(actual) { + return { + pass: (void 0 !== actual) + }; + } + }; + } + + return toBeDefined; +}; + +getJasmineRequireObj().toBeFalsy = function() { + function toBeFalsy() { + return { + compare: function(actual) { + return { + pass: !!!actual + }; + } + }; + } + + return toBeFalsy; +}; + +getJasmineRequireObj().toBeGreaterThan = function() { + + function toBeGreaterThan() { + return { + compare: function(actual, expected) { + return { + pass: actual > expected + }; + } + }; + } + + return toBeGreaterThan; +}; + + +getJasmineRequireObj().toBeGreaterThanOrEqual = function() { + + function toBeGreaterThanOrEqual() { + return { + compare: function(actual, expected) { + return { + pass: actual >= expected + }; + } + }; + } + + return toBeGreaterThanOrEqual; +}; + +getJasmineRequireObj().toBeLessThan = function() { + function toBeLessThan() { + return { + + compare: function(actual, expected) { + return { + pass: actual < expected + }; + } + }; + } + + return toBeLessThan; +}; +getJasmineRequireObj().toBeLessThanOrEqual = function() { + function toBeLessThanOrEqual() { + return { + + compare: function(actual, expected) { + return { + pass: actual <= expected + }; + } + }; + } + + return toBeLessThanOrEqual; +}; + +getJasmineRequireObj().toBeNaN = function(j$) { + + function toBeNaN() { + return { + compare: function(actual) { + var result = { + pass: (actual !== actual) + }; + + if (result.pass) { + result.message = 'Expected actual not to be NaN.'; + } else { + result.message = function() { return 'Expected ' + j$.pp(actual) + ' to be NaN.'; }; + } + + return result; + } + }; + } + + return toBeNaN; +}; + +getJasmineRequireObj().toBeNull = function() { + + function toBeNull() { + return { + compare: function(actual) { + return { + pass: actual === null + }; + } + }; + } + + return toBeNull; +}; + +getJasmineRequireObj().toBeTruthy = function() { + + function toBeTruthy() { + return { + compare: function(actual) { + return { + pass: !!actual + }; + } + }; + } + + return toBeTruthy; +}; + +getJasmineRequireObj().toBeUndefined = function() { + + function toBeUndefined() { + return { + compare: function(actual) { + return { + pass: void 0 === actual + }; + } + }; + } + + return toBeUndefined; +}; + +getJasmineRequireObj().toContain = function() { + function toContain(util, customEqualityTesters) { + customEqualityTesters = customEqualityTesters || []; + + return { + compare: function(actual, expected) { + + return { + pass: util.contains(actual, expected, customEqualityTesters) + }; + } + }; + } + + return toContain; +}; + +getJasmineRequireObj().toEqual = function() { + + function toEqual(util, customEqualityTesters) { + customEqualityTesters = customEqualityTesters || []; + + return { + compare: function(actual, expected) { + var result = { + pass: false + }; + + result.pass = util.equals(actual, expected, customEqualityTesters); + + return result; + } + }; + } + + return toEqual; +}; + +getJasmineRequireObj().toHaveBeenCalled = function(j$) { + + var getErrorMsg = j$.formatErrorMsg('', 'expect().toHaveBeenCalled()'); + + function toHaveBeenCalled() { + return { + compare: function(actual) { + var result = {}; + + if (!j$.isSpy(actual)) { + throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.')); + } + + if (arguments.length > 1) { + throw new Error(getErrorMsg('Does not take arguments, use toHaveBeenCalledWith')); + } + + result.pass = actual.calls.any(); + + result.message = result.pass ? + 'Expected spy ' + actual.and.identity() + ' not to have been called.' : + 'Expected spy ' + actual.and.identity() + ' to have been called.'; + + return result; + } + }; + } + + return toHaveBeenCalled; +}; + +getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) { + + var getErrorMsg = j$.formatErrorMsg('', 'expect().toHaveBeenCalledTimes()'); + + function toHaveBeenCalledTimes() { + return { + compare: function(actual, expected) { + if (!j$.isSpy(actual)) { + throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.')); + } + + var args = Array.prototype.slice.call(arguments, 0), + result = { pass: false }; + + if (!j$.isNumber_(expected)){ + throw new Error(getErrorMsg('The expected times failed is a required argument and must be a number.')); + } + + actual = args[0]; + var calls = actual.calls.count(); + var timesMessage = expected === 1 ? 'once' : expected + ' times'; + result.pass = calls === expected; + result.message = result.pass ? + 'Expected spy ' + actual.and.identity() + ' not to have been called ' + timesMessage + '. It was called ' + calls + ' times.' : + 'Expected spy ' + actual.and.identity() + ' to have been called ' + timesMessage + '. It was called ' + calls + ' times.'; + return result; + } + }; + } + + return toHaveBeenCalledTimes; +}; + +getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { + + var getErrorMsg = j$.formatErrorMsg('', 'expect().toHaveBeenCalledWith(...arguments)'); + + function toHaveBeenCalledWith(util, customEqualityTesters) { + return { + compare: function() { + var args = Array.prototype.slice.call(arguments, 0), + actual = args[0], + expectedArgs = args.slice(1), + result = { pass: false }; + + if (!j$.isSpy(actual)) { + throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.')); + } + + if (!actual.calls.any()) { + result.message = function() { return 'Expected spy ' + actual.and.identity() + ' to have been called with ' + j$.pp(expectedArgs) + ' but it was never called.'; }; + return result; + } + + if (util.contains(actual.calls.allArgs(), expectedArgs, customEqualityTesters)) { + result.pass = true; + result.message = function() { return 'Expected spy ' + actual.and.identity() + ' not to have been called with ' + j$.pp(expectedArgs) + ' but it was.'; }; + } else { + result.message = function() { return 'Expected spy ' + actual.and.identity() + ' to have been called with ' + j$.pp(expectedArgs) + ' but actual calls were ' + j$.pp(actual.calls.allArgs()).replace(/^\[ | \]$/g, '') + '.'; }; + } + + return result; + } + }; + } + + return toHaveBeenCalledWith; +}; + +getJasmineRequireObj().toMatch = function(j$) { + + var getErrorMsg = j$.formatErrorMsg('', 'expect().toMatch( || )'); + + function toMatch() { + return { + compare: function(actual, expected) { + if (!j$.isString_(expected) && !j$.isA_('RegExp', expected)) { + throw new Error(getErrorMsg('Expected is not a String or a RegExp')); + } + + var regexp = new RegExp(expected); + + return { + pass: regexp.test(actual) + }; + } + }; + } + + return toMatch; +}; + +getJasmineRequireObj().toThrow = function(j$) { + + var getErrorMsg = j$.formatErrorMsg('', 'expect(function() {}).toThrow()'); + + function toThrow(util) { + return { + compare: function(actual, expected) { + var result = { pass: false }, + threw = false, + thrown; + + if (typeof actual != 'function') { + throw new Error(getErrorMsg('Actual is not a Function')); + } + + try { + actual(); + } catch (e) { + threw = true; + thrown = e; + } + + if (!threw) { + result.message = 'Expected function to throw an exception.'; + return result; + } + + if (arguments.length == 1) { + result.pass = true; + result.message = function() { return 'Expected function not to throw, but it threw ' + j$.pp(thrown) + '.'; }; + + return result; + } + + if (util.equals(thrown, expected)) { + result.pass = true; + result.message = function() { return 'Expected function not to throw ' + j$.pp(expected) + '.'; }; + } else { + result.message = function() { return 'Expected function to throw ' + j$.pp(expected) + ', but it threw ' + j$.pp(thrown) + '.'; }; + } + + return result; + } + }; + } + + return toThrow; +}; + +getJasmineRequireObj().toThrowError = function(j$) { + + var getErrorMsg = j$.formatErrorMsg('', 'expect(function() {}).toThrowError(, )'); + + function toThrowError () { + return { + compare: function(actual) { + var threw = false, + pass = {pass: true}, + fail = {pass: false}, + thrown; + + if (typeof actual != 'function') { + throw new Error(getErrorMsg('Actual is not a Function')); + } + + var errorMatcher = getMatcher.apply(null, arguments); + + try { + actual(); + } catch (e) { + threw = true; + thrown = e; + } + + if (!threw) { + fail.message = 'Expected function to throw an Error.'; + return fail; + } + + if (!(thrown instanceof Error)) { + fail.message = function() { return 'Expected function to throw an Error, but it threw ' + j$.pp(thrown) + '.'; }; + return fail; + } + + if (errorMatcher.hasNoSpecifics()) { + pass.message = 'Expected function not to throw an Error, but it threw ' + j$.fnNameFor(thrown) + '.'; + return pass; + } + + if (errorMatcher.matches(thrown)) { + pass.message = function() { + return 'Expected function not to throw ' + errorMatcher.errorTypeDescription + errorMatcher.messageDescription() + '.'; + }; + return pass; + } else { + fail.message = function() { + return 'Expected function to throw ' + errorMatcher.errorTypeDescription + errorMatcher.messageDescription() + + ', but it threw ' + errorMatcher.thrownDescription(thrown) + '.'; + }; + return fail; + } + } + }; + + function getMatcher() { + var expected = null, + errorType = null; + + if (arguments.length == 2) { + expected = arguments[1]; + if (isAnErrorType(expected)) { + errorType = expected; + expected = null; + } + } else if (arguments.length > 2) { + errorType = arguments[1]; + expected = arguments[2]; + if (!isAnErrorType(errorType)) { + throw new Error(getErrorMsg('Expected error type is not an Error.')); + } + } + + if (expected && !isStringOrRegExp(expected)) { + if (errorType) { + throw new Error(getErrorMsg('Expected error message is not a string or RegExp.')); + } else { + throw new Error(getErrorMsg('Expected is not an Error, string, or RegExp.')); + } + } + + function messageMatch(message) { + if (typeof expected == 'string') { + return expected == message; + } else { + return expected.test(message); + } + } + + return { + errorTypeDescription: errorType ? j$.fnNameFor(errorType) : 'an exception', + thrownDescription: function(thrown) { + var thrownName = errorType ? j$.fnNameFor(thrown.constructor) : 'an exception', + thrownMessage = ''; + + if (expected) { + thrownMessage = ' with message ' + j$.pp(thrown.message); + } + + return thrownName + thrownMessage; + }, + messageDescription: function() { + if (expected === null) { + return ''; + } else if (expected instanceof RegExp) { + return ' with a message matching ' + j$.pp(expected); + } else { + return ' with message ' + j$.pp(expected); + } + }, + hasNoSpecifics: function() { + return expected === null && errorType === null; + }, + matches: function(error) { + return (errorType === null || error instanceof errorType) && + (expected === null || messageMatch(error.message)); + } + }; + } + + function isStringOrRegExp(potential) { + return potential instanceof RegExp || (typeof potential == 'string'); + } + + function isAnErrorType(type) { + if (typeof type !== 'function') { + return false; + } + + var Surrogate = function() {}; + Surrogate.prototype = type.prototype; + return (new Surrogate()) instanceof Error; + } + } + + return toThrowError; +}; + +getJasmineRequireObj().interface = function(jasmine, env) { + var jasmineInterface = { + describe: function(description, specDefinitions) { + return env.describe(description, specDefinitions); + }, + + xdescribe: function(description, specDefinitions) { + return env.xdescribe(description, specDefinitions); + }, + + fdescribe: function(description, specDefinitions) { + return env.fdescribe(description, specDefinitions); + }, + + it: function() { + return env.it.apply(env, arguments); + }, + + xit: function() { + return env.xit.apply(env, arguments); + }, + + fit: function() { + return env.fit.apply(env, arguments); + }, + + beforeEach: function() { + return env.beforeEach.apply(env, arguments); + }, + + afterEach: function() { + return env.afterEach.apply(env, arguments); + }, + + beforeAll: function() { + return env.beforeAll.apply(env, arguments); + }, + + afterAll: function() { + return env.afterAll.apply(env, arguments); + }, + + expect: function(actual) { + return env.expect(actual); + }, + + pending: function() { + return env.pending.apply(env, arguments); + }, + + fail: function() { + return env.fail.apply(env, arguments); + }, + + spyOn: function(obj, methodName) { + return env.spyOn(obj, methodName); + }, + + jsApiReporter: new jasmine.JsApiReporter({ + timer: new jasmine.Timer() + }), + + jasmine: jasmine + }; + + jasmine.addCustomEqualityTester = function(tester) { + env.addCustomEqualityTester(tester); + }; + + jasmine.addMatchers = function(matchers) { + return env.addMatchers(matchers); + }; + + jasmine.clock = function() { + return env.clock; + }; + + return jasmineInterface; +}; + +getJasmineRequireObj().version = function() { + return '2.5.2'; +}; diff --git a/tests/jasmine/jasmine_favicon.png b/tests/jasmine/jasmine_favicon.png new file mode 100644 index 0000000..3b84583 Binary files /dev/null and b/tests/jasmine/jasmine_favicon.png differ diff --git a/tests/plugins/attributes/src/assets/bitcoin.png b/tests/plugins/attributes/src/assets/bitcoin.png new file mode 100644 index 0000000..7018c83 Binary files /dev/null and b/tests/plugins/attributes/src/assets/bitcoin.png differ diff --git a/tests/plugins/attributes/src/index.html b/tests/plugins/attributes/src/index.html new file mode 100644 index 0000000..af99718 --- /dev/null +++ b/tests/plugins/attributes/src/index.html @@ -0,0 +1,37 @@ + + + + + X-Tag: Jasmine Spec Runner + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/plugins/attributes/src/spec.js b/tests/plugins/attributes/src/spec.js new file mode 100644 index 0000000..409fc66 --- /dev/null +++ b/tests/plugins/attributes/src/spec.js @@ -0,0 +1,27 @@ + + +describe("X-Tag's src extension should", function() { + + it("fetch the data from the provided value", function(done) { + + var component = xtag.create(class extends XTagElement.extensions('src') { + 'load::event'(event){ + this.innerHTML = event.detail; + expect(event).toBeDefined(); + done() + } + 'error::event'(event){ + expect(event).toBeDefined(); + done() + } + }); + + defineTestElement(component); + + node = new component(); + node.src = 'https://api.github.com'; + expect(node.src).toBe('https://api.github.com'); + + }, 10000); + +}); diff --git a/tests/plugins/rendering/hyperHTML/assets/bitcoin.png b/tests/plugins/rendering/hyperHTML/assets/bitcoin.png new file mode 100644 index 0000000..7018c83 Binary files /dev/null and b/tests/plugins/rendering/hyperHTML/assets/bitcoin.png differ diff --git a/tests/plugins/rendering/hyperHTML/index.html b/tests/plugins/rendering/hyperHTML/index.html new file mode 100644 index 0000000..c332989 --- /dev/null +++ b/tests/plugins/rendering/hyperHTML/index.html @@ -0,0 +1,38 @@ + + + + + X-Tag: Jasmine Spec Runner + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/plugins/rendering/hyperHTML/spec.js b/tests/plugins/rendering/hyperHTML/spec.js new file mode 100644 index 0000000..d162110 --- /dev/null +++ b/tests/plugins/rendering/hyperHTML/spec.js @@ -0,0 +1,72 @@ + +describe("The hyperHTML extension should", function() { + + it("render its content when loaded", function(done) { + + var count = 0; + var component = xtag.create(class extends XTagElement.extensions('hyper') { + '::hyper(ready)'(render){ + render(this)`

${this.foo}

`; + } + get foo (){ + return 'foo ' + count++; + } + bar (){ + return 'bar ' + count++; + } + }); + + defineTestElement(component); + + var node = new component(); + node.rxn('ready', function(){ + var first = node.firstElementChild; + var last = node.lastElementChild; + console.log(first.innerHTML); + expect(node.firstElementChild.textContent).toBe('foo 0'); + expect(node.lastElementChild.value).toBe('bar 1'); + node.render(); + expect(node.firstElementChild.textContent).toBe('foo 2'); + expect(node.lastElementChild.value).toBe('bar 3'); + expect(node.firstElementChild === first).toBe(true); + expect(node.lastElementChild === last).toBe(true); + done(); + }); + }); + + it("flush old nodes when rendering a new template", function(done) { + + var count = 0; + var component = xtag.create(class extends XTagElement.extensions('hyper') { + '::hyper(ready)'(render){ + render(this)`

${this.foo}

`; + } + 'second::hyper'(render){ + render(this)`

${this.foo}

`; + } + get foo (){ + return 'foo ' + count++; + } + bar (){ + return 'bar ' + count++; + } + }); + + defineTestElement(component); + + var node = new component(); + node.rxn('ready', function(){ + var first = node.firstElementChild; + var last = node.lastElementChild; + expect(node.firstElementChild.innerHTML).toBe('foo 0'); + expect(node.lastElementChild.value).toBe('bar 1'); + node.render('second'); + expect(node.firstElementChild.innerHTML).toBe('foo 2'); + expect(node.lastElementChild.value).toBe('bar 3'); + expect(node.firstElementChild === first).toBe(false); + expect(node.lastElementChild === last).toBe(false); + done(); + }); + }); + +}); diff --git a/tests/utils.js b/tests/utils.js new file mode 100644 index 0000000..12f22be --- /dev/null +++ b/tests/utils.js @@ -0,0 +1,13 @@ + +(function(){ + +var count = 0; + +defineTestElement = function(klass){ + var name = 'test-' + ++count; + var node = document.body.appendChild(document.createElement(name)); + xtag.register(name, klass); + return node; +} + +})(); \ No newline at end of file