target
stringlengths 5
300
| feat_repo_name
stringlengths 6
76
| text
stringlengths 26
1.05M
|
---|---|---|
public/home/address/jquery-1.8.3.min.js | PHPlistener/listener-project | /*! jQuery v1.8.3 jquery.com | jquery.org/license */
!function(e,t){function n(e){var t=he[e]={};return K.each(e.split(te),function(e,n){t[n]=!0}),t}function r(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(me,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:ge.test(r)?K.parseJSON(r):r}catch(o){}K.data(e,n,r)}else r=t}return r}function i(e){var t;for(t in e)if(("data"!==t||!K.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function o(){return!1}function a(){return!0}function s(e){return!e||!e.parentNode||11===e.parentNode.nodeType}function l(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function u(e,t,n){if(t=t||0,K.isFunction(t))return K.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return K.grep(e,function(e,r){return e===t===n});if("string"==typeof t){var r=K.grep(e,function(e){return 1===e.nodeType});if(_e.test(t))return K.filter(t,r,!n);t=K.filter(t,r)}return K.grep(e,function(e,r){return K.inArray(e,t)>=0===n})}function c(e){var t=We.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function f(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function p(e,t){if(1===t.nodeType&&K.hasData(e)){var n,r,i,o=K._data(e),a=K._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)K.event.add(t,n,s[n][r])}a.data&&(a.data=K.extend({},a.data))}}function d(e,t){var n;1===t.nodeType&&(t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),K.support.html5Clone&&e.innerHTML&&!K.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Je.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.selected=e.defaultSelected:"input"===n||"textarea"===n?t.defaultValue=e.defaultValue:"script"===n&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(K.expando))}function h(e){return"undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName("*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll("*"):[]}function g(e){Je.test(e.type)&&(e.defaultChecked=e.checked)}function m(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=yt.length;i--;)if(t=yt[i]+n,t in e)return t;return r}function y(e,t){return e=t||e,"none"===K.css(e,"display")||!K.contains(e.ownerDocument,e)}function v(e,t){for(var n,r,i=[],o=0,a=e.length;a>o;o++)n=e[o],n.style&&(i[o]=K._data(n,"olddisplay"),t?(!i[o]&&"none"===n.style.display&&(n.style.display=""),""===n.style.display&&y(n)&&(i[o]=K._data(n,"olddisplay",T(n.nodeName)))):(r=nt(n,"display"),!i[o]&&"none"!==r&&K._data(n,"olddisplay",r)));for(o=0;a>o;o++)n=e[o],n.style&&(t&&"none"!==n.style.display&&""!==n.style.display||(n.style.display=t?i[o]||"":"none"));return e}function b(e,t,n){var r=ct.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function x(e,t,n,r){for(var i=n===(r?"border":"content")?4:"width"===t?1:0,o=0;4>i;i+=2)"margin"===n&&(o+=K.css(e,n+mt[i],!0)),r?("content"===n&&(o-=parseFloat(nt(e,"padding"+mt[i]))||0),"margin"!==n&&(o-=parseFloat(nt(e,"border"+mt[i]+"Width"))||0)):(o+=parseFloat(nt(e,"padding"+mt[i]))||0,"padding"!==n&&(o+=parseFloat(nt(e,"border"+mt[i]+"Width"))||0));return o}function w(e,t,n){var r="width"===t?e.offsetWidth:e.offsetHeight,i=!0,o=K.support.boxSizing&&"border-box"===K.css(e,"boxSizing");if(0>=r||null==r){if(r=nt(e,t),(0>r||null==r)&&(r=e.style[t]),ft.test(r))return r;i=o&&(K.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+x(e,t,n||(o?"border":"content"),i)+"px"}function T(e){if(dt[e])return dt[e];var t=K("<"+e+">").appendTo(R.body),n=t.css("display");return t.remove(),("none"===n||""===n)&&(rt=R.body.appendChild(rt||K.extend(R.createElement("iframe"),{frameBorder:0,width:0,height:0})),it&&rt.createElement||(it=(rt.contentWindow||rt.contentDocument).document,it.write("<!doctype html><html><body>"),it.close()),t=it.body.appendChild(it.createElement(e)),n=nt(t,"display"),R.body.removeChild(rt)),dt[e]=n,n}function N(e,t,n,r){var i;if(K.isArray(t))K.each(t,function(t,i){n||xt.test(e)?r(e,i):N(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==K.type(t))r(e,t);else for(i in t)N(e+"["+i+"]",t[i],n,r)}function C(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i,o,a=t.toLowerCase().split(te),s=0,l=a.length;if(K.isFunction(n))for(;l>s;s++)r=a[s],o=/^\+/.test(r),o&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[o?"unshift":"push"](n)}}function k(e,n,r,i,o,a){o=o||n.dataTypes[0],a=a||{},a[o]=!0;for(var s,l=e[o],u=0,c=l?l.length:0,f=e===_t;c>u&&(f||!s);u++)s=l[u](n,r,i),"string"==typeof s&&(!f||a[s]?s=t:(n.dataTypes.unshift(s),s=k(e,n,r,i,s,a)));return(f||!s)&&!a["*"]&&(s=k(e,n,r,i,"*",a)),s}function E(e,n){var r,i,o=K.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((o[r]?e:i||(i={}))[r]=n[r]);i&&K.extend(!0,e,i)}function S(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes,c=e.responseFields;for(o in c)o in r&&(n[c[o]]=r[o]);for(;"*"===u[0];)u.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(o in l)if(l[o]&&l[o].test(i)){u.unshift(o);break}if(u[0]in r)a=u[0];else{for(o in r){if(!u[0]||e.converters[o+" "+u[0]]){a=o;break}s||(s=o)}a=a||s}return a?(a!==u[0]&&u.unshift(a),r[a]):void 0}function A(e,t){var n,r,i,o,a=e.dataTypes.slice(),s=a[0],l={},u=0;if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),a[1])for(n in e.converters)l[n.toLowerCase()]=e.converters[n];for(;i=a[++u];)if("*"!==i){if("*"!==s&&s!==i){if(n=l[s+" "+i]||l["* "+i],!n)for(r in l)if(o=r.split(" "),o[1]===i&&(n=l[s+" "+o[0]]||l["* "+o[0]])){n===!0?n=l[r]:l[r]!==!0&&(i=o[0],a.splice(u--,0,i));break}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(c){return{state:"parsererror",error:n?c:"No conversion from "+s+" to "+i}}}s=i}return{state:"success",data:t}}function j(){try{return new e.XMLHttpRequest}catch(t){}}function D(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function L(){return setTimeout(function(){Yt=t},0),Yt=K.now()}function H(e,t){K.each(t,function(t,n){for(var r=(Zt[t]||[]).concat(Zt["*"]),i=0,o=r.length;o>i;i++)if(r[i].call(e,t,n))return})}function F(e,t,n){var r,i=0,o=Kt.length,a=K.Deferred().always(function(){delete s.elem}),s=function(){for(var t=Yt||L(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,i=1-r,o=0,s=l.tweens.length;s>o;o++)l.tweens[o].run(i);return a.notifyWith(e,[l,i,n]),1>i&&s?n:(a.resolveWith(e,[l]),!1)},l=a.promise({elem:e,props:K.extend({},t),opts:K.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Yt||L(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=K.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(i),i},stop:function(t){for(var n=0,r=t?l.tweens.length:0;r>n;n++)l.tweens[n].run(1);return t?a.resolveWith(e,[l,t]):a.rejectWith(e,[l,t]),this}}),u=l.props;for(M(u,l.opts.specialEasing);o>i;i++)if(r=Kt[i].call(l,e,u,l.opts))return r;return H(l,u),K.isFunction(l.opts.start)&&l.opts.start.call(e,l),K.fx.timer(K.extend(s,{anim:l,queue:l.opts.queue,elem:e})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function M(e,t){var n,r,i,o,a;for(n in e)if(r=K.camelCase(n),i=t[r],o=e[n],K.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=K.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function O(e,t,n){var r,i,o,a,s,l,u,c,f,p=this,d=e.style,h={},g=[],m=e.nodeType&&y(e);n.queue||(c=K._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,f=c.empty.fire,c.empty.fire=function(){c.unqueued||f()}),c.unqueued++,p.always(function(){p.always(function(){c.unqueued--,K.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===K.css(e,"display")&&"none"===K.css(e,"float")&&(K.support.inlineBlockNeedsLayout&&"inline"!==T(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",K.support.shrinkWrapBlocks||p.done(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(r in t)if(o=t[r],Jt.exec(o)){if(delete t[r],l=l||"toggle"===o,o===(m?"hide":"show"))continue;g.push(r)}if(a=g.length){s=K._data(e,"fxshow")||K._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),l&&(s.hidden=!m),m?K(e).show():p.done(function(){K(e).hide()}),p.done(function(){var t;K.removeData(e,"fxshow",!0);for(t in h)K.style(e,t,h[t])});for(r=0;a>r;r++)i=g[r],u=p.createTween(i,m?s[i]:0),h[i]=s[i]||K.style(e,i),i in s||(s[i]=u.start,m&&(u.end=u.start,u.start="width"===i||"height"===i?1:0))}}function _(e,t,n,r,i){return new _.prototype.init(e,t,n,r,i)}function q(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=mt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function B(e){return K.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var W,P,R=e.document,$=e.location,I=e.navigator,z=e.jQuery,X=e.$,U=Array.prototype.push,Y=Array.prototype.slice,V=Array.prototype.indexOf,J=Object.prototype.toString,G=Object.prototype.hasOwnProperty,Q=String.prototype.trim,K=function(e,t){return new K.fn.init(e,t,W)},Z=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,ee=/\S/,te=/\s+/,ne=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,re=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,ie=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,oe=/^[\],:{}\s]*$/,ae=/(?:^|:|,)(?:\s*\[)+/g,se=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,le=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,ue=/^-ms-/,ce=/-([\da-z])/gi,fe=function(e,t){return(t+"").toUpperCase()},pe=function(){R.addEventListener?(R.removeEventListener("DOMContentLoaded",pe,!1),K.ready()):"complete"===R.readyState&&(R.detachEvent("onreadystatechange",pe),K.ready())},de={};K.fn=K.prototype={constructor:K,init:function(e,n,r){var i,o,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:re.exec(e),i&&(i[1]||!n)){if(i[1])return n=n instanceof K?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:R,e=K.parseHTML(i[1],a,!0),ie.test(i[1])&&K.isPlainObject(n)&&this.attr.call(e,n,!0),K.merge(this,e);if(o=R.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=R,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return K.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),K.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return Y.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=K.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,"find"===t?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return K.each(this,e,t)},ready:function(e){return K.ready.promise().done(e),this},eq:function(e){return e=+e,-1===e?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(Y.apply(this,arguments),"slice",Y.call(arguments).join(","))},map:function(e){return this.pushStack(K.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:U,sort:[].sort,splice:[].splice},K.fn.init.prototype=K.fn,K.extend=K.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"!=typeof s&&!K.isFunction(s)&&(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(e=arguments[l]))for(n in e)r=s[n],i=e[n],s!==i&&(c&&i&&(K.isPlainObject(i)||(o=K.isArray(i)))?(o?(o=!1,a=r&&K.isArray(r)?r:[]):a=r&&K.isPlainObject(r)?r:{},s[n]=K.extend(c,a,i)):i!==t&&(s[n]=i));return s},K.extend({noConflict:function(t){return e.$===K&&(e.$=X),t&&e.jQuery===K&&(e.jQuery=z),K},isReady:!1,readyWait:1,holdReady:function(e){e?K.readyWait++:K.ready(!0)},ready:function(e){if(e===!0?!--K.readyWait:!K.isReady){if(!R.body)return setTimeout(K.ready,1);K.isReady=!0,e!==!0&&--K.readyWait>0||(P.resolveWith(R,[K]),K.fn.trigger&&K(R).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===K.type(e)},isArray:Array.isArray||function(e){return"array"===K.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?String(e):de[J.call(e)]||"object"},isPlainObject:function(e){if(!e||"object"!==K.type(e)||e.nodeType||K.isWindow(e))return!1;try{if(e.constructor&&!G.call(e,"constructor")&&!G.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||G.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return e&&"string"==typeof e?("boolean"==typeof t&&(n=t,t=0),t=t||R,(r=ie.exec(e))?[t.createElement(r[1])]:(r=K.buildFragment([e],t,n?null:[]),K.merge([],(r.cacheable?K.clone(r.fragment):r.fragment).childNodes))):null},parseJSON:function(t){return t&&"string"==typeof t?(t=K.trim(t),e.JSON&&e.JSON.parse?e.JSON.parse(t):oe.test(t.replace(se,"@").replace(le,"]").replace(ae,""))?new Function("return "+t)():void K.error("Invalid JSON: "+t)):null},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&K.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&ee.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(ue,"ms-").replace(ce,fe)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,o=0,a=e.length,s=a===t||K.isFunction(e);if(r)if(s){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;a>o&&n.apply(e[o++],r)!==!1;);else if(s){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;a>o&&n.call(e[o],o,e[o++])!==!1;);return e},trim:Q&&!Q.call("\ufeff ")?function(e){return null==e?"":Q.call(e)}:function(e){return null==e?"":(e+"").replace(ne,"")},makeArray:function(e,t){var n,r=t||[];return null!=e&&(n=K.type(e),null==e.length||"string"===n||"function"===n||"regexp"===n||K.isWindow(e)?U.call(r,e):K.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(V)return V.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else for(;n[o]!==t;)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,n,r){var i,o,a=[],s=0,l=e.length,u=e instanceof K||l!==t&&"number"==typeof l&&(l>0&&e[0]&&e[l-1]||0===l||K.isArray(e));if(u)for(;l>s;s++)i=n(e[s],s,r),null!=i&&(a[a.length]=i);else for(o in e)i=n(e[o],o,r),null!=i&&(a[a.length]=i);return a.concat.apply([],a)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(r=e[n],n=e,e=r),K.isFunction(e)?(i=Y.call(arguments,2),o=function(){return e.apply(n,i.concat(Y.call(arguments)))},o.guid=e.guid=e.guid||K.guid++,o):t},access:function(e,n,r,i,o,a,s){var l,u=null==r,c=0,f=e.length;if(r&&"object"==typeof r){for(c in r)K.access(e,n,c,r[c],1,a,i);o=1}else if(i!==t){if(l=s===t&&K.isFunction(i),u&&(l?(l=n,n=function(e,t,n){return l.call(K(e),n)}):(n.call(e,i),n=null)),n)for(;f>c;c++)n(e[c],r,l?i.call(e[c],c,n(e[c],r)):i,s);o=1}return o?e:u?n.call(e):f?n(e[0],r):a},now:function(){return(new Date).getTime()}}),K.ready.promise=function(t){if(!P)if(P=K.Deferred(),"complete"===R.readyState)setTimeout(K.ready,1);else if(R.addEventListener)R.addEventListener("DOMContentLoaded",pe,!1),e.addEventListener("load",K.ready,!1);else{R.attachEvent("onreadystatechange",pe),e.attachEvent("onload",K.ready);var n=!1;try{n=null==e.frameElement&&R.documentElement}catch(r){}n&&n.doScroll&&function i(){if(!K.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}K.ready()}}()}return P.promise(t)},K.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){de["[object "+t+"]"]=t.toLowerCase()}),W=K(R);var he={};K.Callbacks=function(e){e="string"==typeof e?he[e]||n(e):K.extend({},e);var r,i,o,a,s,l,u=[],c=!e.once&&[],f=function(t){for(r=e.memory&&t,i=!0,l=a||0,a=0,s=u.length,o=!0;u&&s>l;l++)if(u[l].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}o=!1,u&&(c?c.length&&f(c.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;!function n(t){K.each(t,function(t,r){var i=K.type(r);"function"===i?(!e.unique||!p.has(r))&&u.push(r):r&&r.length&&"string"!==i&&n(r)})}(arguments),o?s=u.length:r&&(a=t,f(r))}return this},remove:function(){return u&&K.each(arguments,function(e,t){for(var n;(n=K.inArray(t,u,n))>-1;)u.splice(n,1),o&&(s>=n&&s--,l>=n&&l--)}),this},has:function(e){return K.inArray(e,u)>-1},empty:function(){return u=[],this},disable:function(){return u=c=r=t,this},disabled:function(){return!u},lock:function(){return c=t,r||p.disable(),this},locked:function(){return!c},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],u&&(!i||c)&&(o?c.push(t):f(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},K.extend({Deferred:function(e){var t=[["resolve","done",K.Callbacks("once memory"),"resolved"],["reject","fail",K.Callbacks("once memory"),"rejected"],["notify","progress",K.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return K.Deferred(function(n){K.each(t,function(t,r){var o=r[0],a=e[t];i[r[1]](K.isFunction(a)?function(){var e=a.apply(this,arguments);e&&K.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o+"With"](this===i?n:this,[e])}:n[o])}),e=null}).promise()},promise:function(e){return null!=e?K.extend(e,r):r}},i={};return r.pipe=r.then,K.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=a.fire,i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=Y.call(arguments),a=o.length,s=1!==a||e&&K.isFunction(e.promise)?a:0,l=1===s?e:K.Deferred(),u=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?Y.call(arguments):i,r===t?l.notifyWith(n,r):--s||l.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&K.isFunction(o[i].promise)?o[i].promise().done(u(i,r,o)).fail(l.reject).progress(u(i,n,t)):--s;return s||l.resolveWith(r,o),l.promise()}}),K.support=function(){var t,n,r,i,o,a,s,l,u,c,f,p=R.createElement("div");if(p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0],!n||!r||!n.length)return{};i=R.createElement("select"),o=i.appendChild(R.createElement("option")),a=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:3===p.firstChild.nodeType,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:"on"===a.value,optSelected:o.selected,getSetAttribute:"t"!==p.className,enctype:!!R.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==R.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===R.compatMode,submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,i.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}if(!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",f=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",f)),a=R.createElement("input"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","checked"),a.setAttribute("name","t"),p.appendChild(a),s=R.createDocumentFragment(),s.appendChild(p.lastChild),t.checkClone=s.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=a.checked,s.removeChild(a),s.appendChild(p),p.attachEvent)for(u in{submit:!0,change:!0,focusin:!0})l="on"+u,c=l in p,c||(p.setAttribute(l,"return;"),c="function"==typeof p[l]),t[u+"Bubbles"]=c;return K(function(){var n,r,i,o,a="padding:0;margin:0;border:0;display:block;overflow:hidden;",s=R.getElementsByTagName("body")[0];s&&(n=R.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",s.insertBefore(n,s.firstChild),r=R.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=r.getElementsByTagName("td"),i[0].style.cssText="padding:0;margin:0;border:0;display:none",c=0===i[0].offsetHeight,i[0].style.display="",i[1].style.display="none",t.reliableHiddenOffsets=c&&0===i[0].offsetHeight,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===r.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==s.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(r,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(r,null)||{width:"4px"}).width,o=R.createElement("div"),o.style.cssText=r.style.cssText=a,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),"undefined"!=typeof r.style.zoom&&(r.innerHTML="",r.style.cssText=a+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===r.offsetWidth,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==r.offsetWidth,n.style.zoom=1),s.removeChild(n),n=r=i=o=null)}),s.removeChild(p),n=r=i=o=a=s=p=null,t}();var ge=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,me=/([A-Z])/g;K.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(K.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?K.cache[e[K.expando]]:e[K.expando],!!e&&!i(e)},data:function(e,n,r,i){if(K.acceptData(e)){var o,a,s=K.expando,l="string"==typeof n,u=e.nodeType,c=u?K.cache:e,f=u?e[s]:e[s]&&s;if(f&&c[f]&&(i||c[f].data)||!l||r!==t)return f||(u?e[s]=f=K.deletedIds.pop()||K.guid++:f=s),c[f]||(c[f]={},u||(c[f].toJSON=K.noop)),("object"==typeof n||"function"==typeof n)&&(i?c[f]=K.extend(c[f],n):c[f].data=K.extend(c[f].data,n)),o=c[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[K.camelCase(n)]=r),l?(a=o[n],null==a&&(a=o[K.camelCase(n)])):a=o,a}},removeData:function(e,t,n){if(K.acceptData(e)){var r,o,a,s=e.nodeType,l=s?K.cache:e,u=s?e[K.expando]:K.expando;if(l[u]){if(t&&(r=n?l[u]:l[u].data)){K.isArray(t)||(t in r?t=[t]:(t=K.camelCase(t),t=t in r?[t]:t.split(" ")));for(o=0,a=t.length;a>o;o++)delete r[t[o]];if(!(n?i:K.isEmptyObject)(r))return}(n||(delete l[u].data,i(l[u])))&&(s?K.cleanData([e],!0):K.support.deleteExpando||l!=l.window?delete l[u]:l[u]=null)}}},_data:function(e,t,n){return K.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&K.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),K.fn.extend({data:function(e,n){var i,o,a,s,l,u=this[0],c=0,f=null;if(e===t){if(this.length&&(f=K.data(u),1===u.nodeType&&!K._data(u,"parsedAttrs"))){for(a=u.attributes,l=a.length;l>c;c++)s=a[c].name,s.indexOf("data-")||(s=K.camelCase(s.substring(5)),r(u,s,f[s]));K._data(u,"parsedAttrs",!0)}return f}return"object"==typeof e?this.each(function(){K.data(this,e)}):(i=e.split(".",2),i[1]=i[1]?"."+i[1]:"",o=i[1]+"!",K.access(this,function(n){return n===t?(f=this.triggerHandler("getData"+o,[i[0]]),f===t&&u&&(f=K.data(u,e),f=r(u,e,f)),f===t&&i[1]?this.data(i[0]):f):(i[1]=n,void this.each(function(){var t=K(this);t.triggerHandler("setData"+o,i),K.data(this,e,n),t.triggerHandler("changeData"+o,i)}))},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){K.removeData(this,e)})}}),K.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=K._data(e,t),n&&(!r||K.isArray(n)?r=K._data(e,t,K.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=K.queue(e,t),r=n.length,i=n.shift(),o=K._queueHooks(e,t),a=function(){K.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return K._data(e,n)||K._data(e,n,{empty:K.Callbacks("once memory").add(function(){K.removeData(e,t+"queue",!0),K.removeData(e,n,!0)})})}}),K.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),arguments.length<r?K.queue(this[0],e):n===t?this:this.each(function(){var t=K.queue(this,e,n);K._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&K.dequeue(this,e)})},dequeue:function(e){return this.each(function(){K.dequeue(this,e)})},delay:function(e,t){return e=K.fx?K.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=K.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};for("string"!=typeof e&&(n=e,e=t),e=e||"fx";s--;)r=K._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var ye,ve,be,xe=/[\t\r\n]/g,we=/\r/g,Te=/^(?:button|input)$/i,Ne=/^(?:button|input|object|select|textarea)$/i,Ce=/^a(?:rea|)$/i,ke=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,Ee=K.support.getSetAttribute;K.fn.extend({attr:function(e,t){return K.access(this,K.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){K.removeAttr(this,e)})},prop:function(e,t){return K.access(this,K.prop,e,t,arguments.length>1)},removeProp:function(e){return e=K.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a,s;if(K.isFunction(e))return this.each(function(t){K(this).addClass(e.call(this,t,this.className))});if(e&&"string"==typeof e)for(t=e.split(te),n=0,r=this.length;r>n;n++)if(i=this[n],1===i.nodeType)if(i.className||1!==t.length){for(o=" "+i.className+" ",a=0,s=t.length;s>a;a++)o.indexOf(" "+t[a]+" ")<0&&(o+=t[a]+" ");i.className=K.trim(o)}else i.className=e;return this},removeClass:function(e){var n,r,i,o,a,s,l;if(K.isFunction(e))return this.each(function(t){K(this).removeClass(e.call(this,t,this.className))});if(e&&"string"==typeof e||e===t)for(n=(e||"").split(te),s=0,l=this.length;l>s;s++)if(i=this[s],1===i.nodeType&&i.className){for(r=(" "+i.className+" ").replace(xe," "),o=0,a=n.length;a>o;o++)for(;r.indexOf(" "+n[o]+" ")>=0;)r=r.replace(" "+n[o]+" "," ");i.className=e?K.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return K.isFunction(e)?this.each(function(n){K(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n)for(var i,o=0,a=K(this),s=t,l=e.split(te);i=l[o++];)s=r?s:!a.hasClass(i),a[s?"addClass":"removeClass"](i);else("undefined"===n||"boolean"===n)&&(this.className&&K._data(this,"__className__",this.className),this.className=this.className||e===!1?"":K._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(xe," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=K.isFunction(e),this.each(function(r){var o,a=K(this);1===this.nodeType&&(o=i?e.call(this,r,a.val()):e,null==o?o="":"number"==typeof o?o+="":K.isArray(o)&&(o=K.map(o,function(e){return null==e?"":e+""})),n=K.valHooks[this.type]||K.valHooks[this.nodeName.toLowerCase()],n&&"set"in n&&n.set(this,o,"value")!==t||(this.value=o))});if(o)return n=K.valHooks[o.type]||K.valHooks[o.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(o,"value"))!==t?r:(r=o.value,"string"==typeof r?r.replace(we,""):null==r?"":r)}}}),K.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;s>l;l++)if(n=r[l],(n.selected||l===i)&&(K.support.optDisabled?!n.disabled:null===n.getAttribute("disabled"))&&(!n.parentNode.disabled||!K.nodeName(n.parentNode,"optgroup"))){if(t=K(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=K.makeArray(t);return K(e).find("option").each(function(){this.selected=K.inArray(K(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var o,a,s,l=e.nodeType;if(e&&3!==l&&8!==l&&2!==l)return i&&K.isFunction(K.fn[n])?K(e)[n](r):"undefined"==typeof e.getAttribute?K.prop(e,n,r):(s=1!==l||!K.isXMLDoc(e),s&&(n=n.toLowerCase(),a=K.attrHooks[n]||(ke.test(n)?ve:ye)),r!==t?null===r?void K.removeAttr(e,n):a&&"set"in a&&s&&(o=a.set(e,r,n))!==t?o:(e.setAttribute(n,r+""),r):a&&"get"in a&&s&&null!==(o=a.get(e,n))?o:(o=e.getAttribute(n),null===o?t:o))},removeAttr:function(e,t){var n,r,i,o,a=0;if(t&&1===e.nodeType)for(r=t.split(te);a<r.length;a++)i=r[a],i&&(n=K.propFix[i]||i,o=ke.test(i),o||K.attr(e,i,""),e.removeAttribute(Ee?i:n),o&&n in e&&(e[n]=!1))},attrHooks:{type:{set:function(e,t){if(Te.test(e.nodeName)&&e.parentNode)K.error("type property can't be changed");else if(!K.support.radioValue&&"radio"===t&&K.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return ye&&K.nodeName(e,"button")?ye.get(e,t):t in e?e.value:null},set:function(e,t,n){return ye&&K.nodeName(e,"button")?ye.set(e,t,n):void(e.value=t)}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!K.isXMLDoc(e),a&&(n=K.propFix[n]||n,o=K.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):Ne.test(e.nodeName)||Ce.test(e.nodeName)&&e.href?0:t}}}}),ve={get:function(e,n){var r,i=K.prop(e,n);return i===!0||"boolean"!=typeof i&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?K.removeAttr(e,n):(r=K.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},Ee||(be={name:!0,id:!0,coords:!0},ye=K.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(be[n]?""!==r.value:r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=R.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},K.each(["width","height"],function(e,t){K.attrHooks[t]=K.extend(K.attrHooks[t],{
set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}})}),K.attrHooks.contenteditable={get:ye.get,set:function(e,t,n){""===t&&(t="false"),ye.set(e,t,n)}}),K.support.hrefNormalized||K.each(["href","src","width","height"],function(e,n){K.attrHooks[n]=K.extend(K.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null===r?t:r}})}),K.support.style||(K.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),K.support.optSelected||(K.propHooks.selected=K.extend(K.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),K.support.enctype||(K.propFix.enctype="encoding"),K.support.checkOn||K.each(["radio","checkbox"],function(){K.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),K.each(["radio","checkbox"],function(){K.valHooks[this]=K.extend(K.valHooks[this],{set:function(e,t){return K.isArray(t)?e.checked=K.inArray(K(e).val(),t)>=0:void 0}})});var Se=/^(?:textarea|input|select)$/i,Ae=/^([^\.]*|)(?:\.(.+)|)$/,je=/(?:^|\s)hover(\.\S+|)\b/,De=/^key/,Le=/^(?:mouse|contextmenu)|click/,He=/^(?:focusinfocus|focusoutblur)$/,Fe=function(e){return K.event.special.hover?e:e.replace(je,"mouseenter$1 mouseleave$1")};K.event={add:function(e,n,r,i,o){var a,s,l,u,c,f,p,d,h,g,m;if(3!==e.nodeType&&8!==e.nodeType&&n&&r&&(a=K._data(e))){for(r.handler&&(h=r,r=h.handler,o=h.selector),r.guid||(r.guid=K.guid++),l=a.events,l||(a.events=l={}),s=a.handle,s||(a.handle=s=function(e){return"undefined"==typeof K||e&&K.event.triggered===e.type?t:K.event.dispatch.apply(s.elem,arguments)},s.elem=e),n=K.trim(Fe(n)).split(" "),u=0;u<n.length;u++)c=Ae.exec(n[u])||[],f=c[1],p=(c[2]||"").split(".").sort(),m=K.event.special[f]||{},f=(o?m.delegateType:m.bindType)||f,m=K.event.special[f]||{},d=K.extend({type:f,origType:c[1],data:i,handler:r,guid:r.guid,selector:o,needsContext:o&&K.expr.match.needsContext.test(o),namespace:p.join(".")},h),g=l[f],g||(g=l[f]=[],g.delegateCount=0,m.setup&&m.setup.call(e,i,p,s)!==!1||(e.addEventListener?e.addEventListener(f,s,!1):e.attachEvent&&e.attachEvent("on"+f,s))),m.add&&(m.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),o?g.splice(g.delegateCount++,0,d):g.push(d),K.event.global[f]=!0;e=null}},global:{},remove:function(e,t,n,r,i){var o,a,s,l,u,c,f,p,d,h,g,m=K.hasData(e)&&K._data(e);if(m&&(p=m.events)){for(t=K.trim(Fe(t||"")).split(" "),o=0;o<t.length;o++)if(a=Ae.exec(t[o])||[],s=l=a[1],u=a[2],s){for(d=K.event.special[s]||{},s=(r?d.delegateType:d.bindType)||s,h=p[s]||[],c=h.length,u=u?new RegExp("(^|\\.)"+u.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null,f=0;f<h.length;f++)g=h[f],(i||l===g.origType)&&(!n||n.guid===g.guid)&&(!u||u.test(g.namespace))&&(!r||r===g.selector||"**"===r&&g.selector)&&(h.splice(f--,1),g.selector&&h.delegateCount--,d.remove&&d.remove.call(e,g));0===h.length&&c!==h.length&&((!d.teardown||d.teardown.call(e,u,m.handle)===!1)&&K.removeEvent(e,s,m.handle),delete p[s])}else for(s in p)K.event.remove(e,s+t[o],n,r,!0);K.isEmptyObject(p)&&(delete m.handle,K.removeData(e,"events",!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,i,o){if(!i||3!==i.nodeType&&8!==i.nodeType){var a,s,l,u,c,f,p,d,h,g,m=n.type||n,y=[];if(He.test(m+K.event.triggered))return;if(m.indexOf("!")>=0&&(m=m.slice(0,-1),s=!0),m.indexOf(".")>=0&&(y=m.split("."),m=y.shift(),y.sort()),(!i||K.event.customEvent[m])&&!K.event.global[m])return;if(n="object"==typeof n?n[K.expando]?n:new K.Event(m,n):new K.Event(m),n.type=m,n.isTrigger=!0,n.exclusive=s,n.namespace=y.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+y.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,f=m.indexOf(":")<0?"on"+m:"",!i){a=K.cache;for(l in a)a[l].events&&a[l].events[m]&&K.event.trigger(n,r,a[l].handle.elem,!0);return}if(n.result=t,n.target||(n.target=i),r=null!=r?K.makeArray(r):[],r.unshift(n),p=K.event.special[m]||{},p.trigger&&p.trigger.apply(i,r)===!1)return;if(h=[[i,p.bindType||m]],!o&&!p.noBubble&&!K.isWindow(i)){for(g=p.delegateType||m,u=He.test(g+m)?i:i.parentNode,c=i;u;u=u.parentNode)h.push([u,g]),c=u;c===(i.ownerDocument||R)&&h.push([c.defaultView||c.parentWindow||e,g])}for(l=0;l<h.length&&!n.isPropagationStopped();l++)u=h[l][0],n.type=h[l][1],d=(K._data(u,"events")||{})[n.type]&&K._data(u,"handle"),d&&d.apply(u,r),d=f&&u[f],d&&K.acceptData(u)&&d.apply&&d.apply(u,r)===!1&&n.preventDefault();return n.type=m,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(i.ownerDocument,r)===!1)&&("click"!==m||!K.nodeName(i,"a"))&&K.acceptData(i)&&f&&i[m]&&("focus"!==m&&"blur"!==m||0!==n.target.offsetWidth)&&!K.isWindow(i)&&(c=i[f],c&&(i[f]=null),K.event.triggered=m,i[m](),K.event.triggered=t,c&&(i[f]=c)),n.result}},dispatch:function(n){n=K.event.fix(n||e.event);var r,i,o,a,s,l,u,c,f,p=(K._data(this,"events")||{})[n.type]||[],d=p.delegateCount,h=Y.call(arguments),g=!n.exclusive&&!n.namespace,m=K.event.special[n.type]||{},y=[];if(h[0]=n,n.delegateTarget=this,!m.preDispatch||m.preDispatch.call(this,n)!==!1){if(d&&(!n.button||"click"!==n.type))for(o=n.target;o!=this;o=o.parentNode||this)if(o.disabled!==!0||"click"!==n.type){for(s={},u=[],r=0;d>r;r++)c=p[r],f=c.selector,s[f]===t&&(s[f]=c.needsContext?K(f,this).index(o)>=0:K.find(f,this,null,[o]).length),s[f]&&u.push(c);u.length&&y.push({elem:o,matches:u})}for(p.length>d&&y.push({elem:this,matches:p.slice(d)}),r=0;r<y.length&&!n.isPropagationStopped();r++)for(l=y[r],n.currentTarget=l.elem,i=0;i<l.matches.length&&!n.isImmediatePropagationStopped();i++)c=l.matches[i],(g||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))&&(n.data=c.data,n.handleObj=c,a=((K.event.special[c.origType]||{}).handle||c.handler).apply(l.elem,h),a!==t&&(n.result=a,a===!1&&(n.preventDefault(),n.stopPropagation())));return m.postDispatch&&m.postDispatch.call(this,n),n.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,a=n.button,s=n.fromElement;return null==e.pageX&&null!=n.clientX&&(r=e.target.ownerDocument||R,i=r.documentElement,o=r.body,e.pageX=n.clientX+(i&&i.scrollLeft||o&&o.scrollLeft||0)-(i&&i.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(i&&i.scrollTop||o&&o.scrollTop||0)-(i&&i.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?n.toElement:s),!e.which&&a!==t&&(e.which=1&a?1:2&a?3:4&a?2:0),e}},fix:function(e){if(e[K.expando])return e;var t,n,r=e,i=K.event.fixHooks[e.type]||{},o=i.props?this.props.concat(i.props):this.props;for(e=K.Event(r),t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||R),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,i.filter?i.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){K.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=K.extend(new K.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?K.event.trigger(i,null,t):K.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},K.event.handle=K.event.dispatch,K.removeEvent=R.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&("undefined"==typeof e[r]&&(e[r]=null),e.detachEvent(r,n))},K.Event=function(e,t){return this instanceof K.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?a:o):this.type=e,t&&K.extend(this,t),this.timeStamp=e&&e.timeStamp||K.now(),this[K.expando]=!0,void 0):new K.Event(e,t)},K.Event.prototype={preventDefault:function(){this.isDefaultPrevented=a;var e=this.originalEvent;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=a;var e=this.originalEvent;e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=a,this.stopPropagation()},isDefaultPrevented:o,isPropagationStopped:o,isImmediatePropagationStopped:o},K.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){K.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;o.selector;return(!i||i!==r&&!K.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),K.support.submitBubbles||(K.event.special.submit={setup:function(){return K.nodeName(this,"form")?!1:void K.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=K.nodeName(n,"input")||K.nodeName(n,"button")?n.form:t;r&&!K._data(r,"_submit_attached")&&(K.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),K._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&K.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return K.nodeName(this,"form")?!1:void K.event.remove(this,"._submit")}}),K.support.changeBubbles||(K.event.special.change={setup:function(){return Se.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(K.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),K.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),K.event.simulate("change",this,e,!0)})),!1):void K.event.add(this,"beforeactivate._change",function(e){var t=e.target;Se.test(t.nodeName)&&!K._data(t,"_change_attached")&&(K.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&K.event.simulate("change",this.parentNode,e,!0)}),K._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return K.event.remove(this,"._change"),!Se.test(this.nodeName)}}),K.support.focusinBubbles||K.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){K.event.simulate(t,e.target,K.event.fix(e),!0)};K.event.special[t]={setup:function(){0===n++&&R.addEventListener(e,r,!0)},teardown:function(){0===--n&&R.removeEventListener(e,r,!0)}}}),K.fn.extend({on:function(e,n,r,i,a){var s,l;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(l in e)this.on(l,n,r,e[l],a);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=o;else if(!i)return this;return 1===a&&(s=i,i=function(e){return K().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=K.guid++)),this.each(function(){K.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,a;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,K(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(a in e)this.off(a,n,e[a]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=o),this.each(function(){K.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return K(this.context).on(e,this.selector,t,n),this},die:function(e,t){return K(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){K.event.trigger(e,t,this)})},triggerHandler:function(e,t){return this[0]?K.event.trigger(e,t,this[0],!0):void 0},toggle:function(e){var t=arguments,n=e.guid||K.guid++,r=0,i=function(n){var i=(K._data(this,"lastToggle"+e.guid)||0)%r;return K._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};for(i.guid=n;r<t.length;)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),K.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){K.fn[t]=function(e,n){return null==n&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},De.test(t)&&(K.event.fixHooks[t]=K.event.keyHooks),Le.test(t)&&(K.event.fixHooks[t]=K.event.mouseHooks)}),function(e,t){function n(e,t,n,r){n=n||[],t=t||L;var i,o,a,s,l=t.nodeType;if(!e||"string"!=typeof e)return n;if(1!==l&&9!==l)return[];if(a=w(t),!a&&!r&&(i=ne.exec(e)))if(s=i[1]){if(9===l){if(o=t.getElementById(s),!o||!o.parentNode)return n;if(o.id===s)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&T(t,o)&&o.id===s)return n.push(o),n}else{if(i[2])return _.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((s=i[3])&&pe&&t.getElementsByClassName)return _.apply(n,q.call(t.getElementsByClassName(s),0)),n}return g(e.replace(Q,"$1"),t,n,r,a)}function r(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function i(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function o(e){return W(function(t){return t=+t,W(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function a(e,t,n){if(e===t)return n;for(var r=e.nextSibling;r;){if(r===t)return-1;r=r.nextSibling}return 1}function s(e,t){var r,i,o,a,s,l,u,c=$[j][e+" "];if(c)return t?0:c.slice(0);for(s=e,l=[],u=b.preFilter;s;){(!r||(i=Z.exec(s)))&&(i&&(s=s.slice(i[0].length)||s),l.push(o=[])),r=!1,(i=ee.exec(s))&&(o.push(r=new D(i.shift())),s=s.slice(r.length),r.type=i[0].replace(Q," "));for(a in b.filter)(i=se[a].exec(s))&&(!u[a]||(i=u[a](i)))&&(o.push(r=new D(i.shift())),s=s.slice(r.length),r.type=a,r.matches=i);if(!r)break}return t?s.length:s?n.error(e):$(e,l).slice(0)}function l(e,t,n){var r=t.dir,i=n&&"parentNode"===t.dir,o=M++;return t.first?function(t,n,o){for(;t=t[r];)if(i||1===t.nodeType)return e(t,n,o)}:function(t,n,a){if(a){for(;t=t[r];)if((i||1===t.nodeType)&&e(t,n,a))return t}else for(var s,l=F+" "+o+" ",u=l+y;t=t[r];)if(i||1===t.nodeType){if((s=t[j])===u)return t.sizset;if("string"==typeof s&&0===s.indexOf(l)){if(t.sizset)return t}else{if(t[j]=u,e(t,n,a))return t.sizset=!0,t;t.sizset=!1}}}}function u(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function c(e,t,n,r,i){for(var o,a=[],s=0,l=e.length,u=null!=t;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function f(e,t,n,r,i,o){return r&&!r[j]&&(r=f(r)),i&&!i[j]&&(i=f(i,o)),W(function(o,a,s,l){var u,f,p,d=[],g=[],m=a.length,y=o||h(t||"*",s.nodeType?[s]:s,[]),v=!e||!o&&t?y:c(y,d,e,s,l),b=n?i||(o?e:m||r)?[]:a:v;if(n&&n(v,b,s,l),r)for(u=c(b,g),r(u,[],s,l),f=u.length;f--;)(p=u[f])&&(b[g[f]]=!(v[g[f]]=p));if(o){if(i||e){if(i){for(u=[],f=b.length;f--;)(p=b[f])&&u.push(v[f]=p);i(null,b=[],u,l)}for(f=b.length;f--;)(p=b[f])&&(u=i?B.call(o,p):d[f])>-1&&(o[u]=!(a[u]=p))}}else b=c(b===a?b.splice(m,b.length):b),i?i(null,a,b,l):_.apply(a,b)})}function p(e){for(var t,n,r,i=e.length,o=b.relative[e[0].type],a=o||b.relative[" "],s=o?1:0,c=l(function(e){return e===t},a,!0),d=l(function(e){return B.call(t,e)>-1},a,!0),h=[function(e,n,r){return!o&&(r||n!==E)||((t=n).nodeType?c(e,n,r):d(e,n,r))}];i>s;s++)if(n=b.relative[e[s].type])h=[l(u(h),n)];else{if(n=b.filter[e[s].type].apply(null,e[s].matches),n[j]){for(r=++s;i>r&&!b.relative[e[r].type];r++);return f(s>1&&u(h),s>1&&e.slice(0,s-1).join("").replace(Q,"$1"),n,r>s&&p(e.slice(s,r)),i>r&&p(e=e.slice(r)),i>r&&e.join(""))}h.push(n)}return u(h)}function d(e,t){var r=t.length>0,i=e.length>0,o=function(a,s,l,u,f){var p,d,h,g=[],m=0,v="0",x=a&&[],w=null!=f,T=E,N=a||i&&b.find.TAG("*",f&&s.parentNode||s),C=F+=null==T?1:Math.E;for(w&&(E=s!==L&&s,y=o.el);null!=(p=N[v]);v++){if(i&&p){for(d=0;h=e[d];d++)if(h(p,s,l)){u.push(p);break}w&&(F=C,y=++o.el)}r&&((p=!h&&p)&&m--,a&&x.push(p))}if(m+=v,r&&v!==m){for(d=0;h=t[d];d++)h(x,g,s,l);if(a){if(m>0)for(;v--;)!x[v]&&!g[v]&&(g[v]=O.call(u));g=c(g)}_.apply(u,g),w&&!a&&g.length>0&&m+t.length>1&&n.uniqueSort(u)}return w&&(F=C,E=T),x};return o.el=0,r?W(o):o}function h(e,t,r){for(var i=0,o=t.length;o>i;i++)n(e,t[i],r);return r}function g(e,t,n,r,i){var o,a,l,u,c,f=s(e);f.length;if(!r&&1===f.length){if(a=f[0]=f[0].slice(0),a.length>2&&"ID"===(l=a[0]).type&&9===t.nodeType&&!i&&b.relative[a[1].type]){if(t=b.find.ID(l.matches[0].replace(ae,""),t,i)[0],!t)return n;e=e.slice(a.shift().length)}for(o=se.POS.test(e)?-1:a.length-1;o>=0&&(l=a[o],!b.relative[u=l.type]);o--)if((c=b.find[u])&&(r=c(l.matches[0].replace(ae,""),re.test(a[0].type)&&t.parentNode||t,i))){if(a.splice(o,1),e=r.length&&a.join(""),!e)return _.apply(n,q.call(r,0)),n;break}}return N(e,f)(r,t,i,n,re.test(e)),n}function m(){}var y,v,b,x,w,T,N,C,k,E,S=!0,A="undefined",j=("sizcache"+Math.random()).replace(".",""),D=String,L=e.document,H=L.documentElement,F=0,M=0,O=[].pop,_=[].push,q=[].slice,B=[].indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},W=function(e,t){return e[j]=null==t||t,e},P=function(){var e={},t=[];return W(function(n,r){return t.push(n)>b.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},R=P(),$=P(),I=P(),z="[\\x20\\t\\r\\n\\f]",X="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",U=X.replace("w","w#"),Y="([*^$|!~]?=)",V="\\["+z+"*("+X+")"+z+"*(?:"+Y+z+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+U+")|)|)"+z+"*\\]",J=":("+X+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+V+")|[^:]|\\\\.)*|.*))\\)|)",G=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+z+"*((?:-\\d)?\\d*)"+z+"*\\)|)(?=[^-]|$)",Q=new RegExp("^"+z+"+|((?:^|[^\\\\])(?:\\\\.)*)"+z+"+$","g"),Z=new RegExp("^"+z+"*,"+z+"*"),ee=new RegExp("^"+z+"*([\\x20\\t\\r\\n\\f>+~])"+z+"*"),te=new RegExp(J),ne=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,re=/[\x20\t\r\n\f]*[+~]/,ie=/h\d/i,oe=/input|select|textarea|button/i,ae=/\\(?!\\)/g,se={ID:new RegExp("^#("+X+")"),CLASS:new RegExp("^\\.("+X+")"),NAME:new RegExp("^\\[name=['\"]?("+X+")['\"]?\\]"),TAG:new RegExp("^("+X.replace("w","w*")+")"),ATTR:new RegExp("^"+V),PSEUDO:new RegExp("^"+J),POS:new RegExp(G,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+z+"*(even|odd|(([+-]|)(\\d*)n|)"+z+"*(?:([+-]|)"+z+"*(\\d+)|))"+z+"*\\)|)","i"),needsContext:new RegExp("^"+z+"*[>+~]|"+G,"i")},le=function(e){var t=L.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},ue=le(function(e){return e.appendChild(L.createComment("")),!e.getElementsByTagName("*").length}),ce=le(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")}),fe=le(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),pe=le(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),de=le(function(e){e.id=j+0,e.innerHTML="<a name='"+j+"'></a><div name='"+j+"'></div>",H.insertBefore(e,H.firstChild);var t=L.getElementsByName&&L.getElementsByName(j).length===2+L.getElementsByName(j+0).length;return v=!L.getElementById(j),H.removeChild(e),t});try{q.call(H.childNodes,0)[0].nodeType}catch(he){q=function(e){for(var t,n=[];t=this[e];e++)n.push(t);return n}}n.matches=function(e,t){return n(e,null,null,t)},n.matchesSelector=function(e,t){return n(t,null,null,[e]).length>0},x=n.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=x(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=x(t);return n},w=n.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},T=n.contains=H.contains?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&1===r.nodeType&&n.contains&&n.contains(r))}:H.compareDocumentPosition?function(e,t){return t&&!!(16&e.compareDocumentPosition(t))}:function(e,t){for(;t=t.parentNode;)if(t===e)return!0;return!1},n.attr=function(e,t){var n,r=w(e);return r||(t=t.toLowerCase()),(n=b.attrHandle[t])?n(e):r||fe?e.getAttribute(t):(n=e.getAttributeNode(t),n?"boolean"==typeof e[t]?e[t]?t:null:n.specified?n.value:null:null)},b=n.selectors={cacheLength:50,createPseudo:W,match:se,attrHandle:ce?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:v?function(e,t,n){if(typeof t.getElementById!==A&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==A&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==A&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:ue?function(e,t){return typeof t.getElementsByTagName!==A?t.getElementsByTagName(e):void 0}:function(e,t){var n=t.getElementsByTagName(e);if("*"===e){for(var r,i=[],o=0;r=n[o];o++)1===r.nodeType&&i.push(r);return i}return n},NAME:de&&function(e,t){return typeof t.getElementsByName!==A?t.getElementsByName(name):void 0},CLASS:pe&&function(e,t,n){return typeof t.getElementsByClassName===A||n?void 0:t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(ae,""),e[3]=(e[4]||e[5]||"").replace(ae,""),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1]?(e[2]||n.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*("even"===e[2]||"odd"===e[2])),e[4]=+(e[6]+e[7]||"odd"===e[2])):e[2]&&n.error(e[0]),e},PSEUDO:function(e){var t,n;return se.CHILD.test(e[0])?null:(e[3]?e[2]=e[3]:(t=e[4])&&(te.test(t)&&(n=s(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t),e.slice(0,3))}},filter:{ID:v?function(e){return e=e.replace(ae,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace(ae,""),function(t){var n=typeof t.getAttributeNode!==A&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(ae,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=R[j][e+" "];return t||(t=new RegExp("(^|"+z+")"+e+"("+z+"|$)"))&&R(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,r){return function(i,o){var a=n.attr(i,e);return null==a?"!="===t:t?(a+="","="===t?a===r:"!="===t?a!==r:"^="===t?r&&0===a.indexOf(r):"*="===t?r&&a.indexOf(r)>-1:"$="===t?r&&a.substr(a.length-r.length)===r:"~="===t?(" "+a+" ").indexOf(r)>-1:"|="===t?a===r||a.substr(0,r.length+1)===r+"-":!1):!0}},CHILD:function(e,t,n,r){return"nth"===e?function(e){var t,i,o=e.parentNode;if(1===n&&0===r)return!0;if(o)for(i=0,t=o.firstChild;t&&(1!==t.nodeType||(i++,e!==t));t=t.nextSibling);return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":for(;n=n.previousSibling;)if(1===n.nodeType)return!1;if("first"===e)return!0;n=t;case"last":for(;n=n.nextSibling;)if(1===n.nodeType)return!1;return!0}}},PSEUDO:function(e,t){var r,i=b.pseudos[e]||b.setFilters[e.toLowerCase()]||n.error("unsupported pseudo: "+e);return i[j]?i(t):i.length>1?(r=[e,e,"",t],b.setFilters.hasOwnProperty(e.toLowerCase())?W(function(e,n){for(var r,o=i(e,t),a=o.length;a--;)r=B.call(e,o[a]),e[r]=!(n[r]=o[a])}):function(e){return i(e,0,r)}):i}},pseudos:{not:W(function(e){var t=[],n=[],r=N(e.replace(Q,"$1"));return r[j]?W(function(e,t,n,i){for(var o,a=r(e,null,i,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:W(function(e){return function(t){return n(e,t).length>0}}),contains:W(function(e){return function(t){return(t.textContent||t.innerText||x(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!b.pseudos.empty(e)},empty:function(e){var t;for(e=e.firstChild;e;){if(e.nodeName>"@"||3===(t=e.nodeType)||4===t)return!1;e=e.nextSibling}return!0},header:function(e){return ie.test(e.nodeName)},text:function(e){var t,n;return"input"===e.nodeName.toLowerCase()&&"text"===(t=e.type)&&(null==(n=e.getAttribute("type"))||n.toLowerCase()===t)},radio:r("radio"),checkbox:r("checkbox"),file:r("file"),password:r("password"),image:r("image"),submit:i("submit"),reset:i("reset"),button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},input:function(e){return oe.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:o(function(){return[0]}),last:o(function(e,t){return[t-1]}),eq:o(function(e,t,n){return[0>n?n+t:n]}),even:o(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:o(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:o(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:o(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}},C=H.compareDocumentPosition?function(e,t){return e===t?(k=!0,0):(e.compareDocumentPosition&&t.compareDocumentPosition?4&e.compareDocumentPosition(t):e.compareDocumentPosition)?-1:1}:function(e,t){if(e===t)return k=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],o=[],s=e.parentNode,l=t.parentNode,u=s;if(s===l)return a(e,t);if(!s)return-1;if(!l)return 1;for(;u;)i.unshift(u),u=u.parentNode;for(u=l;u;)o.unshift(u),u=u.parentNode;n=i.length,r=o.length;for(var c=0;n>c&&r>c;c++)if(i[c]!==o[c])return a(i[c],o[c]);return c===n?a(e,o[c],-1):a(i[c],t,1)},[0,0].sort(C),S=!k,n.uniqueSort=function(e){var t,n=[],r=1,i=0;if(k=S,e.sort(C),k){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));for(;i--;)e.splice(n[i],1)}return e},n.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},N=n.compile=function(e,t){var n,r=[],i=[],o=I[j][e+" "];if(!o){for(t||(t=s(e)),n=t.length;n--;)o=p(t[n]),o[j]?r.push(o):i.push(o);o=I(e,d(i,r))}return o},L.querySelectorAll&&function(){var e,t=g,r=/'|\\/g,i=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,o=[":focus"],a=[":active"],l=H.matchesSelector||H.mozMatchesSelector||H.webkitMatchesSelector||H.oMatchesSelector||H.msMatchesSelector;le(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||o.push("\\["+z+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||o.push(":checked")}),le(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&o.push("[*^$]="+z+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||o.push(":enabled",":disabled")}),o=new RegExp(o.join("|")),g=function(e,n,i,a,l){if(!a&&!l&&!o.test(e)){var u,c,f=!0,p=j,d=n,h=9===n.nodeType&&e;if(1===n.nodeType&&"object"!==n.nodeName.toLowerCase()){for(u=s(e),(f=n.getAttribute("id"))?p=f.replace(r,"\\$&"):n.setAttribute("id",p),p="[id='"+p+"'] ",c=u.length;c--;)u[c]=p+u[c].join("");d=re.test(e)&&n.parentNode||n,h=u.join(",")}if(h)try{return _.apply(i,q.call(d.querySelectorAll(h),0)),i}catch(g){}finally{f||n.removeAttribute("id")}}return t(e,n,i,a,l)},l&&(le(function(t){e=l.call(t,"div");try{l.call(t,"[test!='']:sizzle"),a.push("!=",J)}catch(n){}}),a=new RegExp(a.join("|")),n.matchesSelector=function(t,r){if(r=r.replace(i,"='$1']"),!w(t)&&!a.test(r)&&!o.test(r))try{var s=l.call(t,r);if(s||e||t.document&&11!==t.document.nodeType)return s}catch(u){}return n(r,null,null,[t]).length>0})}(),b.pseudos.nth=b.pseudos.eq,b.filters=m.prototype=b.pseudos,b.setFilters=new m,n.attr=K.attr,K.find=n,K.expr=n.selectors,K.expr[":"]=K.expr.pseudos,K.unique=n.uniqueSort,K.text=n.getText,K.isXMLDoc=n.isXML,K.contains=n.contains}(e);var Me=/Until$/,Oe=/^(?:parents|prev(?:Until|All))/,_e=/^.[^:#\[\.,]*$/,qe=K.expr.match.needsContext,Be={children:!0,contents:!0,next:!0,prev:!0};K.fn.extend({find:function(e){var t,n,r,i,o,a,s=this;if("string"!=typeof e)return K(e).filter(function(){for(t=0,n=s.length;n>t;t++)if(K.contains(s[t],this))return!0});for(a=this.pushStack("","find",e),t=0,n=this.length;n>t;t++)if(r=a.length,K.find(e,this[t],a),t>0)for(i=r;i<a.length;i++)for(o=0;r>o;o++)if(a[o]===a[i]){a.splice(i--,1);break}return a},has:function(e){var t,n=K(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(K.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(u(this,e,!1),"not",e)},filter:function(e){return this.pushStack(u(this,e,!0),"filter",e)},is:function(e){return!!e&&("string"==typeof e?qe.test(e)?K(e,this.context).index(this[0])>=0:K.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=qe.test(e)||"string"!=typeof e?K(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n.ownerDocument&&n!==t&&11!==n.nodeType;){if(a?a.index(n)>-1:K.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}return o=o.length>1?K.unique(o):o,this.pushStack(o,"closest",e)},index:function(e){return e?"string"==typeof e?K.inArray(this[0],K(e)):K.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n="string"==typeof e?K(e,t):K.makeArray(e&&e.nodeType?[e]:e),r=K.merge(this.get(),n);return this.pushStack(s(n[0])||s(r[0])?r:K.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),K.fn.andSelf=K.fn.addBack,K.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return K.dir(e,"parentNode")},parentsUntil:function(e,t,n){return K.dir(e,"parentNode",n)},next:function(e){return l(e,"nextSibling")},prev:function(e){return l(e,"previousSibling")},nextAll:function(e){return K.dir(e,"nextSibling")},prevAll:function(e){return K.dir(e,"previousSibling")},nextUntil:function(e,t,n){return K.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return K.dir(e,"previousSibling",n)},siblings:function(e){return K.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return K.sibling(e.firstChild)},contents:function(e){return K.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:K.merge([],e.childNodes)}},function(e,t){K.fn[e]=function(n,r){var i=K.map(this,t,n);return Me.test(e)||(r=n),r&&"string"==typeof r&&(i=K.filter(r,i)),i=this.length>1&&!Be[e]?K.unique(i):i,this.length>1&&Oe.test(e)&&(i=i.reverse()),this.pushStack(i,e,Y.call(arguments).join(","))}}),K.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?K.find.matchesSelector(t[0],e)?[t[0]]:[]:K.find.matches(e,t)},dir:function(e,n,r){for(var i=[],o=e[n];o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!K(o).is(r));)1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});var We="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Pe=/ jQuery\d+="(?:null|\d+)"/g,Re=/^\s+/,$e=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Ie=/<([\w:]+)/,ze=/<tbody/i,Xe=/<|&#?\w+;/,Ue=/<(?:script|style|link)/i,Ye=/<(?:script|object|embed|option|style)/i,Ve=new RegExp("<(?:"+We+")[\\s/>]","i"),Je=/^(?:checkbox|radio)$/,Ge=/checked\s*(?:[^=]|=\s*.checked.)/i,Qe=/\/(java|ecma)script/i,Ke=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Ze={
option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},et=c(R),tt=et.appendChild(R.createElement("div"));Ze.optgroup=Ze.option,Ze.tbody=Ze.tfoot=Ze.colgroup=Ze.caption=Ze.thead,Ze.th=Ze.td,K.support.htmlSerialize||(Ze._default=[1,"X<div>","</div>"]),K.fn.extend({text:function(e){return K.access(this,function(e){return e===t?K.text(this):this.empty().append((this[0]&&this[0].ownerDocument||R).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(K.isFunction(e))return this.each(function(t){K(this).wrapAll(e.call(this,t))});if(this[0]){var t=K(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return K.isFunction(e)?this.each(function(t){K(this).wrapInner(e.call(this,t))}):this.each(function(){var t=K(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=K.isFunction(e);return this.each(function(n){K(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){K.nodeName(this,"body")||K(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!s(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=K.clean(arguments);return this.pushStack(K.merge(e,this),"before",this.selector)}},after:function(){if(!s(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=K.clean(arguments);return this.pushStack(K.merge(this,e),"after",this.selector)}},remove:function(e,t){for(var n,r=0;null!=(n=this[r]);r++)(!e||K.filter(e,[n]).length)&&(!t&&1===n.nodeType&&(K.cleanData(n.getElementsByTagName("*")),K.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)for(1===e.nodeType&&K.cleanData(e.getElementsByTagName("*"));e.firstChild;)e.removeChild(e.firstChild);return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return K.clone(this,e,t)})},html:function(e){return K.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(Pe,""):t;if("string"==typeof e&&!Ue.test(e)&&(K.support.htmlSerialize||!Ve.test(e))&&(K.support.leadingWhitespace||!Re.test(e))&&!Ze[(Ie.exec(e)||["",""])[1].toLowerCase()]){e=e.replace($e,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(K.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return s(this[0])?this.length?this.pushStack(K(K.isFunction(e)?e():e),"replaceWith",e):this:K.isFunction(e)?this.each(function(t){var n=K(this),r=n.html();n.replaceWith(e.call(this,t,r))}):("string"!=typeof e&&(e=K(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;K(this).remove(),t?K(t).before(e):K(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,o,a,s,l=0,u=e[0],c=[],p=this.length;if(!K.support.checkClone&&p>1&&"string"==typeof u&&Ge.test(u))return this.each(function(){K(this).domManip(e,n,r)});if(K.isFunction(u))return this.each(function(i){var o=K(this);e[0]=u.call(this,i,n?o.html():t),o.domManip(e,n,r)});if(this[0]){if(i=K.buildFragment(e,this,c),a=i.fragment,o=a.firstChild,1===a.childNodes.length&&(a=o),o)for(n=n&&K.nodeName(o,"tr"),s=i.cacheable||p-1;p>l;l++)r.call(n&&K.nodeName(this[l],"table")?f(this[l],"tbody"):this[l],l===s?a:K.clone(a,!0,!0));a=o=null,c.length&&K.each(c,function(e,t){t.src?K.ajax?K.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):K.error("no ajax"):K.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Ke,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),K.buildFragment=function(e,n,r){var i,o,a,s=e[0];return n=n||R,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,1===e.length&&"string"==typeof s&&s.length<512&&n===R&&"<"===s.charAt(0)&&!Ye.test(s)&&(K.support.checkClone||!Ge.test(s))&&(K.support.html5Clone||!Ve.test(s))&&(o=!0,i=K.fragments[s],a=i!==t),i||(i=n.createDocumentFragment(),K.clean(e,n,i,r),o&&(K.fragments[s]=a&&i)),{fragment:i,cacheable:o}},K.fragments={},K.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){K.fn[e]=function(n){var r,i=0,o=[],a=K(n),s=a.length,l=1===this.length&&this[0].parentNode;if((null==l||l&&11===l.nodeType&&1===l.childNodes.length)&&1===s)return a[t](this[0]),this;for(;s>i;i++)r=(i>0?this.clone(!0):this).get(),K(a[i])[t](r),o=o.concat(r);return this.pushStack(o,e,a.selector)}}),K.extend({clone:function(e,t,n){var r,i,o,a;if(K.support.html5Clone||K.isXMLDoc(e)||!Ve.test("<"+e.nodeName+">")?a=e.cloneNode(!0):(tt.innerHTML=e.outerHTML,tt.removeChild(a=tt.firstChild)),!(K.support.noCloneEvent&&K.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||K.isXMLDoc(e)))for(d(e,a),r=h(e),i=h(a),o=0;r[o];++o)i[o]&&d(r[o],i[o]);if(t&&(p(e,a),n))for(r=h(e),i=h(a),o=0;r[o];++o)p(r[o],i[o]);return r=i=null,a},clean:function(e,t,n,r){var i,o,a,s,l,u,f,p,d,h,m,y=t===R&&et,v=[];for(t&&"undefined"!=typeof t.createDocumentFragment||(t=R),i=0;null!=(a=e[i]);i++)if("number"==typeof a&&(a+=""),a){if("string"==typeof a)if(Xe.test(a)){for(y=y||c(t),f=t.createElement("div"),y.appendChild(f),a=a.replace($e,"<$1></$2>"),s=(Ie.exec(a)||["",""])[1].toLowerCase(),l=Ze[s]||Ze._default,u=l[0],f.innerHTML=l[1]+a+l[2];u--;)f=f.lastChild;if(!K.support.tbody)for(p=ze.test(a),d="table"!==s||p?"<table>"!==l[1]||p?[]:f.childNodes:f.firstChild&&f.firstChild.childNodes,o=d.length-1;o>=0;--o)K.nodeName(d[o],"tbody")&&!d[o].childNodes.length&&d[o].parentNode.removeChild(d[o]);!K.support.leadingWhitespace&&Re.test(a)&&f.insertBefore(t.createTextNode(Re.exec(a)[0]),f.firstChild),a=f.childNodes,f.parentNode.removeChild(f)}else a=t.createTextNode(a);a.nodeType?v.push(a):K.merge(v,a)}if(f&&(a=f=y=null),!K.support.appendChecked)for(i=0;null!=(a=v[i]);i++)K.nodeName(a,"input")?g(a):"undefined"!=typeof a.getElementsByTagName&&K.grep(a.getElementsByTagName("input"),g);if(n)for(h=function(e){return!e.type||Qe.test(e.type)?r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e):void 0},i=0;null!=(a=v[i]);i++)K.nodeName(a,"script")&&h(a)||(n.appendChild(a),"undefined"!=typeof a.getElementsByTagName&&(m=K.grep(K.merge([],a.getElementsByTagName("script")),h),v.splice.apply(v,[i+1,0].concat(m)),i+=m.length));return v},cleanData:function(e,t){for(var n,r,i,o,a=0,s=K.expando,l=K.cache,u=K.support.deleteExpando,c=K.event.special;null!=(i=e[a]);a++)if((t||K.acceptData(i))&&(r=i[s],n=r&&l[r])){if(n.events)for(o in n.events)c[o]?K.event.remove(i,o):K.removeEvent(i,o,n.handle);l[r]&&(delete l[r],u?delete i[s]:i.removeAttribute?i.removeAttribute(s):i[s]=null,K.deletedIds.push(r))}}}),function(){var e,t;K.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=K.uaMatch(I.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),K.browser=t,K.sub=function(){function e(t,n){return new e.fn.init(t,n)}K.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(n,r){return r&&r instanceof K&&!(r instanceof e)&&(r=e(r)),K.fn.init.call(this,n,r,t)},e.fn.init.prototype=e.fn;var t=e(R);return e}}();var nt,rt,it,ot=/alpha\([^)]*\)/i,at=/opacity=([^)]*)/,st=/^(top|right|bottom|left)$/,lt=/^(none|table(?!-c[ea]).+)/,ut=/^margin/,ct=new RegExp("^("+Z+")(.*)$","i"),ft=new RegExp("^("+Z+")(?!px)[a-z%]+$","i"),pt=new RegExp("^([-+])=("+Z+")","i"),dt={BODY:"block"},ht={position:"absolute",visibility:"hidden",display:"block"},gt={letterSpacing:0,fontWeight:400},mt=["Top","Right","Bottom","Left"],yt=["Webkit","O","Moz","ms"],vt=K.fn.toggle;K.fn.extend({css:function(e,n){return K.access(this,function(e,n,r){return r!==t?K.style(e,n,r):K.css(e,n)},e,n,arguments.length>1)},show:function(){return v(this,!0)},hide:function(){return v(this)},toggle:function(e,t){var n="boolean"==typeof e;return K.isFunction(e)&&K.isFunction(t)?vt.apply(this,arguments):this.each(function(){(n?e:y(this))?K(this).show():K(this).hide()})}}),K.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=nt(e,"opacity");return""===n?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":K.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=K.camelCase(n),u=e.style;if(n=K.cssProps[l]||(K.cssProps[l]=m(u,l)),s=K.cssHooks[n]||K.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=pt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(K.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"===a&&!K.cssNumber[l]&&(r+="px"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=K.camelCase(n);return n=K.cssProps[l]||(K.cssProps[l]=m(e.style,l)),s=K.cssHooks[n]||K.cssHooks[l],s&&"get"in s&&(o=s.get(e,!0,i)),o===t&&(o=nt(e,n)),"normal"===o&&n in gt&&(o=gt[n]),r||i!==t?(a=parseFloat(o),r||K.isNumeric(a)?a||0:o):o},swap:function(e,t,n){var r,i,o={};for(i in t)o[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=o[i];return r}}),e.getComputedStyle?nt=function(t,n){var r,i,o,a,s=e.getComputedStyle(t,null),l=t.style;return s&&(r=s.getPropertyValue(n)||s[n],""===r&&!K.contains(t.ownerDocument,t)&&(r=K.style(t,n)),ft.test(r)&&ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=r,r=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),r}:R.documentElement.currentStyle&&(nt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],o=e.style;return null==i&&o&&o[t]&&(i=o[t]),ft.test(i)&&!st.test(t)&&(n=o.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),o.left="fontSize"===t?"1em":i,i=o.pixelLeft+"px",o.left=n,r&&(e.runtimeStyle.left=r)),""===i?"auto":i}),K.each(["height","width"],function(e,t){K.cssHooks[t]={get:function(e,n,r){return n?0===e.offsetWidth&<.test(nt(e,"display"))?K.swap(e,ht,function(){return w(e,t,r)}):w(e,t,r):void 0},set:function(e,n,r){return b(e,n,r?x(e,t,r,K.support.boxSizing&&"border-box"===K.css(e,"boxSizing")):0)}}}),K.support.opacity||(K.cssHooks.opacity={get:function(e,t){return at.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=K.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,t>=1&&""===K.trim(o.replace(ot,""))&&n.removeAttribute&&(n.removeAttribute("filter"),r&&!r.filter)||(n.filter=ot.test(o)?o.replace(ot,i):o+" "+i)}}),K(function(){K.support.reliableMarginRight||(K.cssHooks.marginRight={get:function(e,t){return K.swap(e,{display:"inline-block"},function(){return t?nt(e,"marginRight"):void 0})}}),!K.support.pixelPosition&&K.fn.position&&K.each(["top","left"],function(e,t){K.cssHooks[t]={get:function(e,n){if(n){var r=nt(e,t);return ft.test(r)?K(e).position()[t]+"px":r}}}})}),K.expr&&K.expr.filters&&(K.expr.filters.hidden=function(e){return 0===e.offsetWidth&&0===e.offsetHeight||!K.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||nt(e,"display"))},K.expr.filters.visible=function(e){return!K.expr.filters.hidden(e)}),K.each({margin:"",padding:"",border:"Width"},function(e,t){K.cssHooks[e+t]={expand:function(n){var r,i="string"==typeof n?n.split(" "):[n],o={};for(r=0;4>r;r++)o[e+mt[r]+t]=i[r]||i[r-2]||i[0];return o}},ut.test(e)||(K.cssHooks[e+t].set=b)});var bt=/%20/g,xt=/\[\]$/,wt=/\r?\n/g,Tt=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,Nt=/^(?:select|textarea)/i;K.fn.extend({serialize:function(){return K.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?K.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||Nt.test(this.nodeName)||Tt.test(this.type))}).map(function(e,t){var n=K(this).val();return null==n?null:K.isArray(n)?K.map(n,function(e,n){return{name:t.name,value:e.replace(wt,"\r\n")}}):{name:t.name,value:n.replace(wt,"\r\n")}}).get()}}),K.param=function(e,n){var r,i=[],o=function(e,t){t=K.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=K.ajaxSettings&&K.ajaxSettings.traditional),K.isArray(e)||e.jquery&&!K.isPlainObject(e))K.each(e,function(){o(this.name,this.value)});else for(r in e)N(r,e[r],n,o);return i.join("&").replace(bt,"+")};var Ct,kt,Et=/#.*$/,St=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,At=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,jt=/^(?:GET|HEAD)$/,Dt=/^\/\//,Lt=/\?/,Ht=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,Ft=/([?&])_=[^&]*/,Mt=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Ot=K.fn.load,_t={},qt={},Bt=["*/"]+["*"];try{kt=$.href}catch(Wt){kt=R.createElement("a"),kt.href="",kt=kt.href}Ct=Mt.exec(kt.toLowerCase())||[],K.fn.load=function(e,n,r){if("string"!=typeof e&&Ot)return Ot.apply(this,arguments);if(!this.length)return this;var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),K.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(o="POST"),K.ajax({url:e,type:o,dataType:"html",data:n,complete:function(e,t){r&&s.each(r,a||[e.responseText,t,e])}}).done(function(e){a=arguments,s.html(i?K("<div>").append(e.replace(Ht,"")).find(i):e)}),this},K.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){K.fn[t]=function(e){return this.on(t,e)}}),K.each(["get","post"],function(e,n){K[n]=function(e,r,i,o){return K.isFunction(r)&&(o=o||i,i=r,r=t),K.ajax({type:n,url:e,data:r,success:i,dataType:o})}}),K.extend({getScript:function(e,n){return K.get(e,t,n,"script")},getJSON:function(e,t,n){return K.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?E(e,K.ajaxSettings):(t=e,e=K.ajaxSettings),E(e,t),e},ajaxSettings:{url:kt,isLocal:At.test(Ct[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Bt},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":K.parseJSON,"text xml":K.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:C(_t),ajaxTransport:C(qt),ajax:function(e,n){function r(e,n,r,a){var u,f,v,b,w,N=n;2!==x&&(x=2,l&&clearTimeout(l),s=t,o=a||"",T.readyState=e>0?4:0,r&&(b=S(p,T,r)),e>=200&&300>e||304===e?(p.ifModified&&(w=T.getResponseHeader("Last-Modified"),w&&(K.lastModified[i]=w),w=T.getResponseHeader("Etag"),w&&(K.etag[i]=w)),304===e?(N="notmodified",u=!0):(u=A(p,b),N=u.state,f=u.data,v=u.error,u=!v)):(v=N,(!N||e)&&(N="error",0>e&&(e=0))),T.status=e,T.statusText=(n||N)+"",u?g.resolveWith(d,[f,N,T]):g.rejectWith(d,[T,N,v]),T.statusCode(y),y=t,c&&h.trigger("ajax"+(u?"Success":"Error"),[T,p,u?f:v]),m.fireWith(d,[T,N]),c&&(h.trigger("ajaxComplete",[T,p]),--K.active||K.event.trigger("ajaxStop")))}"object"==typeof e&&(n=e,e=t),n=n||{};var i,o,a,s,l,u,c,f,p=K.ajaxSetup({},n),d=p.context||p,h=d!==p&&(d.nodeType||d instanceof K)?K(d):K.event,g=K.Deferred(),m=K.Callbacks("once memory"),y=p.statusCode||{},v={},b={},x=0,w="canceled",T={readyState:0,setRequestHeader:function(e,t){if(!x){var n=e.toLowerCase();e=b[n]=b[n]||e,v[e]=t}return this},getAllResponseHeaders:function(){return 2===x?o:null},getResponseHeader:function(e){var n;if(2===x){if(!a)for(a={};n=St.exec(o);)a[n[1].toLowerCase()]=n[2];n=a[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return x||(p.mimeType=e),this},abort:function(e){return e=e||w,s&&s.abort(e),r(0,e),this}};if(g.promise(T),T.success=T.done,T.error=T.fail,T.complete=m.add,T.statusCode=function(e){if(e){var t;if(2>x)for(t in e)y[t]=[y[t],e[t]];else t=e[T.status],T.always(t)}return this},p.url=((e||p.url)+"").replace(Et,"").replace(Dt,Ct[1]+"//"),p.dataTypes=K.trim(p.dataType||"*").toLowerCase().split(te),null==p.crossDomain&&(u=Mt.exec(p.url.toLowerCase()),p.crossDomain=!(!u||u[1]===Ct[1]&&u[2]===Ct[2]&&(u[3]||("http:"===u[1]?80:443))==(Ct[3]||("http:"===Ct[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=K.param(p.data,p.traditional)),k(_t,p,n,T),2===x)return T;if(c=p.global,p.type=p.type.toUpperCase(),p.hasContent=!jt.test(p.type),c&&0===K.active++&&K.event.trigger("ajaxStart"),!p.hasContent&&(p.data&&(p.url+=(Lt.test(p.url)?"&":"?")+p.data,delete p.data),i=p.url,p.cache===!1)){var N=K.now(),C=p.url.replace(Ft,"$1_="+N);p.url=C+(C===p.url?(Lt.test(p.url)?"&":"?")+"_="+N:"")}(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&T.setRequestHeader("Content-Type",p.contentType),p.ifModified&&(i=i||p.url,K.lastModified[i]&&T.setRequestHeader("If-Modified-Since",K.lastModified[i]),K.etag[i]&&T.setRequestHeader("If-None-Match",K.etag[i])),T.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Bt+"; q=0.01":""):p.accepts["*"]);for(f in p.headers)T.setRequestHeader(f,p.headers[f]);if(!p.beforeSend||p.beforeSend.call(d,T,p)!==!1&&2!==x){w="abort";for(f in{success:1,error:1,complete:1})T[f](p[f]);if(s=k(qt,p,n,T)){T.readyState=1,c&&h.trigger("ajaxSend",[T,p]),p.async&&p.timeout>0&&(l=setTimeout(function(){T.abort("timeout")},p.timeout));try{x=1,s.send(v,r)}catch(E){if(!(2>x))throw E;r(-1,E)}}else r(-1,"No Transport");return T}return T.abort()},active:0,lastModified:{},etag:{}});var Pt=[],Rt=/\?/,$t=/(=)\?(?=&|$)|\?\?/,It=K.now();K.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Pt.pop()||K.expando+"_"+It++;return this[e]=!0,e}}),K.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.data,u=n.url,c=n.jsonp!==!1,f=c&&$t.test(u),p=c&&!f&&"string"==typeof l&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&$t.test(l);return"jsonp"===n.dataTypes[0]||f||p?(o=n.jsonpCallback=K.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,a=e[o],f?n.url=u.replace($t,"$1"+o):p?n.data=l.replace($t,"$1"+o):c&&(n.url+=(Rt.test(u)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||K.error(o+" was not called"),s[0]},n.dataTypes[0]="json",e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Pt.push(o)),s&&K.isFunction(a)&&a(s[0]),s=a=t}),"script"):void 0}),K.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return K.globalEval(e),e}}}),K.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),K.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=R.head||R.getElementsByTagName("head")[0]||R.documentElement;return{send:function(i,o){n=R.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){(i||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var zt,Xt=e.ActiveXObject?function(){for(var e in zt)zt[e](0,1)}:!1,Ut=0;K.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&j()||D()}:j,function(e){K.extend(K.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(K.ajaxSettings.xhr()),K.support.ajax&&K.ajaxTransport(function(n){if(!n.crossDomain||K.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,f,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=K.noop,Xt&&delete zt[a]),i)4!==l.readyState&&l.abort();else{s=l.status,c=l.getAllResponseHeaders(),f={},p=l.responseXML,p&&p.documentElement&&(f.xml=p);try{f.text=l.responseText}catch(d){}try{u=l.statusText}catch(d){u=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=f.text?200:404}}catch(h){i||o(-1,h)}f&&o(s,u,f,c)},n.async?4===l.readyState?setTimeout(r,0):(a=++Ut,Xt&&(zt||(zt={},K(e).unload(Xt)),zt[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var Yt,Vt,Jt=/^(?:toggle|show|hide)$/,Gt=new RegExp("^(?:([-+])=|)("+Z+")([a-z%]*)$","i"),Qt=/queueHooks$/,Kt=[O],Zt={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Gt.exec(t),a=i.cur(),s=+a||0,l=1,u=20;if(o){if(n=+o[2],r=o[3]||(K.cssNumber[e]?"":"px"),"px"!==r&&s){s=K.css(i.elem,e,!0)||n||1;do l=l||".5",s/=l,K.style(i.elem,e,s+r);while(l!==(l=i.cur()/a)&&1!==l&&--u)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};K.Animation=K.extend(F,{tweener:function(e,t){K.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++)n=e[r],Zt[n]=Zt[n]||[],Zt[n].unshift(t)},prefilter:function(e,t){t?Kt.unshift(e):Kt.push(e)}}),K.Tween=_,_.prototype={constructor:_,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(K.cssNumber[n]?"":"px")},cur:function(){var e=_.propHooks[this.prop];return e&&e.get?e.get(this):_.propHooks._default.get(this)},run:function(e){var t,n=_.propHooks[this.prop];return this.options.duration?this.pos=t=K.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):_.propHooks._default.set(this),this}},_.prototype.init.prototype=_.prototype,_.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=K.css(e.elem,e.prop,!1,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){K.fx.step[e.prop]?K.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[K.cssProps[e.prop]]||K.cssHooks[e.prop])?K.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},_.propHooks.scrollTop=_.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},K.each(["toggle","show","hide"],function(e,t){var n=K.fn[t];K.fn[t]=function(r,i,o){return null==r||"boolean"==typeof r||!e&&K.isFunction(r)&&K.isFunction(i)?n.apply(this,arguments):this.animate(q(t,!0),r,i,o)}}),K.fn.extend({fadeTo:function(e,t,n,r){return this.filter(y).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=K.isEmptyObject(e),o=K.speed(t,n,r),a=function(){var t=F(this,K.extend({},e),o);i&&t.stop(!0)};return i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=K.timers,a=K._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Qt.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem===this&&(null==e||o[n].queue===e)&&(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&K.dequeue(this,e)})}}),K.each({slideDown:q("show"),slideUp:q("hide"),slideToggle:q("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){K.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),K.speed=function(e,t,n){var r=e&&"object"==typeof e?K.extend({},e):{complete:n||!n&&t||K.isFunction(e)&&e,duration:e,easing:n&&t||t&&!K.isFunction(t)&&t};return r.duration=K.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in K.fx.speeds?K.fx.speeds[r.duration]:K.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){K.isFunction(r.old)&&r.old.call(this),r.queue&&K.dequeue(this,r.queue)},r},K.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},K.timers=[],K.fx=_.prototype.init,K.fx.tick=function(){var e,n=K.timers,r=0;for(Yt=K.now();r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||K.fx.stop(),Yt=t},K.fx.timer=function(e){e()&&K.timers.push(e)&&!Vt&&(Vt=setInterval(K.fx.tick,K.fx.interval))},K.fx.interval=13,K.fx.stop=function(){clearInterval(Vt),Vt=null},K.fx.speeds={slow:600,fast:200,_default:400},K.fx.step={},K.expr&&K.expr.filters&&(K.expr.filters.animated=function(e){return K.grep(K.timers,function(t){return e===t.elem}).length});var en=/^(?:body|html)$/i;K.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){K.offset.setOffset(this,e,t)});var n,r,i,o,a,s,l,u={top:0,left:0},c=this[0],f=c&&c.ownerDocument;if(f)return(r=f.body)===c?K.offset.bodyOffset(c):(n=f.documentElement,K.contains(n,c)?("undefined"!=typeof c.getBoundingClientRect&&(u=c.getBoundingClientRect()),i=B(f),o=n.clientTop||r.clientTop||0,a=n.clientLeft||r.clientLeft||0,s=i.pageYOffset||n.scrollTop,l=i.pageXOffset||n.scrollLeft,{top:u.top+s-o,left:u.left+l-a}):u)},K.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return K.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(K.css(e,"marginTop"))||0,n+=parseFloat(K.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=K.css(e,"position");"static"===r&&(e.style.position="relative");var i,o,a=K(e),s=a.offset(),l=K.css(e,"top"),u=K.css(e,"left"),c=("absolute"===r||"fixed"===r)&&K.inArray("auto",[l,u])>-1,f={},p={};c?(p=a.position(),i=p.top,o=p.left):(i=parseFloat(l)||0,o=parseFloat(u)||0),K.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(f.top=t.top-s.top+i),null!=t.left&&(f.left=t.left-s.left+o),"using"in t?t.using.call(e,f):a.css(f)}},K.fn.extend({position:function(){if(this[0]){var e=this[0],t=this.offsetParent(),n=this.offset(),r=en.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(K.css(e,"marginTop"))||0,n.left-=parseFloat(K.css(e,"marginLeft"))||0,r.top+=parseFloat(K.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(K.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||R.body;e&&!en.test(e.nodeName)&&"static"===K.css(e,"position");)e=e.offsetParent;return e||R.body})}}),K.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);K.fn[e]=function(i){return K.access(this,function(e,i,o){var a=B(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:void(a?a.scrollTo(r?K(a).scrollLeft():o,r?o:K(a).scrollTop()):e[i]=o)},e,i,arguments.length,null)}}),K.each({Height:"height",Width:"width"},function(e,n){K.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){K.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return K.access(this,function(n,r,i){var o;return K.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?K.css(n,r,i,s):K.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=K,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return K})}(window); |
ajax/libs/ember-data.js/1.0.0-beta.9/ember-data.js | jdanyow/cdnjs | (function(global){
var define, requireModule, require, requirejs;
(function() {
var registry = {}, seen = {}, state = {};
var FAILED = false;
define = function(name, deps, callback) {
registry[name] = {
deps: deps,
callback: callback
};
};
function reify(deps, name, seen) {
var length = deps.length;
var reified = new Array(length);
var dep;
var exports;
for (var i = 0, l = length; i < l; i++) {
dep = deps[i];
if (dep === 'exports') {
exports = reified[i] = seen;
} else {
reified[i] = require(resolve(dep, name));
}
}
return {
deps: reified,
exports: exports
};
}
requirejs = require = requireModule = function(name) {
if (state[name] !== FAILED &&
seen.hasOwnProperty(name)) {
return seen[name];
}
if (!registry[name]) {
throw new Error('Could not find module ' + name);
}
var mod = registry[name];
var reified;
var module;
var loaded = false;
seen[name] = { }; // placeholder for run-time cycles
try {
reified = reify(mod.deps, name, seen[name]);
module = mod.callback.apply(this, reified.deps);
loaded = true;
} finally {
if (!loaded) {
state[name] = FAILED;
}
}
return reified.exports ? seen[name] : (seen[name] = module);
};
function resolve(child, name) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split('/');
var nameParts = name.split('/');
var parentBase;
if (nameParts.length === 1) {
parentBase = nameParts;
} else {
parentBase = nameParts.slice(0, -1);
}
for (var i = 0, l = parts.length; i < l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join('/');
}
requirejs.entries = requirejs._eak_seen = registry;
requirejs.clear = function(){
requirejs.entries = requirejs._eak_seen = registry = {};
seen = state = {};
};
})();
define("activemodel-adapter",
["activemodel-adapter/system","exports"],
function(__dependency1__, __exports__) {
"use strict";
var ActiveModelAdapter = __dependency1__.ActiveModelAdapter;
var ActiveModelSerializer = __dependency1__.ActiveModelSerializer;
__exports__.ActiveModelAdapter = ActiveModelAdapter;
__exports__.ActiveModelSerializer = ActiveModelSerializer;
});
define("activemodel-adapter/setup-container",
["ember-data/system/container_proxy","activemodel-adapter/system/active_model_serializer","activemodel-adapter/system/active_model_adapter","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var ContainerProxy = __dependency1__["default"];
var ActiveModelSerializer = __dependency2__["default"];
var ActiveModelAdapter = __dependency3__["default"];
__exports__["default"] = function setupActiveModelAdapter(container, application){
var proxy = new ContainerProxy(container);
proxy.registerDeprecations([
{ deprecated: 'serializer:_ams', valid: 'serializer:-active-model' },
{ deprecated: 'adapter:_ams', valid: 'adapter:-active-model' }
]);
container.register('serializer:-active-model', ActiveModelSerializer);
container.register('adapter:-active-model', ActiveModelAdapter);
};
});
define("activemodel-adapter/system",
["activemodel-adapter/system/active_model_adapter","activemodel-adapter/system/active_model_serializer","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var ActiveModelAdapter = __dependency1__["default"];
var ActiveModelSerializer = __dependency2__["default"];
__exports__.ActiveModelAdapter = ActiveModelAdapter;
__exports__.ActiveModelSerializer = ActiveModelSerializer;
});
define("activemodel-adapter/system/active_model_adapter",
["ember-data/adapters","ember-data/system/adapter","ember-inflector","activemodel-adapter/system/active_model_serializer","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
var RESTAdapter = __dependency1__.RESTAdapter;
var InvalidError = __dependency2__.InvalidError;
var pluralize = __dependency3__.pluralize;
var ActiveModelSerializer = __dependency4__["default"];
/**
@module ember-data
*/
var forEach = Ember.EnumerableUtils.forEach;
var decamelize = Ember.String.decamelize,
underscore = Ember.String.underscore;
/**
The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate
with a JSON API that uses an underscored naming convention instead of camelCasing.
It has been designed to work out of the box with the
[active_model_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem. This Adapter expects specific settings using ActiveModel::Serializers,
`embed :ids, include: true` which sideloads the records.
This adapter extends the DS.RESTAdapter by making consistent use of the camelization,
decamelization and pluralization methods to normalize the serialized JSON into a
format that is compatible with a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelAdapter expects the JSON returned from your server to follow
the REST adapter conventions substituting underscored keys for camelcased ones.
Unlike the DS.RESTAdapter, async relationship keys must be the singular form
of the relationship name, followed by "_id" for DS.belongsTo relationships,
or "_ids" for DS.hasMany relationships.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
Let's imagine that `Occupation` is just another model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.belongsTo('occupation')
});
App.Occupation = DS.Model.extend({
name: DS.attr('string'),
salary: DS.attr('number'),
people: DS.hasMany('person')
});
```
The JSON needed to avoid extra server calls, should look like this:
```js
{
"people": [{
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation_id": 1
}],
"occupations": [{
"id": 1,
"name": "President",
"salary": 100000,
"person_ids": [1]
}]
}
```
@class ActiveModelAdapter
@constructor
@namespace DS
@extends DS.RESTAdapter
**/
var ActiveModelAdapter = RESTAdapter.extend({
defaultSerializer: '-active-model',
/**
The ActiveModelAdapter overrides the `pathForType` method to build
underscored URLs by decamelizing and pluralizing the object type name.
```js
this.pathForType("famousPerson");
//=> "famous_people"
```
@method pathForType
@param {String} type
@return String
*/
pathForType: function(type) {
var decamelized = decamelize(type);
var underscored = underscore(decamelized);
return pluralize(underscored);
},
/**
The ActiveModelAdapter overrides the `ajaxError` method
to return a DS.InvalidError for all 422 Unprocessable Entity
responses.
A 422 HTTP response from the server generally implies that the request
was well formed but the API was unable to process it because the
content was not semantically correct or meaningful per the API.
For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918
https://tools.ietf.org/html/rfc4918#section-11.2
@method ajaxError
@param jqXHR
@return error
*/
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var response = Ember.$.parseJSON(jqXHR.responseText),
errors = {};
if (response.errors !== undefined) {
var jsonErrors = response.errors;
forEach(Ember.keys(jsonErrors), function(key) {
errors[Ember.String.camelize(key)] = jsonErrors[key];
});
}
return new InvalidError(errors);
} else {
return error;
}
}
});
__exports__["default"] = ActiveModelAdapter;
});
define("activemodel-adapter/system/active_model_serializer",
["ember-inflector","ember-data/serializers/rest_serializer","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var singularize = __dependency1__.singularize;
var RESTSerializer = __dependency2__["default"];
/**
@module ember-data
*/
var get = Ember.get,
forEach = Ember.EnumerableUtils.forEach,
camelize = Ember.String.camelize,
capitalize = Ember.String.capitalize,
decamelize = Ember.String.decamelize,
underscore = Ember.String.underscore;
/**
The ActiveModelSerializer is a subclass of the RESTSerializer designed to integrate
with a JSON API that uses an underscored naming convention instead of camelCasing.
It has been designed to work out of the box with the
[active_model_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem. This Serializer expects specific settings using ActiveModel::Serializers,
`embed :ids, include: true` which sideloads the records.
This serializer extends the DS.RESTSerializer by making consistent
use of the camelization, decamelization and pluralization methods to
normalize the serialized JSON into a format that is compatible with
a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelSerializer expects the JSON returned from your server
to follow the REST adapter conventions substituting underscored keys
for camelcased ones.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
Let's imagine that `Occupation` is just another model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.belongsTo('occupation')
});
App.Occupation = DS.Model.extend({
name: DS.attr('string'),
salary: DS.attr('number'),
people: DS.hasMany('person')
});
```
The JSON needed to avoid extra server calls, should look like this:
```js
{
"people": [{
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation_id": 1
}],
"occupations": [{
"id": 1,
"name": "President",
"salary": 100000,
"person_ids": [1]
}]
}
```
@class ActiveModelSerializer
@namespace DS
@extends DS.RESTSerializer
*/
var ActiveModelSerializer = RESTSerializer.extend({
// SERIALIZE
/**
Converts camelCased attributes to underscored when serializing.
@method keyForAttribute
@param {String} attribute
@return String
*/
keyForAttribute: function(attr) {
return decamelize(attr);
},
/**
Underscores relationship names and appends "_id" or "_ids" when serializing
relationship keys.
@method keyForRelationship
@param {String} key
@param {String} kind
@return String
*/
keyForRelationship: function(rawKey, kind) {
var key = decamelize(rawKey);
if (kind === "belongsTo") {
return key + "_id";
} else if (kind === "hasMany") {
return singularize(key) + "_ids";
} else {
return key;
}
},
/*
Does not serialize hasMany relationships by default.
*/
serializeHasMany: Ember.K,
/**
Underscores the JSON root keys when serializing.
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Model} record
@param {Object} options
*/
serializeIntoHash: function(data, type, record, options) {
var root = underscore(decamelize(type.typeKey));
data[root] = this.serialize(record, options);
},
/**
Serializes a polymorphic type as a fully capitalized model name.
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param relationship
*/
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key;
var belongsTo = get(record, key);
var jsonKey = underscore(key + "_type");
if (Ember.isNone(belongsTo)) {
json[jsonKey] = null;
} else {
json[jsonKey] = capitalize(camelize(belongsTo.constructor.typeKey));
}
},
// EXTRACT
/**
Add extra step to `DS.RESTSerializer.normalize` so links are normalized.
If your payload looks like:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flagged_comments": "api/comments/flagged" }
}
}
```
The normalized version would look like this
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flaggedComments": "api/comments/flagged" }
}
}
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@param {String} prop
@return Object
*/
normalize: function(type, hash, prop) {
this.normalizeLinks(hash);
return this._super(type, hash, prop);
},
/**
Convert `snake_cased` links to `camelCase`
@method normalizeLinks
@param {Object} data
*/
normalizeLinks: function(data){
if (data.links) {
var links = data.links;
for (var link in links) {
var camelizedLink = camelize(link);
if (camelizedLink !== link) {
links[camelizedLink] = links[link];
delete links[link];
}
}
}
},
/**
Normalize the polymorphic type from the JSON.
Normalize:
```js
{
id: "1"
minion: { type: "evil_minion", id: "12"}
}
```
To:
```js
{
id: "1"
minion: { type: "evilMinion", id: "12"}
}
```
@method normalizeRelationships
@private
*/
normalizeRelationships: function(type, hash) {
if (this.keyForRelationship) {
type.eachRelationship(function(key, relationship) {
var payloadKey, payload;
if (relationship.options.polymorphic) {
payloadKey = this.keyForAttribute(key);
payload = hash[payloadKey];
if (payload && payload.type) {
payload.type = this.typeForRoot(payload.type);
} else if (payload && relationship.kind === "hasMany") {
var self = this;
forEach(payload, function(single) {
single.type = self.typeForRoot(single.type);
});
}
} else {
payloadKey = this.keyForRelationship(key, relationship.kind);
if (!hash.hasOwnProperty(payloadKey)) { return; }
payload = hash[payloadKey];
}
hash[key] = payload;
if (key !== payloadKey) {
delete hash[payloadKey];
}
}, this);
}
}
});
__exports__["default"] = ActiveModelSerializer;
});
define("ember-data",
["ember-data/core","ember-data/ext/date","ember-data/system/store","ember-data/system/model","ember-data/system/changes","ember-data/system/adapter","ember-data/system/debug","ember-data/system/record_arrays","ember-data/system/record_array_manager","ember-data/adapters","ember-data/serializers/json_serializer","ember-data/serializers/rest_serializer","ember-inflector","ember-data/serializers/embedded_records_mixin","activemodel-adapter","ember-data/transforms","ember-data/system/relationships","ember-data/ember-initializer","ember-data/setup-container","ember-data/system/container_proxy","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __dependency16__, __dependency17__, __dependency18__, __dependency19__, __dependency20__, __exports__) {
"use strict";
/**
Ember Data
@module ember-data
@main ember-data
*/
// support RSVP 2.x via resolve, but prefer RSVP 3.x's Promise.cast
Ember.RSVP.Promise.cast = Ember.RSVP.Promise.cast || Ember.RSVP.resolve;
var DS = __dependency1__["default"];
var Store = __dependency3__.Store;
var PromiseArray = __dependency3__.PromiseArray;
var PromiseObject = __dependency3__.PromiseObject;
var Model = __dependency4__.Model;
var Errors = __dependency4__.Errors;
var RootState = __dependency4__.RootState;
var attr = __dependency4__.attr;
var AttributeChange = __dependency5__.AttributeChange;
var RelationshipChange = __dependency5__.RelationshipChange;
var RelationshipChangeAdd = __dependency5__.RelationshipChangeAdd;
var RelationshipChangeRemove = __dependency5__.RelationshipChangeRemove;
var OneToManyChange = __dependency5__.OneToManyChange;
var ManyToNoneChange = __dependency5__.ManyToNoneChange;
var OneToOneChange = __dependency5__.OneToOneChange;
var ManyToManyChange = __dependency5__.ManyToManyChange;
var InvalidError = __dependency6__.InvalidError;
var Adapter = __dependency6__.Adapter;
var DebugAdapter = __dependency7__["default"];
var RecordArray = __dependency8__.RecordArray;
var FilteredRecordArray = __dependency8__.FilteredRecordArray;
var AdapterPopulatedRecordArray = __dependency8__.AdapterPopulatedRecordArray;
var ManyArray = __dependency8__.ManyArray;
var RecordArrayManager = __dependency9__["default"];
var RESTAdapter = __dependency10__.RESTAdapter;
var FixtureAdapter = __dependency10__.FixtureAdapter;
var JSONSerializer = __dependency11__["default"];
var RESTSerializer = __dependency12__["default"];
var EmbeddedRecordsMixin = __dependency14__["default"];
var ActiveModelAdapter = __dependency15__.ActiveModelAdapter;
var ActiveModelSerializer = __dependency15__.ActiveModelSerializer;
var Transform = __dependency16__.Transform;
var DateTransform = __dependency16__.DateTransform;
var NumberTransform = __dependency16__.NumberTransform;
var StringTransform = __dependency16__.StringTransform;
var BooleanTransform = __dependency16__.BooleanTransform;
var hasMany = __dependency17__.hasMany;
var belongsTo = __dependency17__.belongsTo;
var setupContainer = __dependency19__["default"];
var ContainerProxy = __dependency20__["default"];
DS.Store = Store;
DS.PromiseArray = PromiseArray;
DS.PromiseObject = PromiseObject;
DS.Model = Model;
DS.RootState = RootState;
DS.attr = attr;
DS.Errors = Errors;
DS.AttributeChange = AttributeChange;
DS.RelationshipChange = RelationshipChange;
DS.RelationshipChangeAdd = RelationshipChangeAdd;
DS.OneToManyChange = OneToManyChange;
DS.ManyToNoneChange = OneToManyChange;
DS.OneToOneChange = OneToOneChange;
DS.ManyToManyChange = ManyToManyChange;
DS.Adapter = Adapter;
DS.InvalidError = InvalidError;
DS.DebugAdapter = DebugAdapter;
DS.RecordArray = RecordArray;
DS.FilteredRecordArray = FilteredRecordArray;
DS.AdapterPopulatedRecordArray = AdapterPopulatedRecordArray;
DS.ManyArray = ManyArray;
DS.RecordArrayManager = RecordArrayManager;
DS.RESTAdapter = RESTAdapter;
DS.FixtureAdapter = FixtureAdapter;
DS.RESTSerializer = RESTSerializer;
DS.JSONSerializer = JSONSerializer;
DS.Transform = Transform;
DS.DateTransform = DateTransform;
DS.StringTransform = StringTransform;
DS.NumberTransform = NumberTransform;
DS.BooleanTransform = BooleanTransform;
DS.ActiveModelAdapter = ActiveModelAdapter;
DS.ActiveModelSerializer = ActiveModelSerializer;
DS.EmbeddedRecordsMixin = EmbeddedRecordsMixin;
DS.belongsTo = belongsTo;
DS.hasMany = hasMany;
DS.ContainerProxy = ContainerProxy;
DS._setupContainer = setupContainer;
Ember.lookup.DS = DS;
__exports__["default"] = DS;
});
define("ember-data/adapters",
["ember-data/adapters/fixture_adapter","ember-data/adapters/rest_adapter","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/**
@module ember-data
*/
var FixtureAdapter = __dependency1__["default"];
var RESTAdapter = __dependency2__["default"];
__exports__.RESTAdapter = RESTAdapter;
__exports__.FixtureAdapter = FixtureAdapter;
});
define("ember-data/adapters/fixture_adapter",
["ember-data/system/adapter","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var get = Ember.get;
var fmt = Ember.String.fmt;
var indexOf = Ember.EnumerableUtils.indexOf;
var counter = 0;
var Adapter = __dependency1__["default"];
/**
`DS.FixtureAdapter` is an adapter that loads records from memory.
It's primarily used for development and testing. You can also use
`DS.FixtureAdapter` while working on the API but is not ready to
integrate yet. It is a fully functioning adapter. All CRUD methods
are implemented. You can also implement query logic that a remote
system would do. It's possible to develop your entire application
with `DS.FixtureAdapter`.
For information on how to use the `FixtureAdapter` in your
application please see the [FixtureAdapter
guide](/guides/models/the-fixture-adapter/).
@class FixtureAdapter
@namespace DS
@extends DS.Adapter
*/
__exports__["default"] = Adapter.extend({
// by default, fixtures are already in normalized form
serializer: null,
/**
If `simulateRemoteResponse` is `true` the `FixtureAdapter` will
wait a number of milliseconds before resolving promises with the
fixture values. The wait time can be configured via the `latency`
property.
@property simulateRemoteResponse
@type {Boolean}
@default true
*/
simulateRemoteResponse: true,
/**
By default the `FixtureAdapter` will simulate a wait of the
`latency` milliseconds before resolving promises with the fixture
values. This behavior can be turned off via the
`simulateRemoteResponse` property.
@property latency
@type {Number}
@default 50
*/
latency: 50,
/**
Implement this method in order to provide data associated with a type
@method fixturesForType
@param {Subclass of DS.Model} type
@return {Array}
*/
fixturesForType: function(type) {
if (type.FIXTURES) {
var fixtures = Ember.A(type.FIXTURES);
return fixtures.map(function(fixture){
var fixtureIdType = typeof fixture.id;
if(fixtureIdType !== "number" && fixtureIdType !== "string"){
throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [fixture]));
}
fixture.id = fixture.id + '';
return fixture;
});
}
return null;
},
/**
Implement this method in order to query fixtures data
@method queryFixtures
@param {Array} fixture
@param {Object} query
@param {Subclass of DS.Model} type
@return {Promise|Array}
*/
queryFixtures: function(fixtures, query, type) {
Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.');
},
/**
@method updateFixtures
@param {Subclass of DS.Model} type
@param {Array} fixture
*/
updateFixtures: function(type, fixture) {
if(!type.FIXTURES) {
type.FIXTURES = [];
}
var fixtures = type.FIXTURES;
this.deleteLoadedFixture(type, fixture);
fixtures.push(fixture);
},
/**
Implement this method in order to provide json for CRUD methods
@method mockJSON
@param {Subclass of DS.Model} type
@param {DS.Model} record
*/
mockJSON: function(store, type, record) {
return store.serializerFor(type).serialize(record, { includeId: true });
},
/**
@method generateIdForRecord
@param {DS.Store} store
@param {DS.Model} record
@return {String} id
*/
generateIdForRecord: function(store) {
return "fixture-" + counter++;
},
/**
@method find
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@return {Promise} promise
*/
find: function(store, type, id) {
var fixtures = this.fixturesForType(type);
var fixture;
Ember.assert("Unable to find fixtures for model type "+type.toString() +". If you're defining your fixtures using `Model.FIXTURES = ...`, please change it to `Model.reopenClass({ FIXTURES: ... })`.", fixtures);
if (fixtures) {
fixture = Ember.A(fixtures).findBy('id', id);
}
if (fixture) {
return this.simulateRemoteCall(function() {
return fixture;
}, this);
}
},
/**
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Array} ids
@return {Promise} promise
*/
findMany: function(store, type, ids) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
if (fixtures) {
fixtures = fixtures.filter(function(item) {
return indexOf(ids, item.id) !== -1;
});
}
if (fixtures) {
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
}
},
/**
@private
@method findAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: function(store, type) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
},
/**
@private
@method findQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} recordArray
@return {Promise} promise
*/
findQuery: function(store, type, query, array) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type " + type.toString(), fixtures);
fixtures = this.queryFixtures(fixtures, query, type);
if (fixtures) {
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
}
},
/**
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
createRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.updateFixtures(type, fixture);
return this.simulateRemoteCall(function() {
return fixture;
}, this);
},
/**
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
updateRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.updateFixtures(type, fixture);
return this.simulateRemoteCall(function() {
return fixture;
}, this);
},
/**
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
deleteRecord: function(store, type, record) {
this.deleteLoadedFixture(type, record);
return this.simulateRemoteCall(function() {
// no payload in a deletion
return null;
});
},
/*
@method deleteLoadedFixture
@private
@param type
@param record
*/
deleteLoadedFixture: function(type, record) {
var existingFixture = this.findExistingFixture(type, record);
if (existingFixture) {
var index = indexOf(type.FIXTURES, existingFixture);
type.FIXTURES.splice(index, 1);
return true;
}
},
/*
@method findExistingFixture
@private
@param type
@param record
*/
findExistingFixture: function(type, record) {
var fixtures = this.fixturesForType(type);
var id = get(record, 'id');
return this.findFixtureById(fixtures, id);
},
/*
@method findFixtureById
@private
@param fixtures
@param id
*/
findFixtureById: function(fixtures, id) {
return Ember.A(fixtures).find(function(r) {
if (''+get(r, 'id') === ''+id) {
return true;
} else {
return false;
}
});
},
/*
@method simulateRemoteCall
@private
@param callback
@param context
*/
simulateRemoteCall: function(callback, context) {
var adapter = this;
return new Ember.RSVP.Promise(function(resolve) {
if (get(adapter, 'simulateRemoteResponse')) {
// Schedule with setTimeout
Ember.run.later(function() {
resolve(callback.call(context));
}, get(adapter, 'latency'));
} else {
// Asynchronous, but at the of the runloop with zero latency
Ember.run.schedule('actions', null, function() {
resolve(callback.call(context));
});
}
}, "DS: FixtureAdapter#simulateRemoteCall");
}
});
});
define("ember-data/adapters/rest_adapter",
["ember-data/system/adapter","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var Adapter = __dependency1__["default"];
var get = Ember.get;
var forEach = Ember.ArrayPolyfills.forEach;
/**
The REST adapter allows your store to communicate with an HTTP server by
transmitting JSON via XHR. Most Ember.js apps that consume a JSON API
should use the REST adapter.
This adapter is designed around the idea that the JSON exchanged with
the server should be conventional.
## JSON Structure
The REST adapter expects the JSON returned from your server to follow
these conventions.
### Object Root
The JSON payload should be an object that contains the record inside a
root property. For example, in response to a `GET` request for
`/posts/1`, the JSON should look like this:
```js
{
"post": {
"id": 1,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz"
}
}
```
Similarly, in response to a `GET` request for `/posts`, the JSON should
look like this:
```js
{
"posts": [
{
"id": 1,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz"
},
{
"id": 2,
"title": "Rails is omakase",
"author": "D2H"
}
]
}
```
### Conventional Names
Attribute names in your JSON payload should be the camelCased versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"person": {
"id": 5,
"firstName": "Barack",
"lastName": "Obama",
"occupation": "President"
}
}
```
## Customization
### Endpoint path customization
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```js
DS.RESTAdapter.reopen({
namespace: 'api/1'
});
```
Requests for `App.Person` would now target `/api/1/people/1`.
### Host customization
An adapter can target other hosts by setting the `host` property.
```js
DS.RESTAdapter.reopen({
host: 'https://api.example.com'
});
```
### Headers customization
Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary
headers can be set as key/value pairs on the `RESTAdapter`'s `headers`
object and Ember Data will send them along with each ajax request.
```js
App.ApplicationAdapter = DS.RESTAdapter.extend({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
`headers` can also be used as a computed property to support dynamic
headers. In the example below, the `session` object has been
injected into an adapter by Ember's container.
```js
App.ApplicationAdapter = DS.RESTAdapter.extend({
headers: function() {
return {
"API_KEY": this.get("session.authToken"),
"ANOTHER_HEADER": "Some header value"
};
}.property("session.authToken")
});
```
In some cases, your dynamic headers may require data from some
object outside of Ember's observer system (for example
`document.cookie`). You can use the
[volatile](/api/classes/Ember.ComputedProperty.html#method_volatile)
function to set the property into a non-cached mode causing the headers to
be recomputed with every request.
```js
App.ApplicationAdapter = DS.RESTAdapter.extend({
headers: function() {
return {
"API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"),
"ANOTHER_HEADER": "Some header value"
};
}.property().volatile()
});
```
@class RESTAdapter
@constructor
@namespace DS
@extends DS.Adapter
*/
__exports__["default"] = Adapter.extend({
defaultSerializer: '-rest',
/**
By default the RESTAdapter will send each find request coming from a `store.find`
or from accessing a relationship separately to the server. If your server supports passing
ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests
within a single runloop.
For example, if you have an initial payload of
```javascript
post: {
id:1,
comments: [1,2]
}
```
By default calling `post.get('comments')` will trigger the following requests(assuming the
comments haven't been loaded before):
```
GET /comments/1
GET /comments/2
```
If you set coalesceFindRequests to `true` it will instead trigger the following request:
```
GET /comments?ids[]=1&ids[]=2
```
Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo`
relationships accessed within the same runloop. If you set `coalesceFindRequests: true`
```javascript
store.find('comment', 1);
store.find('comment', 2);
```
will also send a request to: `GET /comments?ids[]=1&ids[]=2`
@property coalesceFindRequests
@type {boolean}
*/
coalesceFindRequests: false,
/**
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```javascript
DS.RESTAdapter.reopen({
namespace: 'api/1'
});
```
Requests for `App.Post` would now target `/api/1/post/`.
@property namespace
@type {String}
*/
/**
An adapter can target other hosts by setting the `host` property.
```javascript
DS.RESTAdapter.reopen({
host: 'https://api.example.com'
});
```
Requests for `App.Post` would now target `https://api.example.com/post/`.
@property host
@type {String}
*/
/**
Some APIs require HTTP headers, e.g. to provide an API
key. Arbitrary headers can be set as key/value pairs on the
`RESTAdapter`'s `headers` object and Ember Data will send them
along with each ajax request. For dynamic headers see [headers
customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization).
```javascript
App.ApplicationAdapter = DS.RESTAdapter.extend({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
@property headers
@type {Object}
*/
/**
Called by the store in order to fetch the JSON for a given
type and ID.
The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
This method performs an HTTP `GET` request with the id provided as part of the query string.
@method find
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@param {DS.Model} record
@return {Promise} promise
*/
find: function(store, type, id, record) {
return this.ajax(this.buildURL(type.typeKey, id, record), 'GET');
},
/**
Called by the store in order to fetch a JSON array for all
of the records for a given type.
The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@private
@method findAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: function(store, type, sinceToken) {
var query;
if (sinceToken) {
query = { since: sinceToken };
}
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
},
/**
Called by the store in order to fetch a JSON array for
the records that match a particular query.
The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
The `query` argument is a simple JavaScript object that will be passed directly
to the server as parameters.
@private
@method findQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@return {Promise} promise
*/
findQuery: function(store, type, query) {
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
},
/**
Called by the store in order to fetch several records together if `coalesceFindRequests` is true
For example, if the original payload looks like:
```js
{
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2, 3 ]
}
```
The IDs will be passed as a URL-encoded Array of IDs, in this form:
```
ids[]=1&ids[]=2&ids[]=3
```
Many servers, such as Rails and PHP, will automatically convert this URL-encoded array
into an Array for you on the server-side. If you want to encode the
IDs, differently, just override this (one-line) method.
The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Array} ids
@param {Array} records
@return {Promise} promise
*/
findMany: function(store, type, ids, records) {
return this.ajax(this.buildURL(type.typeKey, ids, records), 'GET', { data: { ids: ids } });
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a has-many relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "comments": "/posts/1/comments" }
}
}
```
This method will be called with the parent record and `/posts/1/comments`.
The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL.
If the URL is host-relative (starting with a single slash), the
request will use the host specified on the adapter (if any).
@method findHasMany
@param {DS.Store} store
@param {DS.Model} record
@param {String} url
@return {Promise} promise
*/
findHasMany: function(store, record, url) {
var host = get(this, 'host');
var id = get(record, 'id');
var type = record.constructor.typeKey;
if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') {
url = host + url;
}
return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET');
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a belongs-to relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"person": {
"id": 1,
"name": "Tom Dale",
"links": { "group": "/people/1/group" }
}
}
```
This method will be called with the parent record and `/people/1/group`.
The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL.
@method findBelongsTo
@param {DS.Store} store
@param {DS.Model} record
@param {String} url
@return {Promise} promise
*/
findBelongsTo: function(store, record, url) {
var id = get(record, 'id');
var type = record.constructor.typeKey;
return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET');
},
/**
Called by the store when a newly created record is
saved via the `save` method on a model record instance.
The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
createRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record, { includeId: true });
return this.ajax(this.buildURL(type.typeKey, null, record), "POST", { data: data });
},
/**
Called by the store when an existing record is saved
via the `save` method on a model record instance.
The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var id = get(record, 'id');
return this.ajax(this.buildURL(type.typeKey, id, record), "PUT", { data: data });
},
/**
Called by the store when a record is deleted.
The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`.
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
deleteRecord: function(store, type, record) {
var id = get(record, 'id');
return this.ajax(this.buildURL(type.typeKey, id, record), "DELETE");
},
/**
Builds a URL for a given type and optional ID.
By default, it pluralizes the type's name (for example, 'post'
becomes 'posts' and 'person' becomes 'people'). To override the
pluralization see [pathForType](#method_pathForType).
If an ID is specified, it adds the ID to the path generated
for the type, separated by a `/`.
@method buildURL
@param {String} type
@param {String} id
@param {DS.Model} record
@return {String} url
*/
buildURL: function(type, id, record) {
var url = [],
host = get(this, 'host'),
prefix = this.urlPrefix();
if (type) { url.push(this.pathForType(type)); }
//We might get passed in an array of ids from findMany
//in which case we don't want to modify the url, as the
//ids will be passed in through a query param
if (id && !Ember.isArray(id)) { url.push(id); }
if (prefix) { url.unshift(prefix); }
url = url.join('/');
if (!host && url) { url = '/' + url; }
return url;
},
/**
@method urlPrefix
@private
@param {String} path
@param {String} parentUrl
@return {String} urlPrefix
*/
urlPrefix: function(path, parentURL) {
var host = get(this, 'host');
var namespace = get(this, 'namespace');
var url = [];
if (path) {
// Absolute path
if (path.charAt(0) === '/') {
if (host) {
path = path.slice(1);
url.push(host);
}
// Relative path
} else if (!/^http(s)?:\/\//.test(path)) {
url.push(parentURL);
}
} else {
if (host) { url.push(host); }
if (namespace) { url.push(namespace); }
}
if (path) {
url.push(path);
}
return url.join('/');
},
_stripIDFromURL: function(store, record) {
var type = store.modelFor(record);
var url = this.buildURL(type.typeKey, record.get('id'), record);
var expandedURL = url.split('/');
//Case when the url is of the format ...something/:id
var lastSegment = expandedURL[ expandedURL.length - 1 ];
var id = record.get('id');
if (lastSegment === id) {
expandedURL[expandedURL.length - 1] = "";
} else if(endsWith(lastSegment, '?id=' + id)) {
//Case when the url is of the format ...something?id=:id
expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1);
}
return expandedURL.join('/');
},
/**
Organize records into groups, each of which is to be passed to separate
calls to `findMany`.
This implementation groups together records that have the same base URL but
differing ids. For example `/comments/1` and `/comments/2` will be grouped together
because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2`
It also supports urls where ids are passed as a query param, such as `/comments?id=1`
but not those where there is more than 1 query param such as `/comments?id=2&name=David`
Currently only the query param of `id` is supported. If you need to support others, please
override this or the `_stripIDFromURL` method.
It does not group records that have differing base urls, such as for example: `/posts/1/comments/2`
and `/posts/2/comments/3`
@method groupRecordsForFindMany
@param {Array} records
@return {Array} an array of arrays of records, each of which is to be
loaded separately by `findMany`.
*/
groupRecordsForFindMany: function (store, records) {
var groups = Ember.MapWithDefault.create({defaultValue: function(){return [];}});
var adapter = this;
forEach.call(records, function(record){
var baseUrl = adapter._stripIDFromURL(store, record);
groups.get(baseUrl).push(record);
});
function splitGroupToFitInUrl(group, maxUrlLength) {
var baseUrl = adapter._stripIDFromURL(store, group[0]);
var idsSize = 0;
var splitGroups = [[]];
forEach.call(group, function(record) {
var additionalLength = '&ids[]='.length + record.get('id.length');
if (baseUrl.length + idsSize + additionalLength >= maxUrlLength) {
idsSize = 0;
splitGroups.push([]);
}
idsSize += additionalLength;
var lastGroupIndex = splitGroups.length - 1;
splitGroups[lastGroupIndex].push(record);
});
return splitGroups;
}
var groupsArray = [];
groups.forEach(function(key, group){
// http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers
var maxUrlLength = 2048;
var splitGroups = splitGroupToFitInUrl(group, maxUrlLength);
forEach.call(splitGroups, function(splitGroup) {
groupsArray.push(splitGroup);
});
});
return groupsArray;
},
/**
Determines the pathname for a given type.
By default, it pluralizes the type's name (for example,
'post' becomes 'posts' and 'person' becomes 'people').
### Pathname customization
For example if you have an object LineItem with an
endpoint of "/line_items/".
```js
App.ApplicationAdapter = DS.RESTAdapter.extend({
pathForType: function(type) {
var decamelized = Ember.String.decamelize(type);
return Ember.String.pluralize(decamelized);
}
});
```
@method pathForType
@param {String} type
@return {String} path
**/
pathForType: function(type) {
var camelized = Ember.String.camelize(type);
return Ember.String.pluralize(camelized);
},
/**
Takes an ajax response, and returns a relevant error.
Returning a `DS.InvalidError` from this method will cause the
record to transition into the `invalid` state and make the
`errors` object available on the record.
```javascript
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"];
return new DS.InvalidError(jsonErrors);
} else {
return error;
}
}
});
```
Note: As a correctness optimization, the default implementation of
the `ajaxError` method strips out the `then` method from jquery's
ajax response (jqXHR). This is important because the jqXHR's
`then` method fulfills the promise with itself resulting in a
circular "thenable" chain which may cause problems for some
promise libraries.
@method ajaxError
@param {Object} jqXHR
@return {Object} jqXHR
*/
ajaxError: function(jqXHR) {
if (jqXHR && typeof jqXHR === 'object') {
jqXHR.then = null;
}
return jqXHR;
},
/**
Takes a URL, an HTTP method and a hash of data, and makes an
HTTP request.
When the server responds with a payload, Ember Data will call into `extractSingle`
or `extractArray` (depending on whether the original query was for one record or
many records).
By default, `ajax` method has the following behavior:
* It sets the response `dataType` to `"json"`
* If the HTTP method is not `"GET"`, it sets the `Content-Type` to be
`application/json; charset=utf-8`
* If the HTTP method is not `"GET"`, it stringifies the data passed in. The
data is the serialized record in the case of a save.
* Registers success and failure handlers.
@method ajax
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} hash
@return {Promise} promise
*/
ajax: function(url, type, options) {
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var hash = adapter.ajaxOptions(url, type, options);
hash.success = function(json) {
Ember.run(null, resolve, json);
};
hash.error = function(jqXHR, textStatus, errorThrown) {
Ember.run(null, reject, adapter.ajaxError(jqXHR));
};
Ember.$.ajax(hash);
}, "DS: RESTAdapter#ajax " + type + " to " + url);
},
/**
@method ajaxOptions
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} hash
@return {Object} hash
*/
ajaxOptions: function(url, type, options) {
var hash = options || {};
hash.url = url;
hash.type = type;
hash.dataType = 'json';
hash.context = this;
if (hash.data && type !== 'GET') {
hash.contentType = 'application/json; charset=utf-8';
hash.data = JSON.stringify(hash.data);
}
var headers = get(this, 'headers');
if (headers !== undefined) {
hash.beforeSend = function (xhr) {
forEach.call(Ember.keys(headers), function(key) {
xhr.setRequestHeader(key, headers[key]);
});
};
}
return hash;
}
});
//From http://stackoverflow.com/questions/280634/endswith-in-javascript
function endsWith(string, suffix){
if (typeof String.prototype.endsWith !== 'function') {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
} else {
return string.endsWith(suffix);
}
}
});
define("ember-data/core",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
/**
All Ember Data methods and functions are defined inside of this namespace.
@class DS
@static
*/
var DS;
if ('undefined' === typeof DS) {
/**
@property VERSION
@type String
@default '1.0.0-beta.9'
@static
*/
DS = Ember.Namespace.create({
VERSION: '1.0.0-beta.9'
});
if (Ember.libraries) {
Ember.libraries.registerCoreLibrary('Ember Data', DS.VERSION);
}
}
__exports__["default"] = DS;
});
define("ember-data/ember-initializer",
["ember-data/setup-container"],
function(__dependency1__) {
"use strict";
var setupContainer = __dependency1__["default"];
var K = Ember.K;
/**
@module ember-data
*/
/*
This code initializes Ember-Data onto an Ember application.
If an Ember.js developer defines a subclass of DS.Store on their application,
as `App.ApplicationStore` (or via a module system that resolves to `store:application`)
this code will automatically instantiate it and make it available on the
router.
Additionally, after an application's controllers have been injected, they will
each have the store made available to them.
For example, imagine an Ember.js application with the following classes:
App.ApplicationStore = DS.Store.extend({
adapter: 'custom'
});
App.PostsController = Ember.ArrayController.extend({
// ...
});
When the application is initialized, `App.ApplicationStore` will automatically be
instantiated, and the instance of `App.PostsController` will have its `store`
property set to that instance.
Note that this code will only be run if the `ember-application` package is
loaded. If Ember Data is being used in an environment other than a
typical application (e.g., node.js where only `ember-runtime` is available),
this code will be ignored.
*/
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer({
name: "ember-data",
initialize: setupContainer
});
// Deprecated initializers to satisfy old code that depended on them
Application.initializer({
name: "store",
after: "ember-data",
initialize: K
});
Application.initializer({
name: "activeModelAdapter",
before: "store",
initialize: K
});
Application.initializer({
name: "transforms",
before: "store",
initialize: K
});
Application.initializer({
name: "data-adapter",
before: "store",
initialize: K
});
Application.initializer({
name: "injectStore",
before: "store",
initialize: K
});
});
});
define("ember-data/ext/date",
[],
function() {
"use strict";
/**
@module ember-data
*/
/**
Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
© 2011 Colin Snover <http://zetafleet.com>
Released under MIT license.
@class Date
@namespace Ember
@static
*/
Ember.Date = Ember.Date || {};
var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ];
/**
@method parse
@param date
*/
Ember.Date.parse = function (date) {
var timestamp, struct, minutesOffset = 0;
// ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
// before falling back to any implementation-specific date parsing, so that’s what we do, even if native
// implementations could be faster
// 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) {
// avoid NaN timestamps caused by “undefined” values being passed to Date.UTC
for (var i = 0, k; (k = numericKeys[i]); ++i) {
struct[k] = +struct[k] || 0;
}
// allow undefined days and months
struct[2] = (+struct[2] || 1) - 1;
struct[3] = +struct[3] || 1;
if (struct[8] !== 'Z' && struct[9] !== undefined) {
minutesOffset = struct[10] * 60 + struct[11];
if (struct[9] === '+') {
minutesOffset = 0 - minutesOffset;
}
}
timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
}
else {
timestamp = origParse ? origParse(date) : NaN;
}
return timestamp;
};
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) {
Date.parse = Ember.Date.parse;
}
});
define("ember-data/initializers/data_adapter",
["ember-data/system/debug/debug_adapter","exports"],
function(__dependency1__, __exports__) {
"use strict";
var DebugAdapter = __dependency1__["default"];
/**
Configures a container with injections on Ember applications
for the Ember-Data store. Accepts an optional namespace argument.
@method initializeStoreInjections
@param {Ember.Container} container
*/
__exports__["default"] = function initializeDebugAdapter(container){
container.register('data-adapter:main', DebugAdapter);
};
});
define("ember-data/initializers/store",
["ember-data/serializers","ember-data/adapters","ember-data/system/container_proxy","ember-data/system/store","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
var JSONSerializer = __dependency1__.JSONSerializer;
var RESTSerializer = __dependency1__.RESTSerializer;
var RESTAdapter = __dependency2__.RESTAdapter;
var ContainerProxy = __dependency3__["default"];
var Store = __dependency4__["default"];
/**
Configures a container for use with an Ember-Data
store. Accepts an optional namespace argument.
@method initializeStore
@param {Ember.Container} container
@param {Object} [application] an application namespace
*/
__exports__["default"] = function initializeStore(container, application){
Ember.deprecate('Specifying a custom Store for Ember Data on your global namespace as `App.Store` ' +
'has been deprecated. Please use `App.ApplicationStore` instead.', !(application && application.Store));
container.register('store:main', container.lookupFactory('store:application') || (application && application.Store) || Store);
// allow older names to be looked up
var proxy = new ContainerProxy(container);
proxy.registerDeprecations([
{ deprecated: 'serializer:_default', valid: 'serializer:-default' },
{ deprecated: 'serializer:_rest', valid: 'serializer:-rest' },
{ deprecated: 'adapter:_rest', valid: 'adapter:-rest' }
]);
// new go forward paths
container.register('serializer:-default', JSONSerializer);
container.register('serializer:-rest', RESTSerializer);
container.register('adapter:-rest', RESTAdapter);
// Eagerly generate the store so defaultStore is populated.
// TODO: Do this in a finisher hook
container.lookup('store:main');
};
});
define("ember-data/initializers/store_injections",
["exports"],
function(__exports__) {
"use strict";
/**
Configures a container with injections on Ember applications
for the Ember-Data store. Accepts an optional namespace argument.
@method initializeStoreInjections
@param {Ember.Container} container
*/
__exports__["default"] = function initializeStoreInjections(container){
container.injection('controller', 'store', 'store:main');
container.injection('route', 'store', 'store:main');
container.injection('serializer', 'store', 'store:main');
container.injection('data-adapter', 'store', 'store:main');
};
});
define("ember-data/initializers/transforms",
["ember-data/transforms","exports"],
function(__dependency1__, __exports__) {
"use strict";
var BooleanTransform = __dependency1__.BooleanTransform;
var DateTransform = __dependency1__.DateTransform;
var StringTransform = __dependency1__.StringTransform;
var NumberTransform = __dependency1__.NumberTransform;
/**
Configures a container for use with Ember-Data
transforms.
@method initializeTransforms
@param {Ember.Container} container
*/
__exports__["default"] = function initializeTransforms(container){
container.register('transform:boolean', BooleanTransform);
container.register('transform:date', DateTransform);
container.register('transform:number', NumberTransform);
container.register('transform:string', StringTransform);
};
});
define("ember-data/serializers",
["ember-data/serializers/json_serializer","ember-data/serializers/rest_serializer","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var JSONSerializer = __dependency1__["default"];
var RESTSerializer = __dependency2__["default"];
__exports__.JSONSerializer = JSONSerializer;
__exports__.RESTSerializer = RESTSerializer;
});
define("ember-data/serializers/embedded_records_mixin",
["ember-inflector","exports"],
function(__dependency1__, __exports__) {
"use strict";
var get = Ember.get;
var forEach = Ember.EnumerableUtils.forEach;
var camelize = Ember.String.camelize;
var pluralize = __dependency1__.pluralize;
/**
## Using Embedded Records
`DS.EmbeddedRecordsMixin` supports serializing embedded records.
To set up embedded records, include the mixin when extending a serializer
then define and configure embedded (model) relationships.
Below is an example of a per-type serializer ('post' type).
```js
App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
author: {embedded: 'always'},
comments: {serialize: 'ids'}
}
})
```
The `attrs` option for a resource `{embedded: 'always'}` is shorthand for:
```js
{serialize: 'records', deserialize: 'records'}
```
### Configuring Attrs
A resource's `attrs` option may be set to use `ids`, `records` or false for the
`serialize` and `deserialize` settings.
The `attrs` property can be set on the ApplicationSerializer or a per-type
serializer.
In the case where embedded JSON is expected while extracting a payload (reading)
the setting is `deserialize: 'records'`, there is no need to use `ids` when
extracting as that is the default behavior without this mixin if you are using
the vanilla EmbeddedRecordsMixin. Likewise, to embed JSON in the payload while
serializing `serialize: 'records'` is the setting to use. There is an option of
not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you
do not want the relationship sent at all, you can use `serialize: false`.
### EmbeddedRecordsMixin defaults
If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin`
will behave in the following way:
BelongsTo: `{serialize:'id', deserialize:'id'}`
HasMany: `{serialize:false, deserialize:'ids'}`
### Model Relationships
Embedded records must have a model defined to be extracted and serialized.
To successfully extract and serialize embedded records the model relationships
must be setup correcty See the
[defining relationships](/guides/models/defining-models/#toc_defining-relationships)
section of the **Defining Models** guide page.
Records without an `id` property are not considered embedded records, model
instances must have an `id` property to be used with Ember Data.
### Example JSON payloads, Models and Serializers
**When customizing a serializer it is imporant to grok what the cusomizations
are, please read the docs for the methods this mixin provides, in case you need
to modify to fit your specific needs.**
For example review the docs for each method of this mixin:
* [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize)
* [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo)
* [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany)
@class EmbeddedRecordsMixin
@namespace DS
*/
var EmbeddedRecordsMixin = Ember.Mixin.create({
/**
Normalize the record and recursively normalize/extract all the embedded records
while pushing them into the store as they are encountered
A payload with an attr configured for embedded records needs to be extracted:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
}
}
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash to be normalized
@param {String} key the hash has been referenced by
@return {Object} the normalized hash
**/
normalize: function(type, hash, prop) {
var normalizedHash = this._super(type, hash, prop);
return extractEmbeddedRecords(this, this.store, type, normalizedHash);
},
keyForRelationship: function(key, type){
if (this.hasDeserializeRecordsOption(key)) {
return this.keyForAttribute(key);
} else {
return this._super(key, type) || key;
}
},
/**
Serialize `belongsTo` relationship when it is configured as an embedded object.
This example of an author model belongs to a post model:
```js
Post = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
author: DS.belongsTo('author')
});
Author = DS.Model.extend({
name: DS.attr('string'),
post: DS.belongsTo('post')
});
```
Use a custom (type) serializer for the post model to configure embedded author
```js
App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
author: {embedded: 'always'}
}
})
```
A payload with an attribute configured for embedded records can serialize
the records together under the root attribute's payload:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"author": {
"id": "2"
"name": "dhh"
}
}
}
```
@method serializeBelongsTo
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function(record, json, relationship) {
var attr = relationship.key;
var attrs = this.get('attrs');
if (this.noSerializeOptionSpecified(attr)) {
this._super(record, json, relationship);
return;
}
var includeIds = this.hasSerializeIdsOption(attr);
var includeRecords = this.hasSerializeRecordsOption(attr);
var embeddedRecord = record.get(attr);
var key;
if (includeIds) {
key = this.keyForRelationship(attr, relationship.kind);
if (!embeddedRecord) {
json[key] = null;
} else {
json[key] = get(embeddedRecord, 'id');
}
} else if (includeRecords) {
key = this.keyForAttribute(attr);
if (!embeddedRecord) {
json[key] = null;
} else {
json[key] = embeddedRecord.serialize({includeId: true});
this.removeEmbeddedForeignKey(record, embeddedRecord, relationship, json[key]);
}
}
},
/**
Serialize `hasMany` relationship when it is configured as embedded objects.
This example of a post model has many comments:
```js
Post = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
comments: DS.hasMany('comment')
});
Comment = DS.Model.extend({
body: DS.attr('string'),
post: DS.belongsTo('post')
});
```
Use a custom (type) serializer for the post model to configure embedded comments
```js
App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {embedded: 'always'}
}
})
```
A payload with an attribute configured for embedded records can serialize
the records together under the root attribute's payload:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"body": "I want this for my ORM, I want that for my template language..."
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
}
}
```
The attrs options object can use more specific instruction for extracting and
serializing. When serializing, an option to embed `ids` or `records` can be set.
When extracting the only option is `records`.
So `{embedded: 'always'}` is shorthand for:
`{serialize: 'records', deserialize: 'records'}`
To embed the `ids` for a related object (using a hasMany relationship):
```js
App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {serialize: 'ids', deserialize: 'records'}
}
})
```
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"body": "I want this for my ORM, I want that for my template language..."
"comments": ["1", "2"]
}
}
```
@method serializeHasMany
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function(record, json, relationship) {
var attr = relationship.key;
var attrs = this.get('attrs');
if (this.noSerializeOptionSpecified(attr)) {
this._super(record, json, relationship);
return;
}
var includeIds = this.hasSerializeIdsOption(attr);
var includeRecords = this.hasSerializeRecordsOption(attr);
var key;
if (includeIds) {
key = this.keyForRelationship(attr, relationship.kind);
json[key] = get(record, attr).mapBy('id');
} else if (includeRecords) {
key = this.keyForAttribute(attr);
json[key] = get(record, attr).map(function(embeddedRecord) {
var serializedEmbeddedRecord = embeddedRecord.serialize({includeId: true});
this.removeEmbeddedForeignKey(record, embeddedRecord, relationship, serializedEmbeddedRecord);
return serializedEmbeddedRecord;
}, this);
}
},
/**
When serializing an embedded record, modify the property (in the json payload)
that refers to the parent record (foreign key for relationship).
Serializing a `belongsTo` relationship removes the property that refers to the
parent record
Serializing a `hasMany` relationship does not remove the property that refers to
the parent record.
@method removeEmbeddedForeignKey
@param {DS.Model} record
@param {DS.Model} embeddedRecord
@param {Object} relationship
@param {Object} json
*/
removeEmbeddedForeignKey: function (record, embeddedRecord, relationship, json) {
if (relationship.kind === 'hasMany') {
return;
} else if (relationship.kind === 'belongsTo') {
var parentRecord = record.constructor.inverseFor(relationship.key);
if (parentRecord) {
var name = parentRecord.name;
var embeddedSerializer = this.store.serializerFor(embeddedRecord.constructor);
var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind);
if (parentKey) {
delete json[parentKey];
}
}
}
},
// checks config for attrs option to embedded (always) - serialize and deserialize
hasEmbeddedAlwaysOption: function (attr) {
var option = this.attrsOption(attr);
return option && option.embedded === 'always';
},
// checks config for attrs option to serialize ids
hasSerializeRecordsOption: function(attr) {
var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
var option = this.attrsOption(attr);
return alwaysEmbed || (option && (option.serialize === 'records'));
},
// checks config for attrs option to serialize records
hasSerializeIdsOption: function(attr) {
var option = this.attrsOption(attr);
return option && (option.serialize === 'ids' || option.serialize === 'id');
},
// checks config for attrs option to serialize records
noSerializeOptionSpecified: function(attr) {
var option = this.attrsOption(attr);
var serializeRecords = this.hasSerializeRecordsOption(attr);
var serializeIds = this.hasSerializeIdsOption(attr);
return !(option && (option.serialize || option.embedded));
},
// checks config for attrs option to deserialize records
// a defined option object for a resource is treated the same as
// `deserialize: 'records'`
hasDeserializeRecordsOption: function(attr) {
var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
var option = this.attrsOption(attr);
return alwaysEmbed || (option && option.deserialize === 'records');
},
attrsOption: function(attr) {
var attrs = this.get('attrs');
return attrs && (attrs[camelize(attr)] || attrs[attr]);
}
});
// chooses a relationship kind to branch which function is used to update payload
// does not change payload if attr is not embedded
function extractEmbeddedRecords(serializer, store, type, partial) {
type.eachRelationship(function(key, relationship) {
if (serializer.hasDeserializeRecordsOption(key)) {
var embeddedType = store.modelFor(relationship.type.typeKey);
if (relationship.kind === "hasMany") {
extractEmbeddedHasMany(store, key, embeddedType, partial);
}
if (relationship.kind === "belongsTo") {
extractEmbeddedBelongsTo(store, key, embeddedType, partial);
}
}
});
return partial;
}
// handles embedding for `hasMany` relationship
function extractEmbeddedHasMany(store, key, embeddedType, hash) {
if (!hash[key]) {
return hash;
}
var ids = [];
var embeddedSerializer = store.serializerFor(embeddedType.typeKey);
forEach(hash[key], function(data) {
var embeddedRecord = embeddedSerializer.normalize(embeddedType, data, null);
store.push(embeddedType, embeddedRecord);
ids.push(embeddedRecord.id);
});
hash[key] = ids;
return hash;
}
function extractEmbeddedBelongsTo(store, key, embeddedType, hash) {
if (!hash[key]) {
return hash;
}
var embeddedSerializer = store.serializerFor(embeddedType.typeKey);
var embeddedRecord = embeddedSerializer.normalize(embeddedType, hash[key], null);
store.push(embeddedType, embeddedRecord);
hash[key] = embeddedRecord.id;
//TODO Need to add a reference to the parent later so relationship works between both `belongsTo` records
return hash;
}
__exports__["default"] = EmbeddedRecordsMixin;
});
define("ember-data/serializers/json_serializer",
["ember-data/system/changes","exports"],
function(__dependency1__, __exports__) {
"use strict";
var RelationshipChange = __dependency1__.RelationshipChange;
var get = Ember.get;
var set = Ember.set;
var isNone = Ember.isNone;
var map = Ember.ArrayPolyfills.map;
var merge = Ember.merge;
/**
In Ember Data a Serializer is used to serialize and deserialize
records when they are transferred in and out of an external source.
This process involves normalizing property names, transforming
attribute values and serializing relationships.
For maximum performance Ember Data recommends you use the
[RESTSerializer](DS.RESTSerializer.html) or one of its subclasses.
`JSONSerializer` is useful for simpler or legacy backends that may
not support the http://jsonapi.org/ spec.
@class JSONSerializer
@namespace DS
*/
__exports__["default"] = Ember.Object.extend({
/**
The primaryKey is used when serializing and deserializing
data. Ember Data always uses the `id` property to store the id of
the record. The external source may not always follow this
convention. In these cases it is useful to override the
primaryKey property to match the primaryKey of your external
store.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
primaryKey: '_id'
});
```
@property primaryKey
@type {String}
@default 'id'
*/
primaryKey: 'id',
/**
The `attrs` object can be used to declare a simple mapping between
property names on `DS.Model` records and payload keys in the
serialized JSON object representing the record. An object with the
property `key` can also be used to designate the attribute's key on
the response payload.
Example
```javascript
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string'),
admin: DS.attr('boolean')
});
App.PersonSerializer = DS.JSONSerializer.extend({
attrs: {
admin: 'is_admin',
occupation: {key: 'career'}
}
});
```
You can also remove attributes by setting the `serialize` key to
false in your mapping object.
Example
```javascript
App.PersonSerializer = DS.JSONSerializer.extend({
attrs: {
admin: {serialize: false},
occupation: {key: 'career'}
}
});
```
When serialized:
```javascript
{
"career": "magician"
}
```
Note that the `admin` is now not included in the payload.
@property attrs
@type {Object}
*/
/**
Given a subclass of `DS.Model` and a JSON object this method will
iterate through each attribute of the `DS.Model` and invoke the
`DS.Transform#deserialize` method on the matching property of the
JSON object. This method is typically called after the
serializer's `normalize` method.
@method applyTransforms
@private
@param {subclass of DS.Model} type
@param {Object} data The data to transform
@return {Object} data The transformed data object
*/
applyTransforms: function(type, data) {
type.eachTransformedAttribute(function(key, type) {
if (!data.hasOwnProperty(key)) { return; }
var transform = this.transformFor(type);
data[key] = transform.deserialize(data[key]);
}, this);
return data;
},
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
normalize: function(type, hash) {
var fields = Ember.get(type, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@return {Object}
*/
normalize: function(type, hash) {
if (!hash) { return hash; }
this.normalizeId(hash);
this.normalizeAttributes(type, hash);
this.normalizeRelationships(type, hash);
this.normalizeUsingDeclaredMapping(type, hash);
this.applyTransforms(type, hash);
return hash;
},
/**
You can use this method to normalize all payloads, regardless of whether they
represent single records or an array.
For example, you might want to remove some extraneous data from the payload:
```js
App.ApplicationSerializer = DS.JSONSerializer.extend({
normalizePayload: function(payload) {
delete payload.version;
delete payload.status;
return payload;
}
});
```
@method normalizePayload
@param {Object} payload
@return {Object} the normalized payload
*/
normalizePayload: function(payload) {
return payload;
},
/**
@method normalizeAttributes
@private
*/
normalizeAttributes: function(type, hash) {
var payloadKey, key;
if (this.keyForAttribute) {
type.eachAttribute(function(key) {
payloadKey = this.keyForAttribute(key);
if (key === payloadKey) { return; }
if (!hash.hasOwnProperty(payloadKey)) { return; }
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeRelationships
@private
*/
normalizeRelationships: function(type, hash) {
var payloadKey, key;
if (this.keyForRelationship) {
type.eachRelationship(function(key, relationship) {
payloadKey = this.keyForRelationship(key, relationship.kind);
if (key === payloadKey) { return; }
if (!hash.hasOwnProperty(payloadKey)) { return; }
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeUsingDeclaredMapping
@private
*/
normalizeUsingDeclaredMapping: function(type, hash) {
var attrs = get(this, 'attrs'), payloadKey, key;
if (attrs) {
for (key in attrs) {
payloadKey = this._getMappedKey(key);
if (!hash.hasOwnProperty(payloadKey)) { continue; }
if (payloadKey !== key) {
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}
}
}
},
/**
@method normalizeId
@private
*/
normalizeId: function(hash) {
var primaryKey = get(this, 'primaryKey');
if (primaryKey === 'id') { return; }
hash.id = hash[primaryKey];
delete hash[primaryKey];
},
/**
Looks up the property key that was set by the custom `attr` mapping
passed to the serializer.
@method _getMappedKey
@private
@param {String} key
@return {String} key
*/
_getMappedKey: function(key) {
var attrs = get(this, 'attrs');
var mappedKey;
if (attrs && attrs[key]) {
mappedKey = attrs[key];
//We need to account for both the {title: 'post_title'} and
//{title: {key: 'post_title'}} forms
if (mappedKey.key){
mappedKey = mappedKey.key;
}
if (typeof mappedKey === 'string'){
key = mappedKey;
}
}
return key;
},
/**
Check attrs.key.serialize property to inform if the `key`
can be serialized
@method _canSerialize
@private
@param {String} key
@return {boolean} true if the key can be serialized
*/
_canSerialize: function(key) {
var attrs = get(this, 'attrs');
return !attrs || !attrs[key] || attrs[key].serialize !== false;
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```javascript
App.Comment = DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```javascript
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serialize: function(post, options) {
var json = {
POST_TTL: post.get('title'),
POST_BDY: post.get('body'),
POST_CMS: post.get('comments').mapBy('id')
}
if (options.includeId) {
json.POST_ID_ = post.get('id');
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachAttribute(function(name) {
json[serverAttributeName(name)] = record.get(name);
})
record.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = record.get(name).mapBy('id');
}
});
if (options.includeId) {
json.ID_ = record.get('id');
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```javascript
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = this._super.apply(this, arguments);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param {subclass of DS.Model} record
@param {Object} options
@return {Object} json
*/
serialize: function(record, options) {
var json = {};
if (options && options.includeId) {
var id = get(record, 'id');
if (id) {
json[get(this, 'primaryKey')] = id;
}
}
record.eachAttribute(function(key, attribute) {
this.serializeAttribute(record, json, key, attribute);
}, this);
record.eachRelationship(function(key, relationship) {
if (relationship.kind === 'belongsTo') {
this.serializeBelongsTo(record, json, relationship);
} else if (relationship.kind === 'hasMany') {
this.serializeHasMany(record, json, relationship);
}
}, this);
return json;
},
/**
You can use this method to customize how a serialized record is added to the complete
JSON hash to be sent to the server. By default the JSON Serializer does not namespace
the payload and just sends the raw serialized JSON object.
If your server expects namespaced keys, you should consider using the RESTSerializer.
Otherwise you can override this method to customize how the record is added to the hash.
For example, your server may expect underscored root objects.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.decamelize(type.typeKey);
data[root] = this.serialize(record, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Model} record
@param {Object} options
*/
serializeIntoHash: function(hash, type, record, options) {
merge(hash, this.serialize(record, options));
},
/**
`serializeAttribute` can be used to customize how `DS.attr`
properties are serialized
For example if you wanted to ensure all your attributes were always
serialized as properties on an `attributes` object you could
write:
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serializeAttribute: function(record, json, key, attributes) {
json.attributes = json.attributes || {};
this._super(record, json.attributes, key, attributes);
}
});
```
@method serializeAttribute
@param {DS.Model} record
@param {Object} json
@param {String} key
@param {Object} attribute
*/
serializeAttribute: function(record, json, key, attribute) {
var type = attribute.type;
if (this._canSerialize(key)) {
var value = get(record, key);
if (type) {
var transform = this.transformFor(type);
value = transform.serialize(value);
}
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForAttribute) {
payloadKey = this.keyForAttribute(key);
}
json[payloadKey] = value;
}
},
/**
`serializeBelongsTo` can be used to customize how `DS.belongsTo`
properties are serialized.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serializeBelongsTo: function(record, json, relationship) {
var key = relationship.key;
var belongsTo = get(record, key);
key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key;
json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.toJSON();
}
});
```
@method serializeBelongsTo
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function(record, json, relationship) {
var key = relationship.key;
if (this._canSerialize(key)) {
var belongsTo = get(record, key);
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, "belongsTo");
}
if (isNone(belongsTo)) {
json[payloadKey] = belongsTo;
} else {
json[payloadKey] = get(belongsTo, 'id');
}
if (relationship.options.polymorphic) {
this.serializePolymorphicType(record, json, relationship);
}
}
},
/**
`serializeHasMany` can be used to customize how `DS.hasMany`
properties are serialized.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
if (key === 'comments') {
return;
} else {
this._super.apply(this, arguments);
}
}
});
```
@method serializeHasMany
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
if (this._canSerialize(key)) {
var payloadKey;
// if provided, use the mapping provided by `attrs` in
// the serializer
payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, "hasMany");
}
var relationshipType = RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') {
json[payloadKey] = get(record, key).mapBy('id');
// TODO support for polymorphic manyToNone and manyToMany relationships
}
}
},
/**
You can use this method to customize how polymorphic objects are
serialized. Objects are considered to be polymorphic if
`{polymorphic: true}` is pass as the second argument to the
`DS.belongsTo` function.
Example
```javascript
App.CommentSerializer = DS.JSONSerializer.extend({
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
key = this.keyForAttribute ? this.keyForAttribute(key) : key;
if (Ember.isNone(belongsTo)) {
json[key + "_type"] = null;
} else {
json[key + "_type"] = belongsTo.constructor.typeKey;
}
}
});
```
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: Ember.K,
// EXTRACT
/**
The `extract` method is used to deserialize payload data from the
server. By default the `JSONSerializer` does not push the records
into the store. However records that subclass `JSONSerializer`
such as the `RESTSerializer` may push records into the store as
part of the extract call.
This method delegates to a more specific extract method based on
the `requestType`.
Example
```javascript
var get = Ember.get;
socket.on('message', function(message) {
var modelName = message.model;
var data = message.data;
var type = store.modelFor(modelName);
var serializer = store.serializerFor(type.typeKey);
var record = serializer.extract(store, type, data, get(data, 'id'), 'single');
store.push(modelName, record);
});
```
@method extract
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extract: function(store, type, payload, id, requestType) {
this.extractMeta(store, type, payload);
var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1);
return this[specificExtract](store, type, payload, id, requestType);
},
/**
`extractFindAll` is a hook into the extract method used when a
call is made to `DS.Store#findAll`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindAll: function(store, type, payload, id, requestType){
return this.extractArray(store, type, payload, id, requestType);
},
/**
`extractFindQuery` is a hook into the extract method used when a
call is made to `DS.Store#findQuery`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindQuery: function(store, type, payload, id, requestType){
return this.extractArray(store, type, payload, id, requestType);
},
/**
`extractFindMany` is a hook into the extract method used when a
call is made to `DS.Store#findMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindMany: function(store, type, payload, id, requestType){
return this.extractArray(store, type, payload, id, requestType);
},
/**
`extractFindHasMany` is a hook into the extract method used when a
call is made to `DS.Store#findHasMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindHasMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindHasMany: function(store, type, payload, id, requestType){
return this.extractArray(store, type, payload, id, requestType);
},
/**
`extractCreateRecord` is a hook into the extract method used when a
call is made to `DS.Store#createRecord`. By default this method is
alias for [extractSave](#method_extractSave).
@method extractCreateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractCreateRecord: function(store, type, payload, id, requestType) {
return this.extractSave(store, type, payload, id, requestType);
},
/**
`extractUpdateRecord` is a hook into the extract method used when
a call is made to `DS.Store#update`. By default this method is alias
for [extractSave](#method_extractSave).
@method extractUpdateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractUpdateRecord: function(store, type, payload, id, requestType) {
return this.extractSave(store, type, payload, id, requestType);
},
/**
`extractDeleteRecord` is a hook into the extract method used when
a call is made to `DS.Store#deleteRecord`. By default this method is
alias for [extractSave](#method_extractSave).
@method extractDeleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractDeleteRecord: function(store, type, payload, id, requestType) {
return this.extractSave(store, type, payload, id, requestType);
},
/**
`extractFind` is a hook into the extract method used when
a call is made to `DS.Store#find`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFind
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractFind: function(store, type, payload, id, requestType) {
return this.extractSingle(store, type, payload, id, requestType);
},
/**
`extractFindBelongsTo` is a hook into the extract method used when
a call is made to `DS.Store#findBelongsTo`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFindBelongsTo
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractFindBelongsTo: function(store, type, payload, id, requestType) {
return this.extractSingle(store, type, payload, id, requestType);
},
/**
`extractSave` is a hook into the extract method used when a call
is made to `DS.Model#save`. By default this method is alias
for [extractSingle](#method_extractSingle).
@method extractSave
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractSave: function(store, type, payload, id, requestType) {
return this.extractSingle(store, type, payload, id, requestType);
},
/**
`extractSingle` is used to deserialize a single record returned
from the adapter.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractSingle: function(store, type, payload) {
payload.comments = payload._embedded.comment;
delete payload._embedded;
return this._super(store, type, payload);
},
});
```
@method extractSingle
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractSingle: function(store, type, payload, id, requestType) {
payload = this.normalizePayload(payload);
return this.normalize(type, payload);
},
/**
`extractArray` is used to deserialize an array of records
returned from the adapter.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractArray: function(store, type, payload) {
return payload.map(function(json) {
return this.extractSingle(store, type, json);
}, this);
}
});
```
@method extractArray
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractArray: function(store, type, arrayPayload, id, requestType) {
var normalizedPayload = this.normalizePayload(arrayPayload);
var serializer = this;
return map.call(normalizedPayload, function(singlePayload) {
return serializer.normalize(type, singlePayload);
});
},
/**
`extractMeta` is used to deserialize any meta information in the
adapter payload. By default Ember Data expects meta information to
be located on the `meta` property of the payload object.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractMeta: function(store, type, payload) {
if (payload && payload._pagination) {
store.metaForType(type, payload._pagination);
delete payload._pagination;
}
}
});
```
@method extractMeta
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
*/
extractMeta: function(store, type, payload) {
if (payload && payload.meta) {
store.metaForType(type, payload.meta);
delete payload.meta;
}
},
/**
`keyForAttribute` can be used to define rules for how to convert an
attribute name in your model to a key in your JSON.
Example
```javascript
App.ApplicationSerializer = DS.RESTSerializer.extend({
keyForAttribute: function(attr) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
@method keyForAttribute
@param {String} key
@return {String} normalized key
*/
keyForAttribute: function(key){
return key;
},
/**
`keyForRelationship` can be used to define a custom key when
serializing relationship properties. By default `JSONSerializer`
does not provide an implementation of this method.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
keyForRelationship: function(key, relationship) {
return 'rel_' + Ember.String.underscore(key);
}
});
```
@method keyForRelationship
@param {String} key
@param {String} relationship type
@return {String} normalized key
*/
keyForRelationship: function(key, type){
return key;
},
// HELPERS
/**
@method transformFor
@private
@param {String} attributeType
@param {Boolean} skipAssertion
@return {DS.Transform} transform
*/
transformFor: function(attributeType, skipAssertion) {
var transform = this.container.lookup('transform:' + attributeType);
Ember.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform);
return transform;
}
});
});
define("ember-data/serializers/rest_serializer",
["ember-data/serializers/json_serializer","ember-inflector/system/string","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/**
@module ember-data
*/
var JSONSerializer = __dependency1__["default"];
var get = Ember.get;
var set = Ember.set;
var forEach = Ember.ArrayPolyfills.forEach;
var map = Ember.ArrayPolyfills.map;
var camelize = Ember.String.camelize;
var singularize = __dependency2__.singularize;
function coerceId(id) {
return id == null ? null : id + '';
}
/**
Normally, applications will use the `RESTSerializer` by implementing
the `normalize` method and individual normalizations under
`normalizeHash`.
This allows you to do whatever kind of munging you need, and is
especially useful if your server is inconsistent and you need to
do munging differently for many different kinds of responses.
See the `normalize` documentation for more information.
## Across the Board Normalization
There are also a number of hooks that you might find useful to define
across-the-board rules for your payload. These rules will be useful
if your server is consistent, or if you're building an adapter for
an infrastructure service, like Parse, and want to encode service
conventions.
For example, if all of your keys are underscored and all-caps, but
otherwise consistent with the names you use in your models, you
can implement across-the-board rules for how to convert an attribute
name in your model to a key in your JSON.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
keyForAttribute: function(attr) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
You can also implement `keyForRelationship`, which takes the name
of the relationship as the first parameter, and the kind of
relationship (`hasMany` or `belongsTo`) as the second parameter.
@class RESTSerializer
@namespace DS
@extends DS.JSONSerializer
*/
__exports__["default"] = JSONSerializer.extend({
/**
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, given the following json where the the `IDs` under
`"comments"` are provided as `_id` instead of `id`.
```javascript
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"_id": 1,
"body": "FIRST"
}, {
"_id": 2,
"body": "Rails is unagi"
}]
}
```
You use `normalizeHash` to normalize just the comments:
```javascript
App.PostSerializer = DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is usually just the original key
that was in the original payload. However, key names will be
impacted by any modifications done in the `normalizePayload`
method. The `DS.RESTSerializer`'s default implementation makes no
changes to the payload keys.
@property normalizeHash
@type {Object}
@default undefined
*/
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
For example, if you have a payload that looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"id": 1,
"body": "FIRST"
}, {
"id": 2,
"body": "Rails is unagi"
}]
}
```
The `normalize` method will be called three times:
* With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }`
* With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }`
* With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }`
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, if the `IDs` under `"comments"` are provided as `_id` instead of
`id`, you can specify how to normalize just the comments:
```js
App.PostSerializer = DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is just the original key that was in the original
payload.
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@param {String} prop
@return {Object}
*/
normalize: function(type, hash, prop) {
this.normalizeId(hash);
this.normalizeAttributes(type, hash);
this.normalizeRelationships(type, hash);
this.normalizeUsingDeclaredMapping(type, hash);
if (this.normalizeHash && this.normalizeHash[prop]) {
this.normalizeHash[prop](hash);
}
this.applyTransforms(type, hash);
return hash;
},
/**
Called when the server has returned a payload representing
a single record, such as in response to a `find` or `save`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
post 1:
```js
{
"id": 1,
"title": "Rails is omakase",
"_embedded": {
"comment": [{
"_id": 1,
"comment_title": "FIRST"
}, {
"_id": 2,
"comment_title": "Rails is unagi"
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```js
App.PostSerializer = DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
extractSingle: function(store, type, payload, id) {
var comments = payload._embedded.comment;
delete payload._embedded;
payload = { comments: comments, post: payload };
return this._super(store, type, payload, id);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractSingle`, the
built-in implementation will find the primary record in your normalized
payload and push the remaining records into the store.
The primary record is the single hash found under `post` or the first
element of the `posts` array.
The primary record has special meaning when the record is being created
for the first time or updated (`createRecord` or `updateRecord`). In
particular, it will update the properties of the record that was saved.
@method extractSingle
@param {DS.Store} store
@param {subclass of DS.Model} primaryType
@param {Object} payload
@param {String} recordId
@return {Object} the primary response to the original request
*/
extractSingle: function(store, primaryType, rawPayload, recordId) {
var payload = this.normalizePayload(rawPayload);
var primaryTypeName = primaryType.typeKey;
var primaryRecord;
for (var prop in payload) {
var typeName = this.typeForRoot(prop);
var type = store.modelFor(typeName);
var isPrimary = type.typeKey === primaryTypeName;
var value = payload[prop];
// legacy support for singular resources
if (isPrimary && Ember.typeOf(value) !== "array" ) {
primaryRecord = this.normalize(primaryType, value, prop);
continue;
}
/*jshint loopfunc:true*/
forEach.call(value, function(hash) {
var typeName = this.typeForRoot(prop);
var type = store.modelFor(typeName);
var typeSerializer = store.serializerFor(type);
hash = typeSerializer.normalize(type, hash, prop);
var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord;
var isUpdatedRecord = isPrimary && coerceId(hash.id) === recordId;
// find the primary record.
//
// It's either:
// * the record with the same ID as the original request
// * in the case of a newly created record that didn't have an ID, the first
// record in the Array
if (isFirstCreatedRecord || isUpdatedRecord) {
primaryRecord = hash;
} else {
store.push(typeName, hash);
}
}, this);
}
return primaryRecord;
},
/**
Called when the server has returned a payload representing
multiple records, such as in response to a `findAll` or `findQuery`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
all posts:
```js
{
"_embedded": {
"post": [{
"id": 1,
"title": "Rails is omakase"
}, {
"id": 2,
"title": "The Parley Letter"
}],
"comment": [{
"_id": 1,
"comment_title": "Rails is unagi"
"post_id": 1
}, {
"_id": 2,
"comment_title": "Don't tread on me",
"post_id": 2
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```js
App.PostSerializer = DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
// and the comments are listed under a post's `comments` key.
extractArray: function(store, type, payload) {
var posts = payload._embedded.post;
var comments = [];
var postCache = {};
posts.forEach(function(post) {
post.comments = [];
postCache[post.id] = post;
});
payload._embedded.comment.forEach(function(comment) {
comments.push(comment);
postCache[comment.post_id].comments.push(comment);
delete comment.post_id;
});
payload = { comments: comments, posts: payload };
return this._super(store, type, payload);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractArray`, the
built-in implementation will find the primary array in your normalized
payload and push the remaining records into the store.
The primary array is the array found under `posts`.
The primary record has special meaning when responding to `findQuery`
or `findHasMany`. In particular, the primary array will become the
list of records in the record array that kicked off the request.
If your primary array contains secondary (embedded) records of the same type,
you cannot place these into the primary array `posts`. Instead, place the
secondary items into an underscore prefixed property `_posts`, which will
push these items into the store and will not affect the resulting query.
@method extractArray
@param {DS.Store} store
@param {subclass of DS.Model} primaryType
@param {Object} payload
@return {Array} The primary array that was returned in response
to the original query.
*/
extractArray: function(store, primaryType, rawPayload) {
var payload = this.normalizePayload(rawPayload);
var primaryTypeName = primaryType.typeKey;
var primaryArray;
for (var prop in payload) {
var typeKey = prop;
var forcedSecondary = false;
if (prop.charAt(0) === '_') {
forcedSecondary = true;
typeKey = prop.substr(1);
}
var typeName = this.typeForRoot(typeKey);
var type = store.modelFor(typeName);
var typeSerializer = store.serializerFor(type);
var isPrimary = (!forcedSecondary && (type.typeKey === primaryTypeName));
/*jshint loopfunc:true*/
var normalizedArray = map.call(payload[prop], function(hash) {
return typeSerializer.normalize(type, hash, prop);
}, this);
if (isPrimary) {
primaryArray = normalizedArray;
} else {
store.pushMany(typeName, normalizedArray);
}
}
return primaryArray;
},
/**
This method allows you to push a payload containing top-level
collections of records organized per type.
```js
{
"posts": [{
"id": "1",
"title": "Rails is omakase",
"author", "1",
"comments": [ "1" ]
}],
"comments": [{
"id": "1",
"body": "FIRST"
}],
"users": [{
"id": "1",
"name": "@d2h"
}]
}
```
It will first normalize the payload, so you can use this to push
in data streaming in from your server structured the same way
that fetches and saves are structured.
@method pushPayload
@param {DS.Store} store
@param {Object} payload
*/
pushPayload: function(store, rawPayload) {
var payload = this.normalizePayload(rawPayload);
for (var prop in payload) {
var typeName = this.typeForRoot(prop);
var type = store.modelFor(typeName);
var typeSerializer = store.serializerFor(type);
/*jshint loopfunc:true*/
var normalizedArray = map.call(Ember.makeArray(payload[prop]), function(hash) {
return typeSerializer.normalize(type, hash, prop);
}, this);
store.pushMany(typeName, normalizedArray);
}
},
/**
This method is used to convert each JSON root key in the payload
into a typeKey that it can use to look up the appropriate model for
that part of the payload. By default the typeKey for a model is its
name in camelCase, so if your JSON root key is 'fast-car' you would
use typeForRoot to convert it to 'fastCar' so that Ember Data finds
the `FastCar` model.
If you diverge from this norm you should also consider changes to
store._normalizeTypeKey as well.
For example, your server may return prefixed root keys like so:
```js
{
"response-fast-car": {
"id": "1",
"name": "corvette"
}
}
```
In order for Ember Data to know that the model corresponding to
the 'response-fast-car' hash is `FastCar` (typeKey: 'fastCar'),
you can override typeForRoot to convert 'response-fast-car' to
'fastCar' like so:
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
typeForRoot: function(root) {
// 'response-fast-car' should become 'fast-car'
var subRoot = root.substring(9);
// _super normalizes 'fast-car' to 'fastCar'
return this._super(subRoot);
}
});
```
@method typeForRoot
@param {String} key
@return {String} the model's typeKey
*/
typeForRoot: function(key) {
return camelize(singularize(key));
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```js
App.Comment = DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```js
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```js
App.PostSerializer = DS.RESTSerializer.extend({
serialize: function(post, options) {
var json = {
POST_TTL: post.get('title'),
POST_BDY: post.get('body'),
POST_CMS: post.get('comments').mapBy('id')
}
if (options.includeId) {
json.POST_ID_ = post.get('id');
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachAttribute(function(name) {
json[serverAttributeName(name)] = record.get(name);
})
record.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = record.get(name).mapBy('id');
}
});
if (options.includeId) {
json.ID_ = record.get('id');
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```js
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```js
App.PostSerializer = DS.RESTSerializer.extend({
serialize: function(record, options) {
var json = this._super(record, options);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param record
@param options
*/
serialize: function(record, options) {
return this._super.apply(this, arguments);
},
/**
You can use this method to customize the root keys serialized into the JSON.
By default the REST Serializer sends the typeKey of a model, whih is a camelized
version of the name.
For example, your server may expect underscored root objects.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.decamelize(type.typeKey);
data[root] = this.serialize(record, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Model} record
@param {Object} options
*/
serializeIntoHash: function(hash, type, record, options) {
hash[type.typeKey] = this.serialize(record, options);
},
/**
You can use this method to customize how polymorphic objects are serialized.
By default the JSON Serializer creates the key by appending `Type` to
the attribute and value from the model's camelcased model name.
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key;
var belongsTo = get(record, key);
key = this.keyForAttribute ? this.keyForAttribute(key) : key;
if (Ember.isNone(belongsTo)) {
json[key + "Type"] = null;
} else {
json[key + "Type"] = Ember.String.camelize(belongsTo.constructor.typeKey);
}
}
});
});
define("ember-data/setup-container",
["ember-data/initializers/store","ember-data/initializers/transforms","ember-data/initializers/store_injections","ember-data/initializers/data_adapter","activemodel-adapter/setup-container","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) {
"use strict";
var initializeStore = __dependency1__["default"];
var initializeTransforms = __dependency2__["default"];
var initializeStoreInjections = __dependency3__["default"];
var initializeDataAdapter = __dependency4__["default"];
var setupActiveModelContainer = __dependency5__["default"];
__exports__["default"] = function setupContainer(container, application){
// application is not a required argument. This ensures
// testing setups can setup a container without booting an
// entire ember application.
initializeDataAdapter(container, application);
initializeTransforms(container, application);
initializeStoreInjections(container, application);
initializeStore(container, application);
setupActiveModelContainer(container, application);
};
});
define("ember-data/system/adapter",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
var get = Ember.get;
var set = Ember.set;
var map = Ember.ArrayPolyfills.map;
var errorProps = [
'description',
'fileName',
'lineNumber',
'message',
'name',
'number',
'stack'
];
/**
A `DS.InvalidError` is used by an adapter to signal the external API
was unable to process a request because the content was not
semantically correct or meaningful per the API. Usually this means a
record failed some form of server side validation. When a promise
from an adapter is rejected with a `DS.InvalidError` the record will
transition to the `invalid` state and the errors will be set to the
`errors` property on the record.
Example
```javascript
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"];
return new DS.InvalidError(jsonErrors);
} else {
return error;
}
}
});
```
The `DS.InvalidError` must be constructed with a single object whose
keys are the invalid model properties, and whose values are the
corresponding error messages. For example:
```javascript
return new DS.InvalidError({
length: 'Must be less than 15',
name: 'Must not be blank
});
```
@class InvalidError
@namespace DS
*/
function InvalidError(errors) {
var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors));
this.errors = errors;
for (var i=0, l=errorProps.length; i<l; i++) {
this[errorProps[i]] = tmp[errorProps[i]];
}
}
InvalidError.prototype = Ember.create(Error.prototype);
/**
An adapter is an object that receives requests from a store and
translates them into the appropriate action to take against your
persistence layer. The persistence layer is usually an HTTP API, but
may be anything, such as the browser's local storage. Typically the
adapter is not invoked directly instead its functionality is accessed
through the `store`.
### Creating an Adapter
Create a new subclass of `DS.Adapter`, then assign
it to the `ApplicationAdapter` property of the application.
```javascript
var MyAdapter = DS.Adapter.extend({
// ...your code here
});
App.ApplicationAdapter = MyAdapter;
```
Model-specific adapters can be created by assigning your adapter
class to the `ModelName` + `Adapter` property of the application.
```javascript
var MyPostAdapter = DS.Adapter.extend({
// ...Post-specific adapter code goes here
});
App.PostAdapter = MyPostAdapter;
```
`DS.Adapter` is an abstract base class that you should override in your
application to customize it for your backend. The minimum set of methods
that you should implement is:
* `find()`
* `createRecord()`
* `updateRecord()`
* `deleteRecord()`
* `findAll()`
* `findQuery()`
To improve the network performance of your application, you can optimize
your adapter by overriding these lower-level methods:
* `findMany()`
For an example implementation, see `DS.RESTAdapter`, the
included REST adapter.
@class Adapter
@namespace DS
@extends Ember.Object
*/
var Adapter = Ember.Object.extend({
/**
If you would like your adapter to use a custom serializer you can
set the `defaultSerializer` property to be the name of the custom
serializer.
Note the `defaultSerializer` serializer has a lower priority than
a model specific serializer (i.e. `PostSerializer`) or the
`application` serializer.
```javascript
var DjangoAdapter = DS.Adapter.extend({
defaultSerializer: 'django'
});
```
@property defaultSerializer
@type {String}
*/
/**
The `find()` method is invoked when the store is asked for a record that
has not previously been loaded. In response to `find()` being called, you
should query your persistence layer for a record with the given ID. Once
found, you can asynchronously call the store's `push()` method to push
the record into the store.
Here is an example `find` implementation:
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
find: function(store, type, id) {
var url = [type.typeKey, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method find
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@return {Promise} promise
*/
find: Ember.required(Function),
/**
The `findAll()` method is called when you call `find` on the store
without an ID (i.e. `store.find('post')`).
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
findAll: function(store, type, sinceToken) {
var url = type;
var query = { since: sinceToken };
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@private
@method findAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: null,
/**
This method is called when you call `find` on the store with a
query object as the second parameter (i.e. `store.find('person', {
page: 1 })`).
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
findQuery: function(store, type, query) {
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@private
@method findQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} recordArray
@return {Promise} promise
*/
findQuery: null,
/**
If the globally unique IDs for your records should be generated on the client,
implement the `generateIdForRecord()` method. This method will be invoked
each time you create a new record, and the value returned from it will be
assigned to the record's `primaryKey`.
Most traditional REST-like HTTP APIs will not use this method. Instead, the ID
of the record will be set by the server, and your adapter will update the store
with the new ID when it calls `didCreateRecord()`. Only implement this method if
you intend to generate record IDs on the client-side.
The `generateIdForRecord()` method will be invoked with the requesting store as
the first parameter and the newly created record as the second parameter:
```javascript
generateIdForRecord: function(store, record) {
var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision();
return uuid;
}
```
@method generateIdForRecord
@param {DS.Store} store
@param {DS.Model} record
@return {String|Number} id
*/
generateIdForRecord: null,
/**
Proxies to the serializer's `serialize` method.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
createRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var url = type;
// ...
}
});
```
@method serialize
@param {DS.Model} record
@param {Object} options
@return {Object} serialized record
*/
serialize: function(record, options) {
return get(record, 'store').serializerFor(record.constructor.typeKey).serialize(record, options);
},
/**
Implement this method in a subclass to handle the creation of
new records.
Serializes the record and send it to the server.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
createRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
@return {Promise} promise
*/
createRecord: Ember.required(Function),
/**
Implement this method in a subclass to handle the updating of
a record.
Serializes the record update and send it to the server.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
updateRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var id = record.get('id');
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'PUT',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
@return {Promise} promise
*/
updateRecord: Ember.required(Function),
/**
Implement this method in a subclass to handle the deletion of
a record.
Sends a delete request for the record to the server.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
deleteRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var id = record.get('id');
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'DELETE',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
@return {Promise} promise
*/
deleteRecord: Ember.required(Function),
/**
By default the store will try to coalesce all `fetchRecord` calls within the same runloop
into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call.
You can opt out of this behaviour by either not implementing the findMany hook or by setting
coalesceFindRequests to false
@property coalesceFindRequests
@type {boolean}
*/
coalesceFindRequests: true,
/**
Find multiple records at once if coalesceFindRequests is true
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the records
@param {Array} ids
@param {Array} records
@return {Promise} promise
*/
/**
Organize records into groups, each of which is to be passed to separate
calls to `findMany`.
For example, if your api has nested URLs that depend on the parent, you will
want to group records by their parent.
The default implementation returns the records as a single group.
@method groupRecordsForFindMany
@param {Array} records
@return {Array} an array of arrays of records, each of which is to be
loaded separately by `findMany`.
*/
groupRecordsForFindMany: function (store, records) {
return [records];
}
});
__exports__.InvalidError = InvalidError;
__exports__.Adapter = Adapter;
__exports__["default"] = Adapter;
});
define("ember-data/system/changes",
["ember-data/system/changes/relationship_change","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var RelationshipChange = __dependency1__.RelationshipChange;
var RelationshipChangeAdd = __dependency1__.RelationshipChangeAdd;
var RelationshipChangeRemove = __dependency1__.RelationshipChangeRemove;
var OneToManyChange = __dependency1__.OneToManyChange;
var ManyToNoneChange = __dependency1__.ManyToNoneChange;
var OneToOneChange = __dependency1__.OneToOneChange;
var ManyToManyChange = __dependency1__.ManyToManyChange;
__exports__.RelationshipChange = RelationshipChange;
__exports__.RelationshipChangeAdd = RelationshipChangeAdd;
__exports__.RelationshipChangeRemove = RelationshipChangeRemove;
__exports__.OneToManyChange = OneToManyChange;
__exports__.ManyToNoneChange = ManyToNoneChange;
__exports__.OneToOneChange = OneToOneChange;
__exports__.ManyToManyChange = ManyToManyChange;
});
define("ember-data/system/changes/relationship_change",
["ember-data/system/model/model","ember-data/system/relationship-meta","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/**
@module ember-data
*/
var Model = __dependency1__["default"];
var isSyncRelationship = __dependency2__.isSyncRelationship;
var get = Ember.get;
var set = Ember.set;
var forEach = Ember.EnumerableUtils.forEach;
/**
@class RelationshipChange
@namespace DS
@private
@constructor
*/
var RelationshipChange = function(options) {
this.parentRecord = options.parentRecord;
this.childRecord = options.childRecord;
this.firstRecord = options.firstRecord;
this.firstRecordKind = options.firstRecordKind;
this.firstRecordName = options.firstRecordName;
this.secondRecord = options.secondRecord;
this.secondRecordKind = options.secondRecordKind;
this.secondRecordName = options.secondRecordName;
this.changeType = options.changeType;
this.store = options.store;
this.committed = {};
};
/**
@class RelationshipChangeAdd
@namespace DS
@private
@constructor
*/
function RelationshipChangeAdd(options){
RelationshipChange.call(this, options);
}
/**
@class RelationshipChangeRemove
@namespace DS
@private
@constructor
*/
function RelationshipChangeRemove(options){
RelationshipChange.call(this, options);
}
RelationshipChange.create = function(options) {
return new RelationshipChange(options);
};
RelationshipChangeAdd.create = function(options) {
return new RelationshipChangeAdd(options);
};
RelationshipChangeRemove.create = function(options) {
return new RelationshipChangeRemove(options);
};
var OneToManyChange = {};
var OneToNoneChange = {};
var ManyToNoneChange = {};
var OneToOneChange = {};
var ManyToManyChange = {};
RelationshipChange._createChange = function(options){
if (options.changeType === 'add') {
return RelationshipChangeAdd.create(options);
}
if (options.changeType === 'remove') {
return RelationshipChangeRemove.create(options);
}
};
RelationshipChange.determineRelationshipType = function(recordType, knownSide){
var knownKey = knownSide.key, key, otherKind;
var knownKind = knownSide.kind;
var inverse = recordType.inverseFor(knownKey);
if (inverse) {
key = inverse.name;
otherKind = inverse.kind;
}
if (!inverse) {
return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone';
} else {
if (otherKind === 'belongsTo') {
return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne';
} else {
return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany';
}
}
};
RelationshipChange.createChange = function(firstRecord, secondRecord, store, options){
// Get the type of the child based on the child's client ID
var firstRecordType = firstRecord.constructor, changeType;
changeType = RelationshipChange.determineRelationshipType(firstRecordType, options);
if (changeType === 'oneToMany') {
return OneToManyChange.createChange(firstRecord, secondRecord, store, options);
} else if (changeType === 'manyToOne') {
return OneToManyChange.createChange(secondRecord, firstRecord, store, options);
} else if (changeType === 'oneToNone') {
return OneToNoneChange.createChange(firstRecord, secondRecord, store, options);
} else if (changeType === 'manyToNone') {
return ManyToNoneChange.createChange(firstRecord, secondRecord, store, options);
} else if (changeType === 'oneToOne') {
return OneToOneChange.createChange(firstRecord, secondRecord, store, options);
} else if (changeType === 'manyToMany') {
return ManyToManyChange.createChange(firstRecord, secondRecord, store, options);
}
};
OneToNoneChange.createChange = function(childRecord, parentRecord, store, options) {
var key = options.key;
var change = RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
store: store,
changeType: options.changeType,
firstRecordName: key,
firstRecordKind: 'belongsTo'
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
ManyToNoneChange.createChange = function(childRecord, parentRecord, store, options) {
var key = options.key;
var change = RelationshipChange._createChange({
parentRecord: childRecord,
childRecord: parentRecord,
secondRecord: childRecord,
store: store,
changeType: options.changeType,
secondRecordName: options.key,
secondRecordKind: 'hasMany'
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
ManyToManyChange.createChange = function(childRecord, parentRecord, store, options) {
// If the name of the belongsTo side of the relationship is specified,
// use that
// If the type of the parent is specified, look it up on the child's type
// definition.
var key = options.key;
var change = RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
secondRecord: parentRecord,
firstRecordKind: 'hasMany',
secondRecordKind: 'hasMany',
store: store,
changeType: options.changeType,
firstRecordName: key
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
OneToOneChange.createChange = function(childRecord, parentRecord, store, options) {
var key;
// If the name of the belongsTo side of the relationship is specified,
// use that
// If the type of the parent is specified, look it up on the child's type
// definition.
if (options.parentType) {
key = options.parentType.inverseFor(options.key).name;
} else if (options.key) {
key = options.key;
} else {
Ember.assert('You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent', false);
}
var change = RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
secondRecord: parentRecord,
firstRecordKind: 'belongsTo',
secondRecordKind: 'belongsTo',
store: store,
changeType: options.changeType,
firstRecordName: key
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
OneToOneChange.maintainInvariant = function(options, store, childRecord, key){
if (options.changeType === 'add' && store.recordIsMaterialized(childRecord)) {
var oldParent = get(childRecord, key);
if (oldParent) {
var correspondingChange = OneToOneChange.createChange(childRecord, oldParent, store, {
parentType: options.parentType,
hasManyName: options.hasManyName,
changeType: 'remove',
key: options.key
});
store.addRelationshipChangeFor(childRecord, key, options.parentRecord , null, correspondingChange);
correspondingChange.sync();
}
}
};
OneToManyChange.createChange = function(childRecord, parentRecord, store, options) {
var key;
// If the name of the belongsTo side of the relationship is specified,
// use that
// If the type of the parent is specified, look it up on the child's type
// definition.
if (options.parentType) {
key = options.parentType.inverseFor(options.key).name;
OneToManyChange.maintainInvariant( options, store, childRecord, key );
} else if (options.key) {
key = options.key;
} else {
Ember.assert('You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent', false);
}
var change = RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
secondRecord: parentRecord,
firstRecordKind: 'belongsTo',
secondRecordKind: 'hasMany',
store: store,
changeType: options.changeType,
firstRecordName: key
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, change.getSecondRecordName(), change);
return change;
};
OneToManyChange.maintainInvariant = function(options, store, childRecord, key){
if (options.changeType === 'add' && childRecord) {
var oldParent = get(childRecord, key);
if (oldParent) {
var correspondingChange = OneToManyChange.createChange(childRecord, oldParent, store, {
parentType: options.parentType,
hasManyName: options.hasManyName,
changeType: 'remove',
key: options.key
});
store.addRelationshipChangeFor(childRecord, key, options.parentRecord, correspondingChange.getSecondRecordName(), correspondingChange);
correspondingChange.sync();
}
}
};
/**
@class RelationshipChange
@namespace DS
*/
RelationshipChange.prototype = {
getSecondRecordName: function() {
var name = this.secondRecordName, parent;
if (!name) {
parent = this.secondRecord;
if (!parent) { return; }
var childType = this.firstRecord.constructor;
var inverse = childType.inverseFor(this.firstRecordName);
this.secondRecordName = inverse.name;
}
return this.secondRecordName;
},
/**
Get the name of the relationship on the belongsTo side.
@method getFirstRecordName
@return {String}
*/
getFirstRecordName: function() {
return this.firstRecordName;
},
/**
@method destroy
@private
*/
destroy: function() {
var childRecord = this.childRecord;
var belongsToName = this.getFirstRecordName();
var hasManyName = this.getSecondRecordName();
var store = this.store;
store.removeRelationshipChangeFor(childRecord, belongsToName, this.parentRecord, hasManyName, this.changeType);
},
getSecondRecord: function(){
return this.secondRecord;
},
/**
@method getFirstRecord
@private
*/
getFirstRecord: function() {
return this.firstRecord;
},
coalesce: function(){
var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecord);
forEach(relationshipPairs, function(pair) {
var addedChange = pair['add'];
var removedChange = pair['remove'];
if (addedChange && removedChange) {
addedChange.destroy();
removedChange.destroy();
}
});
}
};
RelationshipChangeAdd.prototype = Ember.create(RelationshipChange.create({}));
RelationshipChangeRemove.prototype = Ember.create(RelationshipChange.create({}));
RelationshipChangeAdd.prototype.changeType = 'add';
RelationshipChangeAdd.prototype.sync = function() {
var secondRecordName = this.getSecondRecordName();
var firstRecordName = this.getFirstRecordName();
var firstRecord = this.getFirstRecord();
var secondRecord = this.getSecondRecord();
//Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName);
//Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName);
if (secondRecord instanceof Model && firstRecord instanceof Model) {
if (this.secondRecordKind === 'belongsTo') {
secondRecord.suspendRelationshipObservers(function() {
set(secondRecord, secondRecordName, firstRecord);
});
} else if (this.secondRecordKind === 'hasMany' && isSyncRelationship(secondRecord, secondRecordName)) {
secondRecord.suspendRelationshipObservers(function() {
var relationship = get(secondRecord, secondRecordName);
relationship.addObject(firstRecord);
});
}
}
if (firstRecord instanceof Model && secondRecord instanceof Model && get(firstRecord, firstRecordName) !== secondRecord) {
if (this.firstRecordKind === 'belongsTo') {
firstRecord.suspendRelationshipObservers(function() {
set(firstRecord, firstRecordName, secondRecord);
});
} else if (this.firstRecordKind === 'hasMany' && isSyncRelationship(secondRecord, secondRecordName)) {
firstRecord.suspendRelationshipObservers(function() {
var relationship = get(firstRecord, firstRecordName);
relationship.addObject(secondRecord);
});
}
}
this.coalesce();
};
RelationshipChangeRemove.prototype.changeType = 'remove';
RelationshipChangeRemove.prototype.sync = function() {
var secondRecordName = this.getSecondRecordName();
var firstRecordName = this.getFirstRecordName();
var firstRecord = this.getFirstRecord();
var secondRecord = this.getSecondRecord();
//Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName);
//Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName);
if (secondRecord instanceof Model && firstRecord instanceof Model) {
if (this.secondRecordKind === 'belongsTo') {
secondRecord.suspendRelationshipObservers(function() {
set(secondRecord, secondRecordName, null);
});
} else if (this.secondRecordKind === 'hasMany' && isSyncRelationship(secondRecord, secondRecordName)) {
secondRecord.suspendRelationshipObservers(function() {
var relationship = get(secondRecord, secondRecordName);
relationship.removeObject(firstRecord);
});
}
}
if (firstRecord instanceof Model && get(firstRecord, firstRecordName)) {
if (this.firstRecordKind === 'belongsTo') {
firstRecord.suspendRelationshipObservers(function() {
set(firstRecord, firstRecordName, null);
});
} else if (this.firstRecordKind === 'hasMany' && isSyncRelationship(firstRecord, firstRecordName)) {
firstRecord.suspendRelationshipObservers(function() {
var relationship = get(firstRecord, firstRecordName);
relationship.removeObject(secondRecord);
});
}
}
this.coalesce();
};
__exports__.RelationshipChange = RelationshipChange;
__exports__.RelationshipChangeAdd = RelationshipChangeAdd;
__exports__.RelationshipChangeRemove = RelationshipChangeRemove;
__exports__.OneToManyChange = OneToManyChange;
__exports__.ManyToNoneChange = ManyToNoneChange;
__exports__.OneToOneChange = OneToOneChange;
__exports__.ManyToManyChange = ManyToManyChange;
});
define("ember-data/system/container_proxy",
["exports"],
function(__exports__) {
"use strict";
/**
This is used internally to enable deprecation of container paths and provide
a decent message to the user indicating how to fix the issue.
@class ContainerProxy
@namespace DS
@private
*/
function ContainerProxy(container){
this.container = container;
}
ContainerProxy.prototype.aliasedFactory = function(path, preLookup) {
var _this = this;
return {create: function(){
if (preLookup) { preLookup(); }
return _this.container.lookup(path);
}};
};
ContainerProxy.prototype.registerAlias = function(source, dest, preLookup) {
var factory = this.aliasedFactory(dest, preLookup);
return this.container.register(source, factory);
};
ContainerProxy.prototype.registerDeprecation = function(deprecated, valid) {
var preLookupCallback = function(){
Ember.deprecate("You tried to look up '" + deprecated + "', " +
"but this has been deprecated in favor of '" + valid + "'.", false);
};
return this.registerAlias(deprecated, valid, preLookupCallback);
};
ContainerProxy.prototype.registerDeprecations = function(proxyPairs) {
var i, proxyPair, deprecated, valid, proxy;
for (i = proxyPairs.length; i > 0; i--) {
proxyPair = proxyPairs[i - 1];
deprecated = proxyPair['deprecated'];
valid = proxyPair['valid'];
this.registerDeprecation(deprecated, valid);
}
};
__exports__["default"] = ContainerProxy;
});
define("ember-data/system/debug",
["ember-data/system/debug/debug_info","ember-data/system/debug/debug_adapter","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/**
@module ember-data
*/
var DebugAdapter = __dependency2__["default"];
__exports__["default"] = DebugAdapter;
});
define("ember-data/system/debug/debug_adapter",
["ember-data/system/model","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var Model = __dependency1__.Model;
var get = Ember.get;
var capitalize = Ember.String.capitalize;
var underscore = Ember.String.underscore;
/**
Extend `Ember.DataAdapter` with ED specific code.
@class DebugAdapter
@namespace DS
@extends Ember.DataAdapter
@private
*/
__exports__["default"] = Ember.DataAdapter.extend({
getFilters: function() {
return [
{ name: 'isNew', desc: 'New' },
{ name: 'isModified', desc: 'Modified' },
{ name: 'isClean', desc: 'Clean' }
];
},
detect: function(klass) {
return klass !== Model && Model.detect(klass);
},
columnsForType: function(type) {
var columns = [{
name: 'id',
desc: 'Id'
}];
var count = 0;
var self = this;
get(type, 'attributes').forEach(function(name, meta) {
if (count++ > self.attributeLimit) { return false; }
var desc = capitalize(underscore(name).replace('_', ' '));
columns.push({ name: name, desc: desc });
});
return columns;
},
getRecords: function(type) {
return this.get('store').all(type);
},
getRecordColumnValues: function(record) {
var self = this, count = 0;
var columnValues = { id: get(record, 'id') };
record.eachAttribute(function(key) {
if (count++ > self.attributeLimit) {
return false;
}
var value = get(record, key);
columnValues[key] = value;
});
return columnValues;
},
getRecordKeywords: function(record) {
var keywords = [];
var keys = Ember.A(['id']);
record.eachAttribute(function(key) {
keys.push(key);
});
keys.forEach(function(key) {
keywords.push(get(record, key));
});
return keywords;
},
getRecordFilterValues: function(record) {
return {
isNew: record.get('isNew'),
isModified: record.get('isDirty') && !record.get('isNew'),
isClean: !record.get('isDirty')
};
},
getRecordColor: function(record) {
var color = 'black';
if (record.get('isNew')) {
color = 'green';
} else if (record.get('isDirty')) {
color = 'blue';
}
return color;
},
observeRecord: function(record, recordUpdated) {
var releaseMethods = Ember.A(), self = this;
var keysToObserve = Ember.A(['id', 'isNew', 'isDirty']);
record.eachAttribute(function(key) {
keysToObserve.push(key);
});
keysToObserve.forEach(function(key) {
var handler = function() {
recordUpdated(self.wrapRecord(record));
};
Ember.addObserver(record, key, handler);
releaseMethods.push(function() {
Ember.removeObserver(record, key, handler);
});
});
var release = function() {
releaseMethods.forEach(function(fn) { fn(); } );
};
return release;
}
});
});
define("ember-data/system/debug/debug_info",
["ember-data/system/model","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Model = __dependency1__.Model;
Model.reopen({
/**
Provides info about the model for debugging purposes
by grouping the properties into more semantic groups.
Meant to be used by debugging tools such as the Chrome Ember Extension.
- Groups all attributes in "Attributes" group.
- Groups all belongsTo relationships in "Belongs To" group.
- Groups all hasMany relationships in "Has Many" group.
- Groups all flags in "Flags" group.
- Flags relationship CPs as expensive properties.
@method _debugInfo
@for DS.Model
@private
*/
_debugInfo: function() {
var attributes = ['id'],
relationships = { belongsTo: [], hasMany: [] },
expensiveProperties = [];
this.eachAttribute(function(name, meta) {
attributes.push(name);
}, this);
this.eachRelationship(function(name, relationship) {
relationships[relationship.kind].push(name);
expensiveProperties.push(name);
});
var groups = [
{
name: 'Attributes',
properties: attributes,
expand: true
},
{
name: 'Belongs To',
properties: relationships.belongsTo,
expand: true
},
{
name: 'Has Many',
properties: relationships.hasMany,
expand: true
},
{
name: 'Flags',
properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid']
}
];
return {
propertyInfo: {
// include all other mixins / properties (not just the grouped ones)
includeOtherProperties: true,
groups: groups,
// don't pre-calculate unless cached
expensiveProperties: expensiveProperties
}
};
}
});
__exports__["default"] = Model;
});
define("ember-data/system/model",
["ember-data/system/model/model","ember-data/system/model/attributes","ember-data/system/model/states","ember-data/system/model/errors","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
/**
@module ember-data
*/
var Model = __dependency1__["default"];
var attr = __dependency2__["default"];
var RootState = __dependency3__["default"];
var Errors = __dependency4__["default"];
__exports__.Model = Model;
__exports__.RootState = RootState;
__exports__.attr = attr;
__exports__.Errors = Errors;
});
define("ember-data/system/model/attributes",
["ember-data/system/model/model","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Model = __dependency1__["default"];
/**
@module ember-data
*/
var get = Ember.get;
/**
@class Model
@namespace DS
*/
Model.reopenClass({
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are the meta object for the
property.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
var attributes = Ember.get(App.Person, 'attributes')
attributes.forEach(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@property attributes
@static
@type {Ember.Map}
@readOnly
*/
attributes: Ember.computed(function() {
var map = Ember.Map.create();
this.eachComputedProperty(function(name, meta) {
if (meta.isAttribute) {
Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id');
meta.name = name;
map.set(name, meta);
}
});
return map;
}).readOnly(),
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are type of transformation
applied to each attribute. This map does not include any
attributes that do not have an transformation type.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
var transformedAttributes = Ember.get(App.Person, 'transformedAttributes')
transformedAttributes.forEach(function(field, type) {
console.log(field, type);
});
// prints:
// lastName string
// birthday date
```
@property transformedAttributes
@static
@type {Ember.Map}
@readOnly
*/
transformedAttributes: Ember.computed(function() {
var map = Ember.Map.create();
this.eachAttribute(function(key, meta) {
if (meta.type) {
map.set(key, meta.type);
}
});
return map;
}).readOnly(),
/**
Iterates through the attributes of the model, calling the passed function on each
attribute.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, meta);
```
- `name` the name of the current property in the iteration
- `meta` the meta object for the attribute property in the iteration
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
App.Person.eachAttribute(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@method eachAttribute
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@static
*/
eachAttribute: function(callback, binding) {
get(this, 'attributes').forEach(function(name, meta) {
callback.call(binding, name, meta);
}, binding);
},
/**
Iterates through the transformedAttributes of the model, calling
the passed function on each attribute. Note the callback will not be
called for any attributes that do not have an transformation type.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, type);
```
- `name` the name of the current property in the iteration
- `type` a string containing the name of the type of transformed
applied to the attribute
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
App.Person.eachTransformedAttribute(function(name, type) {
console.log(name, type);
});
// prints:
// lastName string
// birthday date
```
@method eachTransformedAttribute
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@static
*/
eachTransformedAttribute: function(callback, binding) {
get(this, 'transformedAttributes').forEach(function(name, type) {
callback.call(binding, name, type);
});
}
});
Model.reopen({
eachAttribute: function(callback, binding) {
this.constructor.eachAttribute(callback, binding);
}
});
function getDefaultValue(record, options, key) {
if (typeof options.defaultValue === "function") {
return options.defaultValue.apply(null, arguments);
} else {
return options.defaultValue;
}
}
function hasValue(record, key) {
return record._attributes.hasOwnProperty(key) ||
record._inFlightAttributes.hasOwnProperty(key) ||
record._data.hasOwnProperty(key);
}
function getValue(record, key) {
if (record._attributes.hasOwnProperty(key)) {
return record._attributes[key];
} else if (record._inFlightAttributes.hasOwnProperty(key)) {
return record._inFlightAttributes[key];
} else {
return record._data[key];
}
}
/**
`DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html).
By default, attributes are passed through as-is, however you can specify an
optional type to have the value automatically transformed.
Ember Data ships with four basic transform types: `string`, `number`,
`boolean` and `date`. You can define your own transforms by subclassing
[DS.Transform](/api/data/classes/DS.Transform.html).
Note that you cannot use `attr` to define an attribute of `id`.
`DS.attr` takes an optional hash as a second parameter, currently
supported options are:
- `defaultValue`: Pass a string or a function to be called to set the attribute
to a default value if none is supplied.
Example
```javascript
var attr = DS.attr;
App.User = DS.Model.extend({
username: attr('string'),
email: attr('string'),
verified: attr('boolean', {defaultValue: false})
});
```
@namespace
@method attr
@for DS
@param {String} type the attribute type
@param {Object} options a hash of options
@return {Attribute}
*/
__exports__["default"] = function attr(type, options) {
options = options || {};
var meta = {
type: type,
isAttribute: true,
options: options
};
return Ember.computed('data', function(key, value) {
if (arguments.length > 1) {
Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id');
var oldValue = getValue(this, key);
if (value !== oldValue) {
// Add the new value to the changed attributes hash; it will get deleted by
// the 'didSetProperty' handler if it is no different from the original value
this._attributes[key] = value;
this.send('didSetProperty', {
name: key,
oldValue: oldValue,
originalValue: this._data[key],
value: value
});
}
return value;
} else if (hasValue(this, key)) {
return getValue(this, key);
} else {
return getDefaultValue(this, options, key);
}
// `data` is never set directly. However, it may be
// invalidated from the state manager's setData
// event.
}).meta(meta);
};
});
define("ember-data/system/model/errors",
["exports"],
function(__exports__) {
"use strict";
var get = Ember.get;
var isEmpty = Ember.isEmpty;
var map = Ember.EnumerableUtils.map;
/**
@module ember-data
*/
/**
Holds validation errors for a given record organized by attribute names.
Every DS.Model has an `errors` property that is an instance of
`DS.Errors`. This can be used to display validation error
messages returned from the server when a `record.save()` rejects.
This works automatically with `DS.ActiveModelAdapter`, but you
can implement [ajaxError](api/data/classes/DS.RESTAdapter.html#method_ajaxError)
in other adapters as well.
For Example, if you had an `User` model that looked like this:
```javascript
App.User = DS.Model.extend({
username: attr('string'),
email: attr('string')
});
```
And you attempted to save a record that did not validate on the backend.
```javascript
var user = store.createRecord('user', {
username: 'tomster',
email: 'invalidEmail'
});
user.save();
```
Your backend data store might return a response that looks like
this. This response will be used to populate the error object.
```javascript
{
"errors": {
"username": ["This username is already taken!"],
"email": ["Doesn't look like a valid email."]
}
}
```
Errors can be displayed to the user by accessing their property name
or using the `messages` property to get an array of all errors.
```handlebars
{{#each errors.messages}}
<div class="error">
{{message}}
</div>
{{/each}}
<label>Username: {{input value=username}} </label>
{{#each errors.username}}
<div class="error">
{{message}}
</div>
{{/each}}
<label>Email: {{input value=email}} </label>
{{#each errors.email}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@class Errors
@namespace DS
@extends Ember.Object
@uses Ember.Enumerable
@uses Ember.Evented
*/
__exports__["default"] = Ember.Object.extend(Ember.Enumerable, Ember.Evented, {
/**
Register with target handler
@method registerHandlers
@param {Object} target
@param {Function} becameInvalid
@param {Function} becameValid
*/
registerHandlers: function(target, becameInvalid, becameValid) {
this.on('becameInvalid', target, becameInvalid);
this.on('becameValid', target, becameValid);
},
/**
@property errorsByAttributeName
@type {Ember.MapWithDefault}
@private
*/
errorsByAttributeName: Ember.reduceComputed("content", {
initialValue: function() {
return Ember.MapWithDefault.create({
defaultValue: function() {
return Ember.A();
}
});
},
addedItem: function(errors, error) {
errors.get(error.attribute).pushObject(error);
return errors;
},
removedItem: function(errors, error) {
errors.get(error.attribute).removeObject(error);
return errors;
}
}),
/**
Returns errors for a given attribute
```javascript
var user = store.createRecord('user', {
username: 'tomster',
email: 'invalidEmail'
});
user.save().catch(function(){
user.get('errors').errorsFor('email'); // ["Doesn't look like a valid email."]
});
```
@method errorsFor
@param {String} attribute
@return {Array}
*/
errorsFor: function(attribute) {
return get(this, 'errorsByAttributeName').get(attribute);
},
/**
An array containing all of the error messages for this
record. This is useful for displaying all errors to the user.
```handlebars
{{#each errors.messages}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@property messages
@type {Array}
*/
messages: Ember.computed.mapBy('content', 'message'),
/**
@property content
@type {Array}
@private
*/
content: Ember.computed(function() {
return Ember.A();
}),
/**
@method unknownProperty
@private
*/
unknownProperty: function(attribute) {
var errors = this.errorsFor(attribute);
if (isEmpty(errors)) { return null; }
return errors;
},
/**
@method nextObject
@private
*/
nextObject: function(index, previousObject, context) {
return get(this, 'content').objectAt(index);
},
/**
Total number of errors.
@property length
@type {Number}
@readOnly
*/
length: Ember.computed.oneWay('content.length').readOnly(),
/**
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: Ember.computed.not('length').readOnly(),
/**
Adds error messages to a given attribute and sends
`becameInvalid` event to the record.
Example:
```javascript
if (!user.get('username') {
user.get('errors').add('username', 'This field is required');
}
```
@method add
@param {String} attribute
@param {Array|String} messages
*/
add: function(attribute, messages) {
var wasEmpty = get(this, 'isEmpty');
messages = this._findOrCreateMessages(attribute, messages);
get(this, 'content').addObjects(messages);
this.notifyPropertyChange(attribute);
this.enumerableContentDidChange();
if (wasEmpty && !get(this, 'isEmpty')) {
this.trigger('becameInvalid');
}
},
/**
@method _findOrCreateMessages
@private
*/
_findOrCreateMessages: function(attribute, messages) {
var errors = this.errorsFor(attribute);
return map(Ember.makeArray(messages), function(message) {
return errors.findBy('message', message) || {
attribute: attribute,
message: message
};
});
},
/**
Removes all error messages from the given attribute and sends
`becameValid` event to the record if there no more errors left.
Example:
```javascript
App.User = DS.Model.extend({
email: DS.attr('string'),
twoFactorAuth: DS.attr('boolean'),
phone: DS.attr('string')
});
App.UserEditRoute = Ember.Route.extend({
actions: {
save: function(user) {
if (!user.get('twoFactorAuth')) {
user.get('errors').remove('phone');
}
user.save();
}
}
});
```
@method remove
@param {String} attribute
*/
remove: function(attribute) {
if (get(this, 'isEmpty')) { return; }
var content = get(this, 'content').rejectBy('attribute', attribute);
get(this, 'content').setObjects(content);
this.notifyPropertyChange(attribute);
this.enumerableContentDidChange();
if (get(this, 'isEmpty')) {
this.trigger('becameValid');
}
},
/**
Removes all error messages and sends `becameValid` event
to the record.
Example:
```javascript
App.UserEditRoute = Ember.Route.extend({
actions: {
retrySave: function(user) {
user.get('errors').clear();
user.save();
}
}
});
```
@method clear
*/
clear: function() {
if (get(this, 'isEmpty')) { return; }
get(this, 'content').clear();
this.enumerableContentDidChange();
this.trigger('becameValid');
},
/**
Checks if there is error messages for the given attribute.
```javascript
App.UserEditRoute = Ember.Route.extend({
actions: {
save: function(user) {
if (user.get('errors').has('email')) {
return alert('Please update your email before attempting to save.');
}
user.save();
}
}
});
```
@method has
@param {String} attribute
@return {Boolean} true if there some errors on given attribute
*/
has: function(attribute) {
return !isEmpty(this.errorsFor(attribute));
}
});
});
define("ember-data/system/model/model",
["ember-data/system/model/states","ember-data/system/model/errors","ember-data/system/store","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var RootState = __dependency1__["default"];
var Errors = __dependency2__["default"];
var PromiseObject = __dependency3__.PromiseObject;
/**
@module ember-data
*/
var get = Ember.get;
var set = Ember.set;
var merge = Ember.merge;
var Promise = Ember.RSVP.Promise;
var forEach = Ember.ArrayPolyfills.forEach;
var JSONSerializer;
var retrieveFromCurrentState = Ember.computed('currentState', function(key, value) {
return get(get(this, 'currentState'), key);
}).readOnly();
var _extractPivotNameCache = Object.create(null);
var _splitOnDotCache = Object.create(null);
function splitOnDot(name) {
return _splitOnDotCache[name] || (
_splitOnDotCache[name] = name.split('.')
);
}
function extractPivotName(name) {
return _extractPivotNameCache[name] || (
_extractPivotNameCache[name] = splitOnDot(name)[0]
);
}
/**
The model class that all Ember Data records descend from.
@class Model
@namespace DS
@extends Ember.Object
@uses Ember.Evented
*/
var Model = Ember.Object.extend(Ember.Evented, {
_recordArrays: undefined,
_relationships: undefined,
_loadingRecordArrays: undefined,
/**
If this property is `true` the record is in the `empty`
state. Empty is the first state all records enter after they have
been created. Most records created by the store will quickly
transition to the `loading` state if data needs to be fetched from
the server or the `created` state if the record is created on the
client. A record can also enter the empty state if the adapter is
unable to locate the record.
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loading` state. A
record enters this state when the store asks the adapter for its
data. It remains in this state until the adapter provides the
requested data.
@property isLoading
@type {Boolean}
@readOnly
*/
isLoading: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loaded` state. A
record enters this state when its data is populated. Most of a
record's lifecycle is spent inside substates of the `loaded`
state.
Example
```javascript
var record = store.createRecord('model');
record.get('isLoaded'); // true
store.find('model', 1).then(function(model) {
model.get('isLoaded'); // true
});
```
@property isLoaded
@type {Boolean}
@readOnly
*/
isLoaded: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `dirty` state. The
record has local changes that have not yet been saved by the
adapter. This includes records that have been created (but not yet
saved) or deleted.
Example
```javascript
var record = store.createRecord('model');
record.get('isDirty'); // true
store.find('model', 1).then(function(model) {
model.get('isDirty'); // false
model.set('foo', 'some value');
model.get('isDirty'); // true
});
```
@property isDirty
@type {Boolean}
@readOnly
*/
isDirty: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `saving` state. A
record enters the saving state when `save` is called, but the
adapter has not yet acknowledged that the changes have been
persisted to the backend.
Example
```javascript
var record = store.createRecord('model');
record.get('isSaving'); // false
var promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
record.get('isSaving'); // false
});
```
@property isSaving
@type {Boolean}
@readOnly
*/
isSaving: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `deleted` state
and has been marked for deletion. When `isDeleted` is true and
`isDirty` is true, the record is deleted locally but the deletion
was not yet persisted. When `isSaving` is true, the change is
in-flight. When both `isDirty` and `isSaving` are false, the
change has persisted.
Example
```javascript
var record = store.createRecord('model');
record.get('isDeleted'); // false
record.deleteRecord();
// Locally deleted
record.get('isDeleted'); // true
record.get('isDirty'); // true
record.get('isSaving'); // false
// Persisting the deletion
var promise = record.save();
record.get('isDeleted'); // true
record.get('isSaving'); // true
// Deletion Persisted
promise.then(function() {
record.get('isDeleted'); // true
record.get('isSaving'); // false
record.get('isDirty'); // false
});
```
@property isDeleted
@type {Boolean}
@readOnly
*/
isDeleted: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `new` state. A
record will be in the `new` state when it has been created on the
client and the adapter has not yet report that it was successfully
saved.
Example
```javascript
var record = store.createRecord('model');
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
```
@property isNew
@type {Boolean}
@readOnly
*/
isNew: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `valid` state.
A record will be in the `valid` state when the adapter did not report any
server-side validation failures.
@property isValid
@type {Boolean}
@readOnly
*/
isValid: retrieveFromCurrentState,
/**
If the record is in the dirty state this property will report what
kind of change has caused it to move into the dirty
state. Possible values are:
- `created` The record has been created by the client and not yet saved to the adapter.
- `updated` The record has been updated by the client and not yet saved to the adapter.
- `deleted` The record has been deleted by the client and not yet saved to the adapter.
Example
```javascript
var record = store.createRecord('model');
record.get('dirtyType'); // 'created'
```
@property dirtyType
@type {String}
@readOnly
*/
dirtyType: retrieveFromCurrentState,
/**
If `true` the adapter reported that it was unable to save local
changes to the backend for any reason other than a server-side
validation error.
Example
```javascript
record.get('isError'); // false
record.set('foo', 'valid value');
record.save().then(null, function() {
record.get('isError'); // true
});
```
@property isError
@type {Boolean}
@readOnly
*/
isError: false,
/**
If `true` the store is attempting to reload the record form the adapter.
Example
```javascript
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true
```
@property isReloading
@type {Boolean}
@readOnly
*/
isReloading: false,
/**
The `clientId` property is a transient numerical identifier
generated at runtime by the data store. It is important
primarily because newly created objects may not yet have an
externally generated id.
@property clientId
@private
@type {Number|String}
*/
clientId: null,
/**
All ember models have an id property. This is an identifier
managed by an external source. These are always coerced to be
strings before being used internally. Note when declaring the
attributes for a model it is an error to declare an id
attribute.
```javascript
var record = store.createRecord('model');
record.get('id'); // null
store.find('model', 1).then(function(model) {
model.get('id'); // '1'
});
```
@property id
@type {String}
*/
id: null,
/**
@property currentState
@private
@type {Object}
*/
currentState: RootState.empty,
/**
When the record is in the `invalid` state this object will contain
any errors returned by the adapter. When present the errors hash
typically contains keys corresponding to the invalid property names
and values which are an array of error messages.
```javascript
record.get('errors.length'); // 0
record.set('foo', 'invalid value');
record.save().then(null, function() {
record.get('errors').get('foo'); // ['foo should be a number.']
});
```
@property errors
@type {DS.Errors}
*/
errors: Ember.computed(function() {
var errors = Errors.create();
errors.registerHandlers(this, function() {
this.send('becameInvalid');
}, function() {
this.send('becameValid');
});
return errors;
}).readOnly(),
/**
Create a JSON representation of the record, using the serialization
strategy of the store's adapter.
`serialize` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method serialize
@param {Object} options
@return {Object} an object whose values are primitive JSON values only
*/
serialize: function(options) {
var store = get(this, 'store');
return store.serialize(this, options);
},
/**
Use [DS.JSONSerializer](DS.JSONSerializer.html) to
get the JSON representation of a record.
`toJSON` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method toJSON
@param {Object} options
@return {Object} A JSON representation of the object.
*/
toJSON: function(options) {
if (!JSONSerializer) { JSONSerializer = requireModule("ember-data/serializers/json_serializer")["default"]; }
// container is for lazy transform lookups
var serializer = JSONSerializer.create({ container: this.container });
return serializer.serialize(this, options);
},
/**
Fired when the record is loaded from the server.
@event didLoad
*/
didLoad: Ember.K,
/**
Fired when the record is updated.
@event didUpdate
*/
didUpdate: Ember.K,
/**
Fired when the record is created.
@event didCreate
*/
didCreate: Ember.K,
/**
Fired when the record is deleted.
@event didDelete
*/
didDelete: Ember.K,
/**
Fired when the record becomes invalid.
@event becameInvalid
*/
becameInvalid: Ember.K,
/**
Fired when the record enters the error state.
@event becameError
*/
becameError: Ember.K,
/**
@property data
@private
@type {Object}
*/
data: Ember.computed(function() {
this._data = this._data || {};
return this._data;
}).readOnly(),
_data: null,
init: function() {
this._super();
this._setup();
},
_setup: function() {
this._changesToSync = {};
this._deferredTriggers = [];
this._data = {};
this._attributes = {};
this._inFlightAttributes = {};
this._relationships = {};
},
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send: function(name, context) {
var currentState = get(this, 'currentState');
if (!currentState[name]) {
this._unhandledEvent(currentState, name, context);
}
return currentState[name](this, context);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo: function(name) {
// POSSIBLE TODO: Remove this code and replace with
// always having direct references to state objects
var pivotName = extractPivotName(name);
var currentState = get(this, 'currentState');
var state = currentState;
do {
if (state.exit) { state.exit(this); }
state = state.parentState;
} while (!state.hasOwnProperty(pivotName));
var path = splitOnDot(name);
var setups = [], enters = [], i, l;
for (i=0, l=path.length; i<l; i++) {
state = state[path[i]];
if (state.enter) { enters.push(state); }
if (state.setup) { setups.push(state); }
}
for (i=0, l=enters.length; i<l; i++) {
enters[i].enter(this);
}
set(this, 'currentState', state);
for (i=0, l=setups.length; i<l; i++) {
setups[i].setup(this);
}
this.updateRecordArraysLater();
},
_unhandledEvent: function(state, name, context) {
var errorMessage = "Attempted to handle event `" + name + "` ";
errorMessage += "on " + String(this) + " while in state ";
errorMessage += state.stateName + ". ";
if (context !== undefined) {
errorMessage += "Called with " + Ember.inspect(context) + ".";
}
throw new Ember.Error(errorMessage);
},
withTransaction: function(fn) {
var transaction = get(this, 'transaction');
if (transaction) { fn(transaction); }
},
/**
@method loadingData
@private
@param {Promise} promise
*/
loadingData: function(promise) {
this.send('loadingData', promise);
},
/**
@method loadedData
@private
*/
loadedData: function() {
this.send('loadedData');
},
/**
@method notFound
@private
*/
notFound: function() {
this.send('notFound');
},
/**
@method pushedData
@private
*/
pushedData: function() {
this.send('pushedData');
},
/**
Marks the record as deleted but does not save it. You must call
`save` afterwards if you want to persist it. You might use this
method if you want to allow the user to still `rollback()` a
delete after it was made.
Example
```javascript
App.ModelDeleteRoute = Ember.Route.extend({
actions: {
softDelete: function() {
this.controller.get('model').deleteRecord();
},
confirm: function() {
this.controller.get('model').save();
},
undo: function() {
this.controller.get('model').rollback();
}
}
});
```
@method deleteRecord
*/
deleteRecord: function() {
this.send('deleteRecord');
},
/**
Same as `deleteRecord`, but saves the record immediately.
Example
```javascript
App.ModelDeleteRoute = Ember.Route.extend({
actions: {
delete: function() {
var controller = this.controller;
controller.get('model').destroyRecord().then(function() {
controller.transitionToRoute('model.index');
});
}
}
});
```
@method destroyRecord
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
destroyRecord: function() {
this.deleteRecord();
return this.save();
},
/**
@method unloadRecord
@private
*/
unloadRecord: function() {
if (this.isDestroyed) { return; }
this.send('unloadRecord');
},
/**
@method clearRelationships
@private
*/
clearRelationships: function() {
this.eachRelationship(function(name, relationship) {
if (relationship.kind === 'belongsTo') {
set(this, name, null);
} else if (relationship.kind === 'hasMany') {
var hasMany = this._relationships[name];
if (hasMany) { // relationships are created lazily
hasMany.destroy();
}
}
}, this);
},
/**
@method updateRecordArrays
@private
*/
updateRecordArrays: function() {
this._updatingRecordArraysLater = false;
get(this, 'store').dataWasUpdated(this.constructor, this);
},
/**
When a find request is triggered on the store, the user can optionally passed in
attributes and relationships to be preloaded. These are meant to behave as if they
came back from the server, expect the user obtained them out of band and is informing
the store of their existence. The most common use case is for supporting client side
nested URLs, such as `/posts/1/comments/2` so the user can do
`store.find('comment', 2, {post:1})` without having to fetch the post.
Preloaded data can be attributes and relationships passed in either as IDs or as actual
models.
@method _preloadData
@private
@param {Object} preload
*/
_preloadData: function(preload) {
var record = this;
//TODO(Igor) consider the polymorphic case
forEach.call(Ember.keys(preload), function(key) {
var preloadValue = get(preload, key);
var relationshipMeta = record.constructor.metaForProperty(key);
if (relationshipMeta.isRelationship) {
record._preloadRelationship(key, preloadValue);
} else {
get(record, '_data')[key] = preloadValue;
}
});
},
_preloadRelationship: function(key, preloadValue) {
var relationshipMeta = this.constructor.metaForProperty(key);
var type = relationshipMeta.type;
if (relationshipMeta.kind === 'hasMany'){
this._preloadHasMany(key, preloadValue, type);
} else {
this._preloadBelongsTo(key, preloadValue, type);
}
},
_preloadHasMany: function(key, preloadValue, type) {
Ember.assert("You need to pass in an array to set a hasMany property on a record", Ember.isArray(preloadValue));
var record = this;
forEach.call(preloadValue, function(recordToPush) {
recordToPush = record._convertStringOrNumberIntoRecord(recordToPush, type);
get(record, key).pushObject(recordToPush);
});
},
_preloadBelongsTo: function(key, preloadValue, type){
var recordToPush = this._convertStringOrNumberIntoRecord(preloadValue, type);
set(this, key, recordToPush);
},
_convertStringOrNumberIntoRecord: function(value, type) {
if (Ember.typeOf(value) === 'string' || Ember.typeOf(value) === 'number'){
return this.store.recordForId(type, value);
}
return value;
},
/**
Returns an object, whose keys are changed properties, and value is
an [oldProp, newProp] array.
Example
```javascript
App.Mascot = DS.Model.extend({
name: attr('string')
});
var person = store.createRecord('person');
person.changedAttributes(); // {}
person.set('name', 'Tomster');
person.changedAttributes(); // {name: [undefined, 'Tomster']}
```
@method changedAttributes
@return {Object} an object, whose keys are changed properties,
and value is an [oldProp, newProp] array.
*/
changedAttributes: function() {
var oldData = get(this, '_data');
var newData = get(this, '_attributes');
var diffData = {};
var prop;
for (prop in newData) {
diffData[prop] = [oldData[prop], newData[prop]];
}
return diffData;
},
/**
@method adapterWillCommit
@private
*/
adapterWillCommit: function() {
this.send('willCommit');
},
/**
If the adapter did not return a hash in response to a commit,
merge the changed attributes and relationships into the existing
saved data.
@method adapterDidCommit
*/
adapterDidCommit: function(data) {
set(this, 'isError', false);
if (data) {
this._data = data;
} else {
Ember.mixin(this._data, this._inFlightAttributes);
}
this._inFlightAttributes = {};
this.send('didCommit');
this.updateRecordArraysLater();
if (!data) { return; }
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
/**
@method adapterDidDirty
@private
*/
adapterDidDirty: function() {
this.send('becomeDirty');
this.updateRecordArraysLater();
},
dataDidChange: Ember.observer(function() {
this.reloadHasManys();
}, 'data'),
reloadHasManys: function() {
var relationships = get(this.constructor, 'relationshipsByName');
this.updateRecordArraysLater();
relationships.forEach(function(name, relationship) {
if (this._data.links && this._data.links[name]) { return; }
if (relationship.kind === 'hasMany') {
this.hasManyDidChange(relationship.key);
}
}, this);
},
hasManyDidChange: function(key) {
var hasMany = this._relationships[key];
if (hasMany) {
var records = this._data[key] || [];
set(hasMany, 'content', Ember.A(records));
set(hasMany, 'isLoaded', true);
hasMany.trigger('didLoad');
}
},
/**
@method updateRecordArraysLater
@private
*/
updateRecordArraysLater: function() {
// quick hack (something like this could be pushed into run.once
if (this._updatingRecordArraysLater) { return; }
this._updatingRecordArraysLater = true;
Ember.run.schedule('actions', this, this.updateRecordArrays);
},
/**
@method setupData
@private
@param {Object} data
@param {Boolean} partial the data should be merged into
the existing data, not replace it.
*/
setupData: function(data, partial) {
if (partial) {
Ember.merge(this._data, data);
} else {
this._data = data;
}
var relationships = this._relationships;
this.eachRelationship(function(name, rel) {
if (data.links && data.links[name]) { return; }
if (rel.options.async) { relationships[name] = null; }
});
if (data) { this.pushedData(); }
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
materializeId: function(id) {
set(this, 'id', id);
},
materializeAttributes: function(attributes) {
Ember.assert("Must pass a hash of attributes to materializeAttributes", !!attributes);
merge(this._data, attributes);
},
materializeAttribute: function(name, value) {
this._data[name] = value;
},
/**
@method updateHasMany
@private
@param {String} name
@param {Array} records
*/
updateHasMany: function(name, records) {
this._data[name] = records;
this.hasManyDidChange(name);
},
/**
@method updateBelongsTo
@private
@param {String} name
@param {DS.Model} record
*/
updateBelongsTo: function(name, record) {
this._data[name] = record;
},
/**
If the model `isDirty` this function will discard any unsaved
changes
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollback();
record.get('name'); // 'Untitled Document'
```
@method rollback
*/
rollback: function() {
this._attributes = {};
if (get(this, 'isError')) {
this._inFlightAttributes = {};
set(this, 'isError', false);
}
if (!get(this, 'isValid')) {
this._inFlightAttributes = {};
}
this.send('rolledBack');
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
toStringExtension: function() {
return get(this, 'id');
},
/**
The goal of this method is to temporarily disable specific observers
that take action in response to application changes.
This allows the system to make changes (such as materialization and
rollback) that should not trigger secondary behavior (such as setting an
inverse relationship or marking records as dirty).
The specific implementation will likely change as Ember proper provides
better infrastructure for suspending groups of observers, and if Array
observation becomes more unified with regular observers.
@method suspendRelationshipObservers
@private
@param callback
@param binding
*/
suspendRelationshipObservers: function(callback, binding) {
var observers = get(this.constructor, 'relationshipNames').belongsTo;
var self = this;
try {
this._suspendedRelationships = true;
Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() {
Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() {
callback.call(binding || self);
});
});
} finally {
this._suspendedRelationships = false;
}
},
/**
Save the record and persist any changes to the record to an
extenal source via the adapter.
Example
```javascript
record.set('name', 'Tomster');
record.save().then(function(){
// Success callback
}, function() {
// Error callback
});
```
@method save
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
save: function() {
var promiseLabel = "DS: Model#save " + this;
var resolver = Ember.RSVP.defer(promiseLabel);
this.get('store').scheduleSave(this, resolver);
this._inFlightAttributes = this._attributes;
this._attributes = {};
return PromiseObject.create({
promise: resolver.promise
});
},
/**
Reload the record from the adapter.
This will only work if the record has already finished loading
and has not yet been modified (`isLoaded` but not `isDirty`,
or `isSaving`).
Example
```javascript
App.ModelViewRoute = Ember.Route.extend({
actions: {
reload: function() {
this.controller.get('model').reload();
}
}
});
```
@method reload
@return {Promise} a promise that will be resolved with the record when the
adapter returns successfully or rejected if the adapter returns
with an error.
*/
reload: function() {
set(this, 'isReloading', true);
var record = this;
var promiseLabel = "DS: Model#reload of " + this;
var promise = new Promise(function(resolve){
record.send('reloadRecord', resolve);
}, promiseLabel).then(function() {
record.set('isReloading', false);
record.set('isError', false);
return record;
}, function(reason) {
record.set('isError', true);
throw reason;
}, "DS: Model#reload complete, update flags");
return PromiseObject.create({
promise: promise
});
},
// FOR USE DURING COMMIT PROCESS
adapterDidUpdateAttribute: function(attributeName, value) {
// If a value is passed in, update the internal attributes and clear
// the attribute cache so it picks up the new value. Otherwise,
// collapse the current value into the internal attributes because
// the adapter has acknowledged it.
if (value !== undefined) {
this._data[attributeName] = value;
this.notifyPropertyChange(attributeName);
} else {
this._data[attributeName] = this._inFlightAttributes[attributeName];
}
this.updateRecordArraysLater();
},
/**
@method adapterDidInvalidate
@private
*/
adapterDidInvalidate: function(errors) {
var recordErrors = get(this, 'errors');
function addError(name) {
if (errors[name]) {
recordErrors.add(name, errors[name]);
}
}
this.eachAttribute(addError);
this.eachRelationship(addError);
},
/**
@method adapterDidError
@private
*/
adapterDidError: function() {
this.send('becameError');
set(this, 'isError', true);
},
/**
Override the default event firing from Ember.Evented to
also call methods with the given name.
@method trigger
@private
@param name
*/
trigger: function(name) {
Ember.tryInvoke(this, name, [].slice.call(arguments, 1));
this._super.apply(this, arguments);
},
triggerLater: function() {
if (this._deferredTriggers.push(arguments) !== 1) { return; }
Ember.run.schedule('actions', this, '_triggerDeferredTriggers');
},
_triggerDeferredTriggers: function() {
for (var i=0, l= this._deferredTriggers.length; i<l; i++) {
this.trigger.apply(this, this._deferredTriggers[i]);
}
this._deferredTriggers.length = 0;
},
willDestroy: function() {
this._super();
this.clearRelationships();
},
// This is a temporary solution until we refactor DS.Model to not
// rely on the data property.
willMergeMixin: function(props) {
Ember.assert('`data` is a reserved property name on DS.Model objects. Please choose a different property name for ' + this.constructor.toString(), !props.data);
}
});
Model.reopenClass({
/**
Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model
instances from within the store, but if end users accidentally call `create()`
(instead of `createRecord()`), we can raise an error.
@method _create
@private
@static
*/
_create: Model.create,
/**
Override the class' `create()` method to raise an error. This
prevents end users from inadvertently calling `create()` instead
of `createRecord()`. The store is still able to create instances
by calling the `_create()` method. To create an instance of a
`DS.Model` use [store.createRecord](DS.Store.html#method_createRecord).
@method create
@private
@static
*/
create: function() {
throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.");
}
});
__exports__["default"] = Model;
});
define("ember-data/system/model/states",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
var get = Ember.get;
var set = Ember.set;
/*
This file encapsulates the various states that a record can transition
through during its lifecycle.
*/
/**
### State
Each record has a `currentState` property that explicitly tracks what
state a record is in at any given time. For instance, if a record is
newly created and has not yet been sent to the adapter to be saved,
it would be in the `root.loaded.created.uncommitted` state. If a
record has had local modifications made to it that are in the
process of being saved, the record would be in the
`root.loaded.updated.inFlight` state. (This state paths will be
explained in more detail below.)
Events are sent by the record or its store to the record's
`currentState` property. How the state reacts to these events is
dependent on which state it is in. In some states, certain events
will be invalid and will cause an exception to be raised.
States are hierarchical and every state is a substate of the
`RootState`. For example, a record can be in the
`root.deleted.uncommitted` state, then transition into the
`root.deleted.inFlight` state. If a child state does not implement
an event handler, the state manager will attempt to invoke the event
on all parent states until the root state is reached. The state
hierarchy of a record is described in terms of a path string. You
can determine a record's current state by getting the state's
`stateName` property:
```javascript
record.get('currentState.stateName');
//=> "root.created.uncommitted"
```
The hierarchy of valid states that ship with ember data looks like
this:
```text
* root
* deleted
* saved
* uncommitted
* inFlight
* empty
* loaded
* created
* uncommitted
* inFlight
* saved
* updated
* uncommitted
* inFlight
* loading
```
The `DS.Model` states are themselves stateless. What that means is
that, the hierarchical states that each of *those* points to is a
shared data structure. For performance reasons, instead of each
record getting its own copy of the hierarchy of states, each record
points to this global, immutable shared instance. How does a state
know which record it should be acting on? We pass the record
instance into the state's event handlers as the first argument.
The record passed as the first parameter is where you should stash
state about the record if needed; you should never store data on the state
object itself.
### Events and Flags
A state may implement zero or more events and flags.
#### Events
Events are named functions that are invoked when sent to a record. The
record will first look for a method with the given name on the
current state. If no method is found, it will search the current
state's parent, and then its grandparent, and so on until reaching
the top of the hierarchy. If the root is reached without an event
handler being found, an exception will be raised. This can be very
helpful when debugging new features.
Here's an example implementation of a state with a `myEvent` event handler:
```javascript
aState: DS.State.create({
myEvent: function(manager, param) {
console.log("Received myEvent with", param);
}
})
```
To trigger this event:
```javascript
record.send('myEvent', 'foo');
//=> "Received myEvent with foo"
```
Note that an optional parameter can be sent to a record's `send()` method,
which will be passed as the second parameter to the event handler.
Events should transition to a different state if appropriate. This can be
done by calling the record's `transitionTo()` method with a path to the
desired state. The state manager will attempt to resolve the state path
relative to the current state. If no state is found at that path, it will
attempt to resolve it relative to the current state's parent, and then its
parent, and so on until the root is reached. For example, imagine a hierarchy
like this:
* created
* uncommitted <-- currentState
* inFlight
* updated
* inFlight
If we are currently in the `uncommitted` state, calling
`transitionTo('inFlight')` would transition to the `created.inFlight` state,
while calling `transitionTo('updated.inFlight')` would transition to
the `updated.inFlight` state.
Remember that *only events* should ever cause a state transition. You should
never call `transitionTo()` from outside a state's event handler. If you are
tempted to do so, create a new event and send that to the state manager.
#### Flags
Flags are Boolean values that can be used to introspect a record's current
state in a more user-friendly way than examining its state path. For example,
instead of doing this:
```javascript
var statePath = record.get('stateManager.currentPath');
if (statePath === 'created.inFlight') {
doSomething();
}
```
You can say:
```javascript
if (record.get('isNew') && record.get('isSaving')) {
doSomething();
}
```
If your state does not set a value for a given flag, the value will
be inherited from its parent (or the first place in the state hierarchy
where it is defined).
The current set of flags are defined below. If you want to add a new flag,
in addition to the area below, you will also need to declare it in the
`DS.Model` class.
* [isEmpty](DS.Model.html#property_isEmpty)
* [isLoading](DS.Model.html#property_isLoading)
* [isLoaded](DS.Model.html#property_isLoaded)
* [isDirty](DS.Model.html#property_isDirty)
* [isSaving](DS.Model.html#property_isSaving)
* [isDeleted](DS.Model.html#property_isDeleted)
* [isNew](DS.Model.html#property_isNew)
* [isValid](DS.Model.html#property_isValid)
@namespace DS
@class RootState
*/
function hasDefinedProperties(object) {
// Ignore internal property defined by simulated `Ember.create`.
var names = Ember.keys(object);
var i, l, name;
for (i = 0, l = names.length; i < l; i++ ) {
name = names[i];
if (object.hasOwnProperty(name) && object[name]) { return true; }
}
return false;
}
function didSetProperty(record, context) {
if (context.value === context.originalValue) {
delete record._attributes[context.name];
record.send('propertyWasReset', context.name);
} else if (context.value !== context.oldValue) {
record.send('becomeDirty');
}
record.updateRecordArraysLater();
}
// Implementation notes:
//
// Each state has a boolean value for all of the following flags:
//
// * isLoaded: The record has a populated `data` property. When a
// record is loaded via `store.find`, `isLoaded` is false
// until the adapter sets it. When a record is created locally,
// its `isLoaded` property is always true.
// * isDirty: The record has local changes that have not yet been
// saved by the adapter. This includes records that have been
// created (but not yet saved) or deleted.
// * isSaving: The record has been committed, but
// the adapter has not yet acknowledged that the changes have
// been persisted to the backend.
// * isDeleted: The record was marked for deletion. When `isDeleted`
// is true and `isDirty` is true, the record is deleted locally
// but the deletion was not yet persisted. When `isSaving` is
// true, the change is in-flight. When both `isDirty` and
// `isSaving` are false, the change has persisted.
// * isError: The adapter reported that it was unable to save
// local changes to the backend. This may also result in the
// record having its `isValid` property become false if the
// adapter reported that server-side validations failed.
// * isNew: The record was created on the client and the adapter
// did not yet report that it was successfully saved.
// * isValid: The adapter did not report any server-side validation
// failures.
// The dirty state is a abstract state whose functionality is
// shared between the `created` and `updated` states.
//
// The deleted state shares the `isDirty` flag with the
// subclasses of `DirtyState`, but with a very different
// implementation.
//
// Dirty states have three child states:
//
// `uncommitted`: the store has not yet handed off the record
// to be saved.
// `inFlight`: the store has handed off the record to be saved,
// but the adapter has not yet acknowledged success.
// `invalid`: the record has invalid information and cannot be
// send to the adapter yet.
var DirtyState = {
initialState: 'uncommitted',
// FLAGS
isDirty: true,
// SUBSTATES
// When a record first becomes dirty, it is `uncommitted`.
// This means that there are local pending changes, but they
// have not yet begun to be saved, and are not invalid.
uncommitted: {
// EVENTS
didSetProperty: didSetProperty,
//TODO(Igor) reloading now triggers a
//loadingData event, though it seems fine?
loadingData: Ember.K,
propertyWasReset: function(record, name) {
var stillDirty = false;
for (var prop in record._attributes) {
stillDirty = true;
break;
}
if (!stillDirty) { record.send('rolledBack'); }
},
pushedData: Ember.K,
becomeDirty: Ember.K,
willCommit: function(record) {
record.transitionTo('inFlight');
},
reloadRecord: function(record, resolve) {
resolve(get(record, 'store').reloadRecord(record));
},
rolledBack: function(record) {
record.transitionTo('loaded.saved');
},
becameInvalid: function(record) {
record.transitionTo('invalid');
},
rollback: function(record) {
record.rollback();
}
},
// Once a record has been handed off to the adapter to be
// saved, it is in the 'in flight' state. Changes to the
// record cannot be made during this window.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
didSetProperty: didSetProperty,
becomeDirty: Ember.K,
pushedData: Ember.K,
unloadRecord: function(record) {
Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + " `", false);
},
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function(record) {
var dirtyType = get(this, 'dirtyType');
record.transitionTo('saved');
record.send('invokeLifecycleCallbacks', dirtyType);
},
becameInvalid: function(record) {
record.transitionTo('invalid');
record.send('invokeLifecycleCallbacks');
},
becameError: function(record) {
record.transitionTo('uncommitted');
record.triggerLater('becameError', record);
}
},
// A record is in the `invalid` if the adapter has indicated
// the the record failed server-side invalidations.
invalid: {
// FLAGS
isValid: false,
// EVENTS
deleteRecord: function(record) {
record.transitionTo('deleted.uncommitted');
record.clearRelationships();
},
didSetProperty: function(record, context) {
get(record, 'errors').remove(context.name);
didSetProperty(record, context);
},
becomeDirty: Ember.K,
willCommit: function(record) {
get(record, 'errors').clear();
record.transitionTo('inFlight');
},
rolledBack: function(record) {
get(record, 'errors').clear();
},
becameValid: function(record) {
record.transitionTo('uncommitted');
},
invokeLifecycleCallbacks: function(record) {
record.triggerLater('becameInvalid', record);
},
exit: function(record) {
record._inFlightAttributes = {};
}
}
};
// The created and updated states are created outside the state
// chart so we can reopen their substates and add mixins as
// necessary.
function deepClone(object) {
var clone = {}, value;
for (var prop in object) {
value = object[prop];
if (value && typeof value === 'object') {
clone[prop] = deepClone(value);
} else {
clone[prop] = value;
}
}
return clone;
}
function mixin(original, hash) {
for (var prop in hash) {
original[prop] = hash[prop];
}
return original;
}
function dirtyState(options) {
var newState = deepClone(DirtyState);
return mixin(newState, options);
}
var createdState = dirtyState({
dirtyType: 'created',
// FLAGS
isNew: true
});
createdState.uncommitted.rolledBack = function(record) {
record.transitionTo('deleted.saved');
};
var updatedState = dirtyState({
dirtyType: 'updated'
});
createdState.uncommitted.deleteRecord = function(record) {
record.clearRelationships();
record.transitionTo('deleted.saved');
};
createdState.uncommitted.rollback = function(record) {
DirtyState.uncommitted.rollback.apply(this, arguments);
record.transitionTo('deleted.saved');
};
createdState.uncommitted.propertyWasReset = Ember.K;
function assertAgainstUnloadRecord(record) {
Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + "`", false);
}
updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord;
updatedState.uncommitted.deleteRecord = function(record) {
record.transitionTo('deleted.uncommitted');
record.clearRelationships();
};
var RootState = {
// FLAGS
isEmpty: false,
isLoading: false,
isLoaded: false,
isDirty: false,
isSaving: false,
isDeleted: false,
isNew: false,
isValid: true,
// DEFAULT EVENTS
// Trying to roll back if you're not in the dirty state
// doesn't change your state. For example, if you're in the
// in-flight state, rolling back the record doesn't move
// you out of the in-flight state.
rolledBack: Ember.K,
unloadRecord: function(record) {
// clear relationships before moving to deleted state
// otherwise it fails
record.clearRelationships();
record.transitionTo('deleted.saved');
},
propertyWasReset: Ember.K,
// SUBSTATES
// A record begins its lifecycle in the `empty` state.
// If its data will come from the adapter, it will
// transition into the `loading` state. Otherwise, if
// the record is being created on the client, it will
// transition into the `created` state.
empty: {
isEmpty: true,
// EVENTS
loadingData: function(record, promise) {
record._loadingPromise = promise;
record.transitionTo('loading');
},
loadedData: function(record) {
record.transitionTo('loaded.created.uncommitted');
record.suspendRelationshipObservers(function() {
record.notifyPropertyChange('data');
});
},
pushedData: function(record) {
record.transitionTo('loaded.saved');
record.triggerLater('didLoad');
}
},
// A record enters this state when the store asks
// the adapter for its data. It remains in this state
// until the adapter provides the requested data.
//
// Usually, this process is asynchronous, using an
// XHR to retrieve the data.
loading: {
// FLAGS
isLoading: true,
exit: function(record) {
record._loadingPromise = null;
},
// EVENTS
pushedData: function(record) {
record.transitionTo('loaded.saved');
record.triggerLater('didLoad');
set(record, 'isError', false);
},
becameError: function(record) {
record.triggerLater('becameError', record);
},
notFound: function(record) {
record.transitionTo('empty');
}
},
// A record enters this state when its data is populated.
// Most of a record's lifecycle is spent inside substates
// of the `loaded` state.
loaded: {
initialState: 'saved',
// FLAGS
isLoaded: true,
//TODO(Igor) Reloading now triggers a loadingData event,
//but it should be ok?
loadingData: Ember.K,
// SUBSTATES
// If there are no local changes to a record, it remains
// in the `saved` state.
saved: {
setup: function(record) {
var attrs = record._attributes;
var isDirty = false;
for (var prop in attrs) {
if (attrs.hasOwnProperty(prop)) {
isDirty = true;
break;
}
}
if (isDirty) {
record.adapterDidDirty();
}
},
// EVENTS
didSetProperty: didSetProperty,
pushedData: Ember.K,
becomeDirty: function(record) {
record.transitionTo('updated.uncommitted');
},
willCommit: function(record) {
record.transitionTo('updated.inFlight');
},
reloadRecord: function(record, resolve) {
resolve(get(record, 'store').reloadRecord(record));
},
deleteRecord: function(record) {
record.transitionTo('deleted.uncommitted');
record.clearRelationships();
},
unloadRecord: function(record) {
// clear relationships before moving to deleted state
// otherwise it fails
record.clearRelationships();
record.transitionTo('deleted.saved');
},
didCommit: function(record) {
record.send('invokeLifecycleCallbacks', get(record, 'lastDirtyType'));
},
// loaded.saved.notFound would be triggered by a failed
// `reload()` on an unchanged record
notFound: Ember.K
},
// A record is in this state after it has been locally
// created but before the adapter has indicated that
// it has been saved.
created: createdState,
// A record is in this state if it has already been
// saved to the server, but there are new local changes
// that have not yet been saved.
updated: updatedState
},
// A record is in this state if it was deleted from the store.
deleted: {
initialState: 'uncommitted',
dirtyType: 'deleted',
// FLAGS
isDeleted: true,
isLoaded: true,
isDirty: true,
// TRANSITIONS
setup: function(record) {
record.updateRecordArrays();
},
// SUBSTATES
// When a record is deleted, it enters the `start`
// state. It will exit this state when the record
// starts to commit.
uncommitted: {
// EVENTS
willCommit: function(record) {
record.transitionTo('inFlight');
},
rollback: function(record) {
record.rollback();
},
becomeDirty: Ember.K,
deleteRecord: Ember.K,
rolledBack: function(record) {
record.transitionTo('loaded.saved');
}
},
// After a record starts committing, but
// before the adapter indicates that the deletion
// has saved to the server, a record is in the
// `inFlight` substate of `deleted`.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
unloadRecord: assertAgainstUnloadRecord,
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function(record) {
record.transitionTo('saved');
record.send('invokeLifecycleCallbacks');
},
becameError: function(record) {
record.transitionTo('uncommitted');
record.triggerLater('becameError', record);
}
},
// Once the adapter indicates that the deletion has
// been saved, the record enters the `saved` substate
// of `deleted`.
saved: {
// FLAGS
isDirty: false,
setup: function(record) {
var store = get(record, 'store');
store.dematerializeRecord(record);
},
invokeLifecycleCallbacks: function(record) {
record.triggerLater('didDelete', record);
record.triggerLater('didCommit', record);
},
willCommit: Ember.K,
didCommit: Ember.K
}
},
invokeLifecycleCallbacks: function(record, dirtyType) {
if (dirtyType === 'created') {
record.triggerLater('didCreate', record);
} else {
record.triggerLater('didUpdate', record);
}
record.triggerLater('didCommit', record);
}
};
function wireState(object, parent, name) {
/*jshint proto:true*/
// TODO: Use Object.create and copy instead
object = mixin(parent ? Ember.create(parent) : {}, object);
object.parentState = parent;
object.stateName = name;
for (var prop in object) {
if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; }
if (typeof object[prop] === 'object') {
object[prop] = wireState(object[prop], object, name + "." + prop);
}
}
return object;
}
RootState = wireState(RootState, null, "root");
__exports__["default"] = RootState;
});
define("ember-data/system/record_array_manager",
["ember-data/system/record_arrays","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var RecordArray = __dependency1__.RecordArray;
var FilteredRecordArray = __dependency1__.FilteredRecordArray;
var AdapterPopulatedRecordArray = __dependency1__.AdapterPopulatedRecordArray;
var ManyArray = __dependency1__.ManyArray;
var get = Ember.get;
var set = Ember.set;
var forEach = Ember.EnumerableUtils.forEach;
/**
@class RecordArrayManager
@namespace DS
@private
@extends Ember.Object
*/
__exports__["default"] = Ember.Object.extend({
init: function() {
this.filteredRecordArrays = Ember.MapWithDefault.create({
defaultValue: function() { return []; }
});
this.changedRecords = [];
this._adapterPopulatedRecordArrays = [];
},
recordDidChange: function(record) {
if (this.changedRecords.push(record) !== 1) { return; }
Ember.run.schedule('actions', this, this.updateRecordArrays);
},
recordArraysForRecord: function(record) {
record._recordArrays = record._recordArrays || Ember.OrderedSet.create();
return record._recordArrays;
},
/**
This method is invoked whenever data is loaded into the store by the
adapter or updated by the adapter, or when a record has changed.
It updates all record arrays that a record belongs to.
To avoid thrashing, it only runs at most once per run loop.
@method updateRecordArrays
@param {Class} type
@param {Number|String} clientId
*/
updateRecordArrays: function() {
forEach(this.changedRecords, function(record) {
if (get(record, 'isDeleted')) {
this._recordWasDeleted(record);
} else {
this._recordWasChanged(record);
}
}, this);
this.changedRecords.length = 0;
},
_recordWasDeleted: function (record) {
var recordArrays = record._recordArrays;
if (!recordArrays) { return; }
forEach(recordArrays, function(array) {
array.removeRecord(record);
});
},
_recordWasChanged: function (record) {
var type = record.constructor;
var recordArrays = this.filteredRecordArrays.get(type);
var filter;
forEach(recordArrays, function(array) {
filter = get(array, 'filterFunction');
this.updateRecordArray(array, filter, type, record);
}, this);
// loop through all manyArrays containing an unloaded copy of this
// clientId and notify them that the record was loaded.
var manyArrays = record._loadingRecordArrays;
if (manyArrays) {
for (var i=0, l=manyArrays.length; i<l; i++) {
manyArrays[i].loadedRecord();
}
record._loadingRecordArrays = [];
}
},
/**
Update an individual filter.
@method updateRecordArray
@param {DS.FilteredRecordArray} array
@param {Function} filter
@param {Class} type
@param {Number|String} clientId
*/
updateRecordArray: function(array, filter, type, record) {
var shouldBeInArray;
if (!filter) {
shouldBeInArray = true;
} else {
shouldBeInArray = filter(record);
}
var recordArrays = this.recordArraysForRecord(record);
if (shouldBeInArray) {
if (!recordArrays.has(array)) {
array.pushRecord(record);
recordArrays.add(array);
}
} else if (!shouldBeInArray) {
recordArrays.remove(array);
array.removeRecord(record);
}
},
/**
This method is invoked if the `filterFunction` property is
changed on a `DS.FilteredRecordArray`.
It essentially re-runs the filter from scratch. This same
method is invoked when the filter is created in th first place.
@method updateFilter
@param array
@param type
@param filter
*/
updateFilter: function(array, type, filter) {
var typeMap = this.store.typeMapFor(type);
var records = typeMap.records, record;
for (var i=0, l=records.length; i<l; i++) {
record = records[i];
if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) {
this.updateRecordArray(array, filter, type, record);
}
}
},
/**
Create a `DS.ManyArray` for a type and list of record references, and index
the `ManyArray` under each reference. This allows us to efficiently remove
records from `ManyArray`s when they are deleted.
@method createManyArray
@param {Class} type
@param {Array} references
@return {DS.ManyArray}
*/
createManyArray: function(type, records) {
var manyArray = ManyArray.create({
type: type,
content: records,
store: this.store
});
forEach(records, function(record) {
var arrays = this.recordArraysForRecord(record);
arrays.add(manyArray);
}, this);
return manyArray;
},
/**
Create a `DS.RecordArray` for a type and register it for updates.
@method createRecordArray
@param {Class} type
@return {DS.RecordArray}
*/
createRecordArray: function(type) {
var array = RecordArray.create({
type: type,
content: Ember.A(),
store: this.store,
isLoaded: true
});
this.registerFilteredRecordArray(array, type);
return array;
},
/**
Create a `DS.FilteredRecordArray` for a type and register it for updates.
@method createFilteredRecordArray
@param {Class} type
@param {Function} filter
@param {Object} query (optional
@return {DS.FilteredRecordArray}
*/
createFilteredRecordArray: function(type, filter, query) {
var array = FilteredRecordArray.create({
query: query,
type: type,
content: Ember.A(),
store: this.store,
manager: this,
filterFunction: filter
});
this.registerFilteredRecordArray(array, type, filter);
return array;
},
/**
Create a `DS.AdapterPopulatedRecordArray` for a type with given query.
@method createAdapterPopulatedRecordArray
@param {Class} type
@param {Object} query
@return {DS.AdapterPopulatedRecordArray}
*/
createAdapterPopulatedRecordArray: function(type, query) {
var array = AdapterPopulatedRecordArray.create({
type: type,
query: query,
content: Ember.A(),
store: this.store,
manager: this
});
this._adapterPopulatedRecordArrays.push(array);
return array;
},
/**
Register a RecordArray for a given type to be backed by
a filter function. This will cause the array to update
automatically when records of that type change attribute
values or states.
@method registerFilteredRecordArray
@param {DS.RecordArray} array
@param {Class} type
@param {Function} filter
*/
registerFilteredRecordArray: function(array, type, filter) {
var recordArrays = this.filteredRecordArrays.get(type);
recordArrays.push(array);
this.updateFilter(array, type, filter);
},
// Internally, we maintain a map of all unloaded IDs requested by
// a ManyArray. As the adapter loads data into the store, the
// store notifies any interested ManyArrays. When the ManyArray's
// total number of loading records drops to zero, it becomes
// `isLoaded` and fires a `didLoad` event.
registerWaitingRecordArray: function(record, array) {
var loadingRecordArrays = record._loadingRecordArrays || [];
loadingRecordArrays.push(array);
record._loadingRecordArrays = loadingRecordArrays;
},
willDestroy: function(){
this._super();
forEach(flatten(values(this.filteredRecordArrays.values)), destroy);
forEach(this._adapterPopulatedRecordArrays, destroy);
}
});
function values(obj) {
var result = [];
var keys = Ember.keys(obj);
for (var i = 0; i < keys.length; i++) {
result.push(obj[keys[i]]);
}
return result;
}
function destroy(entry) {
entry.destroy();
}
function flatten(list) {
var length = list.length;
var result = Ember.A();
for (var i = 0; i < length; i++) {
result = result.concat(list[i]);
}
return result;
}
});
define("ember-data/system/record_arrays",
["ember-data/system/record_arrays/record_array","ember-data/system/record_arrays/filtered_record_array","ember-data/system/record_arrays/adapter_populated_record_array","ember-data/system/record_arrays/many_array","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
/**
@module ember-data
*/
var RecordArray = __dependency1__["default"];
var FilteredRecordArray = __dependency2__["default"];
var AdapterPopulatedRecordArray = __dependency3__["default"];
var ManyArray = __dependency4__["default"];
__exports__.RecordArray = RecordArray;
__exports__.FilteredRecordArray = FilteredRecordArray;
__exports__.AdapterPopulatedRecordArray = AdapterPopulatedRecordArray;
__exports__.ManyArray = ManyArray;
});
define("ember-data/system/record_arrays/adapter_populated_record_array",
["ember-data/system/record_arrays/record_array","exports"],
function(__dependency1__, __exports__) {
"use strict";
var RecordArray = __dependency1__["default"];
/**
@module ember-data
*/
var get = Ember.get;
var set = Ember.set;
function cloneNull(source) {
var clone = Object.create(null);
for (var key in source) {
clone[key] = source[key];
}
return clone;
}
/**
Represents an ordered list of records whose order and membership is
determined by the adapter. For example, a query sent to the adapter
may trigger a search on the server, whose results would be loaded
into an instance of the `AdapterPopulatedRecordArray`.
@class AdapterPopulatedRecordArray
@namespace DS
@extends DS.RecordArray
*/
__exports__["default"] = RecordArray.extend({
query: null,
replace: function() {
var type = get(this, 'type').toString();
throw new Error("The result of a server query (on " + type + ") is immutable.");
},
/**
@method load
@private
@param {Array} data
*/
load: function(data) {
var store = get(this, 'store');
var type = get(this, 'type');
var records = store.pushMany(type, data);
var meta = store.metadataFor(type);
this.setProperties({
content: Ember.A(records),
isLoaded: true,
meta: cloneNull(meta)
});
records.forEach(function(record) {
this.manager.recordArraysForRecord(record).add(this);
}, this);
// TODO: should triggering didLoad event be the last action of the runLoop?
Ember.run.once(this, 'trigger', 'didLoad');
}
});
});
define("ember-data/system/record_arrays/filtered_record_array",
["ember-data/system/record_arrays/record_array","exports"],
function(__dependency1__, __exports__) {
"use strict";
var RecordArray = __dependency1__["default"];
/**
@module ember-data
*/
var get = Ember.get;
/**
Represents a list of records whose membership is determined by the
store. As records are created, loaded, or modified, the store
evaluates them to determine if they should be part of the record
array.
@class FilteredRecordArray
@namespace DS
@extends DS.RecordArray
*/
__exports__["default"] = RecordArray.extend({
/**
The filterFunction is a function used to test records from the store to
determine if they should be part of the record array.
Example
```javascript
var allPeople = store.all('person');
allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"]
var people = store.filter('person', function(person) {
if (person.get('name').match(/Katz$/)) { return true; }
});
people.mapBy('name'); // ["Yehuda Katz"]
var notKatzFilter = function(person) {
return !person.get('name').match(/Katz$/);
};
people.set('filterFunction', notKatzFilter);
people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"]
```
@method filterFunction
@param {DS.Model} record
@return {Boolean} `true` if the record should be in the array
*/
filterFunction: null,
isLoaded: true,
replace: function() {
var type = get(this, 'type').toString();
throw new Error("The result of a client-side filter (on " + type + ") is immutable.");
},
/**
@method updateFilter
@private
*/
_updateFilter: function() {
var manager = get(this, 'manager');
manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction'));
},
updateFilter: Ember.observer(function() {
Ember.run.once(this, this._updateFilter);
}, 'filterFunction')
});
});
define("ember-data/system/record_arrays/many_array",
["ember-data/system/record_arrays/record_array","ember-data/system/changes","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var RecordArray = __dependency1__["default"];
var RelationshipChange = __dependency2__.RelationshipChange;
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var map = Ember.EnumerableUtils.map;
function sync(change) {
change.sync();
}
/**
A `ManyArray` is a `RecordArray` that represents the contents of a has-many
relationship.
The `ManyArray` is instantiated lazily the first time the relationship is
requested.
### Inverses
Often, the relationships in Ember Data applications will have
an inverse. For example, imagine the following models are
defined:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
If you created a new instance of `App.Post` and added
a `App.Comment` record to its `comments` has-many
relationship, you would expect the comment's `post`
property to be set to the post that contained
the has-many.
We call the record to which a relationship belongs the
relationship's _owner_.
@class ManyArray
@namespace DS
@extends DS.RecordArray
*/
__exports__["default"] = RecordArray.extend({
init: function() {
this._super.apply(this, arguments);
this._changesToSync = Ember.OrderedSet.create();
},
/**
The property name of the relationship
@property {String} name
@private
*/
name: null,
/**
The record to which this relationship belongs.
@property {DS.Model} owner
@private
*/
owner: null,
/**
`true` if the relationship is polymorphic, `false` otherwise.
@property {Boolean} isPolymorphic
@private
*/
isPolymorphic: false,
// LOADING STATE
isLoaded: false,
/**
Used for async `hasMany` arrays
to keep track of when they will resolve.
@property {Ember.RSVP.Promise} promise
@private
*/
promise: null,
/**
@method loadingRecordsCount
@param {Number} count
@private
*/
loadingRecordsCount: function(count) {
this.loadingRecordsCount = count;
},
/**
@method loadedRecord
@private
*/
loadedRecord: function() {
this.loadingRecordsCount--;
if (this.loadingRecordsCount === 0) {
set(this, 'isLoaded', true);
this.trigger('didLoad');
}
},
/**
@method fetch
@private
*/
fetch: function() {
var records = get(this, 'content');
var store = get(this, 'store');
var owner = get(this, 'owner');
var unloadedRecords = records.filterBy('isEmpty', true);
store.scheduleFetchMany(unloadedRecords, owner);
},
// Overrides Ember.Array's replace method to implement
replaceContent: function(index, removed, added) {
// Map the array of record objects into an array of client ids.
added = map(added, function(record) {
Ember.assert("You cannot add '" + record.constructor.typeKey + "' records to this relationship (only '" + this.type.typeKey + "' allowed)", !this.type || record instanceof this.type);
return record;
}, this);
this._super(index, removed, added);
},
arrangedContentDidChange: function() {
Ember.run.once(this, 'fetch');
},
arrayContentWillChange: function(index, removed, added) {
var owner = get(this, 'owner');
var name = get(this, 'name');
if (!owner._suspendedRelationships) {
// This code is the first half of code that continues inside
// of arrayContentDidChange. It gets or creates a change from
// the child object, adds the current owner as the old
// parent if this is the first time the object was removed
// from a ManyArray, and sets `newParent` to null.
//
// Later, if the object is added to another ManyArray,
// the `arrayContentDidChange` will set `newParent` on
// the change.
for (var i=index; i<index+removed; i++) {
var record = get(this, 'content').objectAt(i);
var change = RelationshipChange.createChange(owner, record, get(this, 'store'), {
parentType: owner.constructor,
changeType: "remove",
kind: "hasMany",
key: name
});
this._changesToSync.add(change);
}
}
return this._super.apply(this, arguments);
},
arrayContentDidChange: function(index, removed, added) {
this._super.apply(this, arguments);
var owner = get(this, 'owner');
var name = get(this, 'name');
var store = get(this, 'store');
if (!owner._suspendedRelationships) {
// This code is the second half of code that started in
// `arrayContentWillChange`. It gets or creates a change
// from the child object, and adds the current owner as
// the new parent.
for (var i=index; i<index+added; i++) {
var record = get(this, 'content').objectAt(i);
var change = RelationshipChange.createChange(owner, record, store, {
parentType: owner.constructor,
changeType: "add",
kind:"hasMany",
key: name
});
change.hasManyName = name;
this._changesToSync.add(change);
}
// We wait until the array has finished being
// mutated before syncing the OneToManyChanges created
// in arrayContentWillChange, so that the array
// membership test in the sync() logic operates
// on the final results.
this._changesToSync.forEach(sync);
this._changesToSync.clear();
}
},
/**
Create a child record within the owner
@method createRecord
@private
@param {Object} hash
@return {DS.Model} record
*/
createRecord: function(hash) {
var owner = get(this, 'owner');
var store = get(owner, 'store');
var type = get(this, 'type');
var record;
Ember.assert("You cannot add '" + type.typeKey + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic'));
record = store.createRecord.call(store, type, hash);
this.pushObject(record);
return record;
}
});
});
define("ember-data/system/record_arrays/record_array",
["ember-data/system/store","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var PromiseArray = __dependency1__.PromiseArray;
var get = Ember.get;
var set = Ember.set;
/**
A record array is an array that contains records of a certain type. The record
array materializes records as needed when they are retrieved for the first
time. You should not create record arrays yourself. Instead, an instance of
`DS.RecordArray` or its subclasses will be returned by your application's store
in response to queries.
@class RecordArray
@namespace DS
@extends Ember.ArrayProxy
@uses Ember.Evented
*/
__exports__["default"] = Ember.ArrayProxy.extend(Ember.Evented, {
/**
The model type contained by this record array.
@property type
@type DS.Model
*/
type: null,
/**
The array of client ids backing the record array. When a
record is requested from the record array, the record
for the client id at the same index is materialized, if
necessary, by the store.
@property content
@private
@type Ember.Array
*/
content: null,
/**
The flag to signal a `RecordArray` is currently loading data.
Example
```javascript
var people = store.all('person');
people.get('isLoaded'); // true
```
@property isLoaded
@type Boolean
*/
isLoaded: false,
/**
The flag to signal a `RecordArray` is currently loading data.
Example
```javascript
var people = store.all('person');
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@property isUpdating
@type Boolean
*/
isUpdating: false,
/**
The store that created this record array.
@property store
@private
@type DS.Store
*/
store: null,
/**
Retrieves an object from the content by index.
@method objectAtContent
@private
@param {Number} index
@return {DS.Model} record
*/
objectAtContent: function(index) {
var content = get(this, 'content');
return content.objectAt(index);
},
/**
Used to get the latest version of all of the records in this array
from the adapter.
Example
```javascript
var people = store.all('person');
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@method update
*/
update: function() {
if (get(this, 'isUpdating')) { return; }
var store = get(this, 'store');
var type = get(this, 'type');
return store.fetchAll(type, this);
},
/**
Adds a record to the `RecordArray` without duplicates
@method addRecord
@private
@param {DS.Model} record
*/
addRecord: function(record) {
get(this, 'content').addObject(record);
},
/**
Adds a record to the `RecordArray`, but allows duplicates
@method pushRecord
@private
@param {DS.Model} record
*/
pushRecord: function(record) {
get(this, 'content').pushObject(record);
},
/**
Removes a record to the `RecordArray`.
@method removeRecord
@private
@param {DS.Model} record
*/
removeRecord: function(record) {
get(this, 'content').removeObject(record);
},
/**
Saves all of the records in the `RecordArray`.
Example
```javascript
var messages = store.all('message');
messages.forEach(function(message) {
message.set('hasBeenSeen', true);
});
messages.save();
```
@method save
@return {DS.PromiseArray} promise
*/
save: function() {
var promiseLabel = "DS: RecordArray#save " + get(this, 'type');
var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) {
return Ember.A(array);
}, null, "DS: RecordArray#save apply Ember.NativeArray");
return PromiseArray.create({ promise: promise });
},
_dissociateFromOwnRecords: function() {
var array = this;
this.forEach(function(record){
var recordArrays = record._recordArrays;
if (recordArrays) {
recordArrays.remove(array);
}
});
},
willDestroy: function(){
this._dissociateFromOwnRecords();
this._super();
}
});
});
define("ember-data/system/relationship-meta",
["ember-inflector/system","exports"],
function(__dependency1__, __exports__) {
"use strict";
var singularize = __dependency1__.singularize;
function typeForRelationshipMeta(store, meta) {
var typeKey, type;
typeKey = meta.type || meta.key;
if (typeof typeKey === 'string') {
if (meta.kind === 'hasMany') {
typeKey = singularize(typeKey);
}
type = store.modelFor(typeKey);
} else {
type = meta.type;
}
return type;
}
__exports__.typeForRelationshipMeta = typeForRelationshipMeta;function relationshipFromMeta(store, meta) {
return {
key: meta.key,
kind: meta.kind,
type: typeForRelationshipMeta(store, meta),
options: meta.options,
parentType: meta.parentType,
isRelationship: true
};
}
__exports__.relationshipFromMeta = relationshipFromMeta;function isSyncRelationship(record, relationshipName) {
var meta = Ember.meta(record);
var desc = meta.descs[relationshipName];
return desc && !desc._meta.options.async;
}
__exports__.isSyncRelationship = isSyncRelationship;
});
define("ember-data/system/relationships",
["./relationships/belongs_to","./relationships/has_many","ember-data/system/relationships/ext","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
/**
@module ember-data
*/
var belongsTo = __dependency1__["default"];
var hasMany = __dependency2__["default"];
__exports__.belongsTo = belongsTo;
__exports__.hasMany = hasMany;
});
define("ember-data/system/relationships/belongs_to",
["ember-data/system/model","ember-data/system/store","ember-data/system/changes","ember-data/system/relationship-meta","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
var get = Ember.get;
var set = Ember.set;
var isNone = Ember.isNone;
var Promise = Ember.RSVP.Promise;
var Model = __dependency1__.Model;
var PromiseObject = __dependency2__.PromiseObject;
var RelationshipChange = __dependency3__.RelationshipChange;
var relationshipFromMeta = __dependency4__.relationshipFromMeta;
var typeForRelationshipMeta = __dependency4__.typeForRelationshipMeta;
var isSyncRelationship = __dependency4__.isSyncRelationship;
/**
@module ember-data
*/
function asyncBelongsTo(type, options, meta) {
return Ember.computed('data', function(key, value) {
var data = get(this, 'data');
var store = get(this, 'store');
var promiseLabel = "DS: Async belongsTo " + this + " : " + key;
var promise;
meta.key = key;
if (arguments.length === 2) {
Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeForRelationshipMeta(store, meta));
return value === undefined ? null : PromiseObject.create({
promise: Promise.cast(value, promiseLabel)
});
}
var link = data.links && data.links[key];
var belongsTo = data[key];
if (!isNone(belongsTo)) {
var inverse = this.constructor.inverseFor(key);
//but for now only in the oneToOne case
if (inverse && inverse.kind === 'belongsTo'){
set(belongsTo, inverse.name, this);
}
//TODO(Igor) after OR doesn't seem that will be called
promise = store.findById(belongsTo.constructor, belongsTo.get('id')) || Promise.cast(belongsTo, promiseLabel);
return PromiseObject.create({
promise: promise
});
} else if (link) {
promise = store.findBelongsTo(this, link, relationshipFromMeta(store, meta));
return PromiseObject.create({
promise: promise
});
} else {
return null;
}
}).meta(meta);
}
/**
`DS.belongsTo` is used to define One-To-One and One-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.belongsTo` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a
related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses)
#### One-To-One
To declare a one-to-one relationship between two models, use
`DS.belongsTo`:
```javascript
App.User = DS.Model.extend({
profile: DS.belongsTo('profile')
});
App.Profile = DS.Model.extend({
user: DS.belongsTo('user')
});
```
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
@namespace
@method belongsTo
@for DS
@param {String or DS.Model} type the model type of the relationship
@param {Object} options a hash of options
@return {Ember.computed} relationship
*/
function belongsTo(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
} else {
Ember.assert("The first argument to DS.belongsTo must be a string representing a model type key, e.g. use DS.belongsTo('person') to define a relation to the App.Person model", !!type && (typeof type === 'string' || Model.detect(type)));
}
options = options || {};
var meta = {
type: type,
isRelationship: true,
options: options,
kind: 'belongsTo',
key: null
};
if (options.async) {
return asyncBelongsTo(type, options, meta);
}
return Ember.computed('data', function(key, value) {
var data = get(this, 'data');
var store = get(this, 'store');
var belongsTo, typeClass;
if (typeof type === 'string') {
typeClass = store.modelFor(type);
} else {
typeClass = type;
}
if (arguments.length === 2) {
Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeClass);
return value === undefined ? null : value;
}
belongsTo = data[key];
if (isNone(belongsTo)) { return null; }
store.findById(belongsTo.constructor, belongsTo.get('id'));
return belongsTo;
}).meta(meta);
}
/**
These observers observe all `belongsTo` relationships on the record. See
`relationships/ext` to see how these observers get their dependencies.
@class Model
@namespace DS
*/
Model.reopen({
/**
@method belongsToWillChange
@private
@static
@param record
@param key
*/
belongsToWillChange: Ember.beforeObserver(function(record, key) {
if (get(record, 'isLoaded') && isSyncRelationship(record, key)) {
var oldParent = get(record, key);
if (oldParent) {
var store = get(record, 'store');
var change = RelationshipChange.createChange(record, oldParent, store, {
key: key,
kind: 'belongsTo',
changeType: 'remove'
});
change.sync();
this._changesToSync[key] = change;
}
}
}),
/**
@method belongsToDidChange
@private
@static
@param record
@param key
*/
belongsToDidChange: Ember.immediateObserver(function(record, key) {
if (get(record, 'isLoaded')) {
var newParent = get(record, key);
if (newParent) {
var store = get(record, 'store');
var change = RelationshipChange.createChange(record, newParent, store, {
key: key,
kind: 'belongsTo',
changeType: 'add'
});
change.sync();
}
}
delete this._changesToSync[key];
})
});
__exports__["default"] = belongsTo;
});
define("ember-data/system/relationships/ext",
["ember-inflector/system","ember-data/system/relationship-meta","ember-data/system/model"],
function(__dependency1__, __dependency2__, __dependency3__) {
"use strict";
var singularize = __dependency1__.singularize;
var typeForRelationshipMeta = __dependency2__.typeForRelationshipMeta;
var relationshipFromMeta = __dependency2__.relationshipFromMeta;
var Model = __dependency3__.Model;
var get = Ember.get;
var set = Ember.set;
/**
@module ember-data
*/
/*
This file defines several extensions to the base `DS.Model` class that
add support for one-to-many relationships.
*/
/**
@class Model
@namespace DS
*/
Model.reopen({
/**
This Ember.js hook allows an object to be notified when a property
is defined.
In this case, we use it to be notified when an Ember Data user defines a
belongs-to relationship. In that case, we need to set up observers for
each one, allowing us to track relationship changes and automatically
reflect changes in the inverse has-many array.
This hook passes the class being set up, as well as the key and value
being defined. So, for example, when the user does this:
```javascript
DS.Model.extend({
parent: DS.belongsTo('user')
});
```
This hook would be called with "parent" as the key and the computed
property returned by `DS.belongsTo` as the value.
@method didDefineProperty
@param proto
@param key
@param value
*/
didDefineProperty: function(proto, key, value) {
// Check if the value being set is a computed property.
if (value instanceof Ember.ComputedProperty) {
// If it is, get the metadata for the relationship. This is
// populated by the `DS.belongsTo` helper when it is creating
// the computed property.
var meta = value.meta();
if (meta.isRelationship && meta.kind === 'belongsTo') {
Ember.addObserver(proto, key, null, 'belongsToDidChange');
Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange');
}
meta.parentType = proto.constructor;
}
}
});
/*
These DS.Model extensions add class methods that provide relationship
introspection abilities about relationships.
A note about the computed properties contained here:
**These properties are effectively sealed once called for the first time.**
To avoid repeatedly doing expensive iteration over a model's fields, these
values are computed once and then cached for the remainder of the runtime of
your application.
If your application needs to modify a class after its initial definition
(for example, using `reopen()` to add additional attributes), make sure you
do it before using your model with the store, which uses these properties
extensively.
*/
Model.reopenClass({
/**
For a given relationship name, returns the model type of the relationship.
For example, if you define a model like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
```
Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`.
@method typeForRelationship
@static
@param {String} name the name of the relationship
@return {subclass of DS.Model} the type of the relationship, or undefined
*/
typeForRelationship: function(name) {
var relationship = get(this, 'relationshipsByName').get(name);
return relationship && relationship.type;
},
inverseFor: function(name) {
var inverseType = this.typeForRelationship(name);
if (!inverseType) { return null; }
var options = this.metaForProperty(name).options;
if (options.inverse === null) { return null; }
var inverseName, inverseKind, inverse;
if (options.inverse) {
inverseName = options.inverse;
inverse = Ember.get(inverseType, 'relationshipsByName').get(inverseName);
Ember.assert("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.typeKey +
"' model. This is most likely due to a missing attribute on your model definition.", !Ember.isNone(inverse));
inverseKind = inverse.kind;
} else {
var possibleRelationships = findPossibleInverses(this, inverseType);
if (possibleRelationships.length === 0) { return null; }
Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " +
this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses",
possibleRelationships.length === 1);
inverseName = possibleRelationships[0].name;
inverseKind = possibleRelationships[0].kind;
}
function findPossibleInverses(type, inverseType, possibleRelationships) {
possibleRelationships = possibleRelationships || [];
var relationshipMap = get(inverseType, 'relationships');
if (!relationshipMap) { return; }
var relationships = relationshipMap.get(type);
if (relationships) {
possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type));
}
if (type.superclass) {
findPossibleInverses(type.superclass, inverseType, possibleRelationships);
}
return possibleRelationships;
}
return {
type: inverseType,
name: inverseName,
kind: inverseKind
};
},
/**
The model's relationships as a map, keyed on the type of the
relationship. The value of each entry is an array containing a descriptor
for each relationship with that type, describing the name of the relationship
as well as the type.
For example, given the following model definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This computed property would return a map describing these
relationships, like this:
```javascript
var relationships = Ember.get(App.Blog, 'relationships');
relationships.get(App.User);
//=> [ { name: 'users', kind: 'hasMany' },
// { name: 'owner', kind: 'belongsTo' } ]
relationships.get(App.Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]
```
@property relationships
@static
@type Ember.Map
@readOnly
*/
relationships: Ember.computed(function() {
var map = new Ember.MapWithDefault({
defaultValue: function() { return []; }
});
// Loop through each computed property on the class
this.eachComputedProperty(function(name, meta) {
// If the computed property is a relationship, add
// it to the map.
if (meta.isRelationship) {
meta.key = name;
var relationshipsForType = map.get(typeForRelationshipMeta(this.store, meta));
relationshipsForType.push({
name: name,
kind: meta.kind
});
}
});
return map;
}).cacheable(false).readOnly(),
/**
A hash containing lists of the model's relationships, grouped
by the relationship kind. For example, given a model with this
definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relationshipNames = Ember.get(App.Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
```
@property relationshipNames
@static
@type Object
@readOnly
*/
relationshipNames: Ember.computed(function() {
var names = {
hasMany: [],
belongsTo: []
};
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
names[meta.kind].push(name);
}
});
return names;
}),
/**
An array of types directly related to a model. Each type will be
included once, regardless of the number of relationships it has with
the model.
For example, given a model with this definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relatedTypes = Ember.get(App.Blog, 'relatedTypes');
//=> [ App.User, App.Post ]
```
@property relatedTypes
@static
@type Ember.Array
@readOnly
*/
relatedTypes: Ember.computed(function() {
var type;
var types = Ember.A();
// Loop through each computed property on the class,
// and create an array of the unique types involved
// in relationships
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
meta.key = name;
type = typeForRelationshipMeta(this.store, meta);
Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type);
if (!types.contains(type)) {
Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type);
types.push(type);
}
}
});
return types;
}).cacheable(false).readOnly(),
/**
A map whose keys are the relationships of a model and whose values are
relationship descriptors.
For example, given a model with this
definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: App.User }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: App.User }
```
@property relationshipsByName
@static
@type Ember.Map
@readOnly
*/
relationshipsByName: Ember.computed(function() {
var map = Ember.Map.create();
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
meta.key = name;
var relationship = relationshipFromMeta(this.store, meta);
relationship.type = typeForRelationshipMeta(this.store, meta);
map.set(name, relationship);
}
});
return map;
}).cacheable(false).readOnly(),
/**
A map whose keys are the fields of the model and whose values are strings
describing the kind of the field. A model's fields are the union of all of its
attributes and relationships.
For example:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post'),
title: DS.attr('string')
});
var fields = Ember.get(App.Blog, 'fields');
fields.forEach(function(field, kind) {
console.log(field, kind);
});
// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
```
@property fields
@static
@type Ember.Map
@readOnly
*/
fields: Ember.computed(function() {
var map = Ember.Map.create();
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
map.set(name, meta.kind);
} else if (meta.isAttribute) {
map.set(name, 'attribute');
}
});
return map;
}).readOnly(),
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function(callback, binding) {
get(this, 'relationshipsByName').forEach(function(name, relationship) {
callback.call(binding, name, relationship);
});
},
/**
Given a callback, iterates over each of the types related to a model,
invoking the callback with the related type's class. Each type will be
returned just once, regardless of how many different relationships it has
with a model.
@method eachRelatedType
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelatedType: function(callback, binding) {
get(this, 'relatedTypes').forEach(function(type) {
callback.call(binding, type);
});
}
});
Model.reopen({
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function(callback, binding) {
this.constructor.eachRelationship(callback, binding);
}
});
});
define("ember-data/system/relationships/has_many",
["ember-data/system/store","ember-data/system/relationship-meta","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/**
@module ember-data
*/
var PromiseArray = __dependency1__.PromiseArray;
var relationshipFromMeta = __dependency2__.relationshipFromMeta;
var typeForRelationshipMeta = __dependency2__.typeForRelationshipMeta;
var get = Ember.get;
var set = Ember.set;
var setProperties = Ember.setProperties;
var map = Ember.EnumerableUtils.map;
/**
Returns a computed property that synchronously returns a ManyArray for
this relationship. If not all of the records in this relationship are
loaded, it will raise an exception.
*/
function syncHasMany(type, options, meta) {
return Ember.computed('data', function(key) {
return buildRelationship(this, key, options, function(store, data) {
// Configure the metadata for the computed property to contain
// the key.
meta.key = key;
var records = data[key];
Ember.assert("You looked up the '" + key + "' relationship on '" + this + "' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", Ember.A(records).isEvery('isEmpty', false));
return store.findMany(this, data[key], typeForRelationshipMeta(store, meta));
});
}).meta(meta).readOnly();
}
/**
Returns a computed property that itself returns a promise that resolves to a
ManyArray.
*/
function asyncHasMany(type, options, meta) {
return Ember.computed('data', function(key) {
// Configure the metadata for the computed property to contain
// the key.
meta.key = key;
var relationship = buildRelationship(this, key, options, function(store, data) {
var link = data.links && data.links[key];
var rel;
var promiseLabel = "DS: Async hasMany " + this + " : " + key;
var resolver = Ember.RSVP.defer(promiseLabel);
if (link) {
rel = store.findHasMany(this, link, relationshipFromMeta(store, meta), resolver);
} else {
//This is a temporary workaround for setting owner on the relationship
//until single source of truth lands. It only works for OneToMany atm
var records = data[key];
var inverse = this.constructor.inverseFor(key);
var owner = this;
if (inverse && records) {
if (inverse.kind === 'belongsTo'){
map(records, function(record){
set(record, inverse.name, owner);
});
}
}
rel = store.findMany(owner, data[key], typeForRelationshipMeta(store, meta), resolver);
}
// Cache the promise so we can use it when we come back and don't
// need to rebuild the relationship.
set(rel, 'promise', resolver.promise);
return rel;
});
var promise = relationship.get('promise').then(function() {
return relationship;
}, null, "DS: Async hasMany records received");
return PromiseArray.create({
promise: promise
});
}).meta(meta).readOnly();
}
/*
Builds the ManyArray for a relationship using the provided callback,
but only if it had not been created previously. After building, it
sets some metadata on the created ManyArray, such as the record which
owns it and the name of the relationship.
*/
function buildRelationship(record, key, options, callback) {
var rels = record._relationships;
if (rels[key]) { return rels[key]; }
var data = get(record, 'data');
var store = get(record, 'store');
var relationship = rels[key] = callback.call(record, store, data);
return setProperties(relationship, {
owner: record,
name: key,
isPolymorphic: options.polymorphic
});
}
/**
`DS.hasMany` is used to define One-To-Many and Many-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.hasMany` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a related model.
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
#### Many-To-Many
To declare a many-to-many relationship between two models, use
`DS.hasMany`:
```javascript
App.Post = DS.Model.extend({
tags: DS.hasMany('tag')
});
App.Tag = DS.Model.extend({
posts: DS.hasMany('post')
});
```
#### Explicit Inverses
Ember Data will do its best to discover which relationships map to
one another. In the one-to-many code above, for example, Ember Data
can figure out that changing the `comments` relationship should update
the `post` relationship on the inverse because post is the only
relationship to that model.
However, sometimes you may have multiple `belongsTo`/`hasManys` for the
same type. You can specify which property on the related model is
the inverse using `DS.hasMany`'s `inverse` option:
```javascript
var belongsTo = DS.belongsTo,
hasMany = DS.hasMany;
App.Comment = DS.Model.extend({
onePost: belongsTo('post'),
twoPost: belongsTo('post'),
redPost: belongsTo('post'),
bluePost: belongsTo('post')
});
App.Post = DS.Model.extend({
comments: hasMany('comment', {
inverse: 'redPost'
})
});
```
You can also specify an inverse on a `belongsTo`, which works how
you'd expect.
@namespace
@method hasMany
@for DS
@param {String or DS.Model} type the model type of the relationship
@param {Object} options a hash of options
@return {Ember.computed} relationship
*/
function hasMany(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
}
options = options || {};
// Metadata about relationships is stored on the meta of
// the relationship. This is used for introspection and
// serialization. Note that `key` is populated lazily
// the first time the CP is called.
var meta = {
type: type,
isRelationship: true,
options: options,
kind: 'hasMany',
key: null
};
if (options.async) {
return asyncHasMany(type, options, meta);
} else {
return syncHasMany(type, options, meta);
}
}
__exports__["default"] = hasMany;
});
define("ember-data/system/store",
["ember-data/system/adapter","ember-inflector/system/string","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/*globals Ember*/
/*jshint eqnull:true*/
/**
@module ember-data
*/
var InvalidError = __dependency1__.InvalidError;
var Adapter = __dependency1__.Adapter;
var singularize = __dependency2__.singularize;
var get = Ember.get;
var set = Ember.set;
var once = Ember.run.once;
var isNone = Ember.isNone;
var forEach = Ember.EnumerableUtils.forEach;
var indexOf = Ember.EnumerableUtils.indexOf;
var map = Ember.EnumerableUtils.map;
var Promise = Ember.RSVP.Promise;
var copy = Ember.copy;
var Store, PromiseObject, PromiseArray, RecordArrayManager, Model;
var camelize = Ember.String.camelize;
// Implementors Note:
//
// The variables in this file are consistently named according to the following
// scheme:
//
// * +id+ means an identifier managed by an external source, provided inside
// the data provided by that source. These are always coerced to be strings
// before being used internally.
// * +clientId+ means a transient numerical identifier generated at runtime by
// the data store. It is important primarily because newly created objects may
// not yet have an externally generated id.
// * +reference+ means a record reference object, which holds metadata about a
// record, even if it has not yet been fully materialized.
// * +type+ means a subclass of DS.Model.
// Used by the store to normalize IDs entering the store. Despite the fact
// that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`),
// it is important that internally we use strings, since IDs may be serialized
// and lose type information. For example, Ember's router may put a record's
// ID into the URL, and if we later try to deserialize that URL and find the
// corresponding record, we will not know if it is a string or a number.
function coerceId(id) {
return id == null ? null : id+'';
}
/**
The store contains all of the data for records loaded from the server.
It is also responsible for creating instances of `DS.Model` that wrap
the individual data for a record, so that they can be bound to in your
Handlebars templates.
Define your application's store like this:
```javascript
MyApp.Store = DS.Store.extend();
```
Most Ember.js applications will only have a single `DS.Store` that is
automatically created by their `Ember.Application`.
You can retrieve models from the store in several ways. To retrieve a record
for a specific id, use `DS.Store`'s `find()` method:
```javascript
store.find('person', 123).then(function (person) {
});
```
If your application has multiple `DS.Store` instances (an unusual case), you can
specify which store should be used:
```javascript
store.find('person', 123).then(function (person) {
});
```
By default, the store will talk to your backend using a standard
REST mechanism. You can customize how the store talks to your
backend by specifying a custom adapter:
```javascript
MyApp.ApplicationAdapter = MyApp.CustomAdapter
```
You can learn more about writing a custom adapter by reading the `DS.Adapter`
documentation.
### Store createRecord() vs. push() vs. pushPayload() vs. update()
The store provides multiple ways to create new record objects. They have
some subtle differences in their use which are detailed below:
[createRecord](#method_createRecord) is used for creating new
records on the client side. This will return a new record in the
`created.uncommitted` state. In order to persist this record to the
backend you will need to call `record.save()`.
[push](#method_push) is used to notify Ember Data's store of new or
updated records that exist in the backend. This will return a record
in the `loaded.saved` state. The primary use-case for `store#push` is
to notify Ember Data about record updates that happen
outside of the normal adapter methods (for example
[SSE](http://dev.w3.org/html5/eventsource/) or [Web
Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)).
[pushPayload](#method_pushPayload) is a convenience wrapper for
`store#push` that will deserialize payloads if the
Serializer implements a `pushPayload` method.
[update](#method_update) works like `push`, except it can handle
partial attributes without overwriting the existing record
properties.
Note: When creating a new record using any of the above methods
Ember Data will update `DS.RecordArray`s such as those returned by
`store#all()`, `store#findAll()` or `store#filter()`. This means any
data bindings or computed properties that depend on the RecordArray
will automatically be synced to include the new or updated record
values.
@class Store
@namespace DS
@extends Ember.Object
*/
Store = Ember.Object.extend({
/**
@method init
@private
*/
init: function() {
// internal bookkeeping; not observable
if (!RecordArrayManager) { RecordArrayManager = requireModule("ember-data/system/record_array_manager")["default"]; }
this.typeMaps = {};
this.recordArrayManager = RecordArrayManager.create({
store: this
});
this._relationshipChanges = {};
this._pendingSave = [];
//Used to keep track of all the find requests that need to be coalesced
this._pendingFetch = Ember.Map.create();
},
/**
The adapter to use to communicate to a backend server or other persistence layer.
This can be specified as an instance, class, or string.
If you want to specify `App.CustomAdapter` as a string, do:
```js
adapter: 'custom'
```
@property adapter
@default DS.RESTAdapter
@type {DS.Adapter|String}
*/
adapter: '-rest',
/**
Returns a JSON representation of the record using a custom
type-specific serializer, if one exists.
The available options are:
* `includeId`: `true` if the record's ID should be included in
the JSON representation
@method serialize
@private
@param {DS.Model} record the record to serialize
@param {Object} options an options hash
*/
serialize: function(record, options) {
return this.serializerFor(record.constructor.typeKey).serialize(record, options);
},
/**
This property returns the adapter, after resolving a possible
string key.
If the supplied `adapter` was a class, or a String property
path resolved to a class, this property will instantiate the
class.
This property is cacheable, so the same instance of a specified
adapter class should be used for the lifetime of the store.
@property defaultAdapter
@private
@return DS.Adapter
*/
defaultAdapter: Ember.computed('adapter', function() {
var adapter = get(this, 'adapter');
Ember.assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name or a factory', !(adapter instanceof Adapter));
if (typeof adapter === 'string') {
adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:-rest');
}
if (DS.Adapter.detect(adapter)) {
adapter = adapter.create({
container: this.container
});
}
return adapter;
}),
// .....................
// . CREATE NEW RECORD .
// .....................
/**
Create a new record in the current store. The properties passed
to this method are set on the newly created record.
To create a new instance of `App.Post`:
```js
store.createRecord('post', {
title: "Rails is omakase"
});
```
@method createRecord
@param {String} type
@param {Object} properties a hash of properties to set on the
newly created record.
@return {DS.Model} record
*/
createRecord: function(typeName, inputProperties) {
var type = this.modelFor(typeName);
var properties = copy(inputProperties) || {};
// If the passed properties do not include a primary key,
// give the adapter an opportunity to generate one. Typically,
// client-side ID generators will use something like uuid.js
// to avoid conflicts.
if (isNone(properties.id)) {
properties.id = this._generateId(type);
}
// Coerce ID to a string
properties.id = coerceId(properties.id);
var record = this.buildRecord(type, properties.id);
// Move the record out of its initial `empty` state into
// the `loaded` state.
record.loadedData();
// Set the properties specified on the record.
record.setProperties(properties);
return record;
},
/**
If possible, this method asks the adapter to generate an ID for
a newly created record.
@method _generateId
@private
@param {String} type
@return {String} if the adapter can generate one, an ID
*/
_generateId: function(type) {
var adapter = this.adapterFor(type);
if (adapter && adapter.generateIdForRecord) {
return adapter.generateIdForRecord(this);
}
return null;
},
// .................
// . DELETE RECORD .
// .................
/**
For symmetry, a record can be deleted via the store.
Example
```javascript
var post = store.createRecord('post', {
title: "Rails is omakase"
});
store.deleteRecord(post);
```
@method deleteRecord
@param {DS.Model} record
*/
deleteRecord: function(record) {
record.deleteRecord();
},
/**
For symmetry, a record can be unloaded via the store. Only
non-dirty records can be unloaded.
Example
```javascript
store.find('post', 1).then(function(post) {
store.unloadRecord(post);
});
```
@method unloadRecord
@param {DS.Model} record
*/
unloadRecord: function(record) {
record.unloadRecord();
},
// ................
// . FIND RECORDS .
// ................
/**
This is the main entry point into finding records. The first parameter to
this method is the model's name as a string.
---
To find a record by ID, pass the `id` as the second parameter:
```javascript
store.find('person', 1);
```
The `find` method will always return a **promise** that will be resolved
with the record. If the record was already in the store, the promise will
be resolved immediately. Otherwise, the store will ask the adapter's `find`
method to find the necessary data.
The `find` method will always resolve its promise with the same object for
a given type and `id`.
---
You can optionally preload specific attributes and relationships that you know of
by passing them as the third argument to find.
For example, if your Ember route looks like `/posts/1/comments/2` and you API route
for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment
without fetching the post you can pass in the post to the `find` call:
```javascript
store.find('comment', 2, {post: 1});
```
If you have access to the post model you can also pass the model itself:
```javascript
store.find('post', 1).then(function (myPostModel) {
store.find('comment', 2, {post: myPostModel});
});
```
This way, your adapter's `find` or `buildURL` method will be able to look up the
relationship on the record and construct the nested URL without having to first
fetch the post.
---
To find all records for a type, call `find` with no additional parameters:
```javascript
store.find('person');
```
This will ask the adapter's `findAll` method to find the records for the
given type, and return a promise that will be resolved once the server
returns the values.
---
To find a record by a query, call `find` with a hash as the second
parameter:
```javascript
store.find('person', { page: 1 });
```
This will ask the adapter's `findQuery` method to find the records for
the query, and return a promise that will be resolved once the server
responds.
@method find
@param {String or subclass of DS.Model} type
@param {Object|String|Integer|null} id
@return {Promise} promise
*/
find: function(type, id, preload) {
Ember.assert("You need to pass a type to the store's find method", arguments.length >= 1);
Ember.assert("You may not pass `" + id + "` as id to the store's find method", arguments.length === 1 || !Ember.isNone(id));
if (arguments.length === 1) {
return this.findAll(type);
}
// We are passed a query instead of an id.
if (Ember.typeOf(id) === 'object') {
return this.findQuery(type, id);
}
return this.findById(type, coerceId(id), preload);
},
/**
This method returns a record for a given type and id combination.
@method findById
@private
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@return {Promise} promise
*/
findById: function(typeName, id, preload) {
var fetchedRecord;
var type = this.modelFor(typeName);
var record = this.recordForId(type, id);
if (preload) {
record._preloadData(preload);
}
if (get(record, 'isEmpty')) {
fetchedRecord = this.scheduleFetch(record);
//TODO double check about reloading
} else if (get(record, 'isLoading')){
fetchedRecord = record._loadingPromise;
}
return promiseObject(fetchedRecord || record, "DS: Store#findById " + type + " with id: " + id);
},
/**
This method makes a series of requests to the adapter's `find` method
and returns a promise that resolves once they are all loaded.
@private
@method findByIds
@param {String} type
@param {Array} ids
@return {Promise} promise
*/
findByIds: function(type, ids) {
var store = this;
var promiseLabel = "DS: Store#findByIds " + type;
return promiseArray(Ember.RSVP.all(map(ids, function(id) {
return store.findById(type, id);
})).then(Ember.A, null, "DS: Store#findByIds of " + type + " complete"));
},
/**
This method is called by `findById` if it discovers that a particular
type/id pair hasn't been loaded yet to kick off a request to the
adapter.
@method fetchRecord
@private
@param {DS.Model} record
@return {Promise} promise
*/
fetchRecord: function(record) {
var type = record.constructor;
var id = get(record, 'id');
var adapter = this.adapterFor(type);
Ember.assert("You tried to find a record but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to find a record but your adapter (for " + type + ") does not implement 'find'", adapter.find);
var promise = _find(adapter, this, type, id, record);
return promise;
},
scheduleFetchMany: function(records) {
return Ember.RSVP.all(map(records, this.scheduleFetch, this));
},
scheduleFetch: function(record) {
var type = record.constructor;
if (isNone(record)) { return null; }
if (record._loadingPromise) { return record._loadingPromise; }
var resolver = Ember.RSVP.defer('Fetching ' + type + 'with id: ' + record.get('id'));
var recordResolverPair = {
record: record,
resolver: resolver
};
var promise = resolver.promise;
record.loadingData(promise);
if (!this._pendingFetch.get(type)){
this._pendingFetch.set(type, [recordResolverPair]);
} else {
this._pendingFetch.get(type).push(recordResolverPair);
}
Ember.run.scheduleOnce('afterRender', this, this.flushAllPendingFetches);
return promise;
},
flushAllPendingFetches: function(){
if (this.isDestroyed || this.isDestroying) {
return;
}
this._pendingFetch.forEach(this._flushPendingFetchForType, this);
this._pendingFetch = Ember.Map.create();
},
_flushPendingFetchForType: function (type, recordResolverPairs) {
var store = this;
var adapter = store.adapterFor(type);
var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests;
var records = Ember.A(recordResolverPairs).mapBy('record');
var resolvers = Ember.A(recordResolverPairs).mapBy('resolver');
function _fetchRecord(recordResolverPair) {
recordResolverPair.resolver.resolve(store.fetchRecord(recordResolverPair.record));
}
function resolveFoundRecords(records) {
forEach(records, function(record){
var pair = Ember.A(recordResolverPairs).findBy('record', record);
if (pair){
var resolver = pair.resolver;
resolver.resolve(record);
}
});
}
function makeMissingRecordsRejector(requestedRecords) {
return function rejectMissingRecords(resolvedRecords) {
var missingRecords = requestedRecords.without(resolvedRecords);
rejectRecords(missingRecords);
};
}
function makeRecordsRejector(records) {
return function (error) {
rejectRecords(records, error);
};
}
function rejectRecords(records, error) {
forEach(records, function(record){
var pair = Ember.A(recordResolverPairs).findBy('record', record);
if (pair){
var resolver = pair.resolver;
resolver.reject(error);
}
});
}
if (recordResolverPairs.length === 1) {
_fetchRecord(recordResolverPairs[0]);
} else if (shouldCoalesce) {
var groups = adapter.groupRecordsForFindMany(this, records);
forEach(groups, function (groupOfRecords) {
var requestedRecords = Ember.A(groupOfRecords);
var ids = requestedRecords.mapBy('id');
if (ids.length > 1) {
_findMany(adapter, store, type, ids, requestedRecords).
then(resolveFoundRecords).
then(makeMissingRecordsRejector(requestedRecords)).
then(null, makeRecordsRejector(requestedRecords));
} else if (ids.length === 1) {
var pair = Ember.A(recordResolverPairs).findBy('record', groupOfRecords[0]);
_fetchRecord(pair);
} else {
Ember.assert("You cannot return an empty array from adapter's method groupRecordsForFindMany", false);
}
});
} else {
forEach(recordResolverPairs, _fetchRecord);
}
},
/**
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it is available in the store,
otherwise it will return `null`. A record is available if it has been fetched earlier, or
pushed manually into the store.
_Note: This is an synchronous method and does not return a promise._
```js
var post = store.getById('post', 1);
post.get('id'); // 1
```
@method getById
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@return {DS.Model|null} record
*/
getById: function(type, id) {
if (this.hasRecordForId(type, id)) {
return this.recordForId(type, id);
} else {
return null;
}
},
/**
This method is called by the record's `reload` method.
This method calls the adapter's `find` method, which returns a promise. When
**that** promise resolves, `reloadRecord` will resolve the promise returned
by the record's `reload`.
@method reloadRecord
@private
@param {DS.Model} record
@return {Promise} promise
*/
reloadRecord: function(record) {
var type = record.constructor;
var adapter = this.adapterFor(type);
var id = get(record, 'id');
Ember.assert("You cannot reload a record without an ID", id);
Ember.assert("You tried to reload a record but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to reload a record but your adapter does not implement `find`", adapter.find);
return this.scheduleFetch(record);
},
/**
Returns true if a record for a given type and ID is already loaded.
@method hasRecordForId
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@return {Boolean}
*/
hasRecordForId: function(typeName, inputId) {
var type = this.modelFor(typeName);
var id = coerceId(inputId);
return !!this.typeMapFor(type).idToRecord[id];
},
/**
Returns id record for a given type and ID. If one isn't already loaded,
it builds a new record and leaves it in the `empty` state.
@method recordForId
@private
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@return {DS.Model} record
*/
recordForId: function(typeName, inputId) {
var type = this.modelFor(typeName);
var id = coerceId(inputId);
var idToRecord = this.typeMapFor(type).idToRecord;
var record = idToRecord[id];
if (!record || !idToRecord[id]) {
record = this.buildRecord(type, id);
}
return record;
},
/**
@method findMany
@private
@param {DS.Model} owner
@param {Array} records
@param {String or subclass of DS.Model} type
@param {Resolver} resolver
@return {DS.ManyArray} records
*/
findMany: function(owner, inputRecords, typeName, resolver) {
var type = this.modelFor(typeName);
var records = Ember.A(inputRecords);
var unloadedRecords = records.filterProperty('isEmpty', true);
var manyArray = this.recordArrayManager.createManyArray(type, records);
manyArray.loadingRecordsCount = unloadedRecords.length;
if (unloadedRecords.length) {
forEach(unloadedRecords, function(record) {
this.recordArrayManager.registerWaitingRecordArray(record, manyArray);
}, this);
resolver.resolve(this.scheduleFetchMany(unloadedRecords, owner));
} else {
if (resolver) { resolver.resolve(); }
manyArray.set('isLoaded', true);
once(manyArray, 'trigger', 'didLoad');
}
return manyArray;
},
/**
If a relationship was originally populated by the adapter as a link
(as opposed to a list of IDs), this method is called when the
relationship is fetched.
The link (which is usually a URL) is passed through unchanged, so the
adapter can make whatever request it wants.
The usual use-case is for the server to register a URL as a link, and
then use that URL in the future to make a request for the relationship.
@method findHasMany
@private
@param {DS.Model} owner
@param {any} link
@param {String or subclass of DS.Model} type
@return {Promise} promise
*/
findHasMany: function(owner, link, relationship, resolver) {
var adapter = this.adapterFor(owner.constructor);
Ember.assert("You tried to load a hasMany relationship but you have no adapter (for " + owner.constructor + ")", adapter);
Ember.assert("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", adapter.findHasMany);
var records = this.recordArrayManager.createManyArray(relationship.type, Ember.A([]));
resolver.resolve(_findHasMany(adapter, this, owner, link, relationship));
return records;
},
/**
@method findBelongsTo
@private
@param {DS.Model} owner
@param {any} link
@param {Relationship} relationship
@return {Promise} promise
*/
findBelongsTo: function(owner, link, relationship) {
var adapter = this.adapterFor(owner.constructor);
Ember.assert("You tried to load a belongsTo relationship but you have no adapter (for " + owner.constructor + ")", adapter);
Ember.assert("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", adapter.findBelongsTo);
return _findBelongsTo(adapter, this, owner, link, relationship);
},
/**
This method delegates a query to the adapter. This is the one place where
adapter-level semantics are exposed to the application.
Exposing queries this way seems preferable to creating an abstract query
language for all server-side queries, and then require all adapters to
implement them.
This method returns a promise, which is resolved with a `RecordArray`
once the server returns.
@method findQuery
@private
@param {String or subclass of DS.Model} type
@param {any} query an opaque query to be used by the adapter
@return {Promise} promise
*/
findQuery: function(typeName, query) {
var type = this.modelFor(typeName);
var array = this.recordArrayManager
.createAdapterPopulatedRecordArray(type, query);
var adapter = this.adapterFor(type);
Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", adapter.findQuery);
return promiseArray(_findQuery(adapter, this, type, query, array));
},
/**
This method returns an array of all records adapter can find.
It triggers the adapter's `findAll` method to give it an opportunity to populate
the array with records of that type.
@method findAll
@private
@param {String or subclass of DS.Model} type
@return {DS.AdapterPopulatedRecordArray}
*/
findAll: function(typeName) {
var type = this.modelFor(typeName);
return this.fetchAll(type, this.all(type));
},
/**
@method fetchAll
@private
@param {DS.Model} type
@param {DS.RecordArray} array
@return {Promise} promise
*/
fetchAll: function(type, array) {
var adapter = this.adapterFor(type);
var sinceToken = this.typeMapFor(type).metadata.since;
set(array, 'isUpdating', true);
Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load all records but your adapter does not implement `findAll`", adapter.findAll);
return promiseArray(_findAll(adapter, this, type, sinceToken));
},
/**
@method didUpdateAll
@param {DS.Model} type
*/
didUpdateAll: function(type) {
var findAllCache = this.typeMapFor(type).findAllCache;
set(findAllCache, 'isUpdating', false);
},
/**
This method returns a filtered array that contains all of the known records
for a given type.
Note that because it's just a filter, it will have any locally
created records of the type.
Also note that multiple calls to `all` for a given type will always
return the same RecordArray.
Example
```javascript
var localPosts = store.all('post');
```
@method all
@param {String or subclass of DS.Model} type
@return {DS.RecordArray}
*/
all: function(typeName) {
var type = this.modelFor(typeName);
var typeMap = this.typeMapFor(type);
var findAllCache = typeMap.findAllCache;
if (findAllCache) { return findAllCache; }
var array = this.recordArrayManager.createRecordArray(type);
typeMap.findAllCache = array;
return array;
},
/**
This method unloads all of the known records for a given type.
```javascript
store.unloadAll('post');
```
@method unloadAll
@param {String or subclass of DS.Model} type
*/
unloadAll: function(type) {
var modelType = this.modelFor(type);
var typeMap = this.typeMapFor(modelType);
var records = typeMap.records.slice();
var record;
for (var i = 0; i < records.length; i++) {
record = records[i];
record.unloadRecord();
record.destroy(); // maybe within unloadRecord
}
typeMap.findAllCache = null;
},
/**
Takes a type and filter function, and returns a live RecordArray that
remains up to date as new records are loaded into the store or created
locally.
The callback function takes a materialized record, and returns true
if the record should be included in the filter and false if it should
not.
The filter function is called once on all records for the type when
it is created, and then once on each newly loaded or created record.
If any of a record's properties change, or if it changes state, the
filter function will be invoked again to determine whether it should
still be in the array.
Optionally you can pass a query which will be triggered at first. The
results returned by the server could then appear in the filter if they
match the filter function.
Example
```javascript
store.filter('post', {unread: true}, function(post) {
return post.get('unread');
}).then(function(unreadPosts) {
unreadPosts.get('length'); // 5
var unreadPost = unreadPosts.objectAt(0);
unreadPost.set('unread', false);
unreadPosts.get('length'); // 4
});
```
@method filter
@param {String or subclass of DS.Model} type
@param {Object} query optional query
@param {Function} filter
@return {DS.PromiseArray}
*/
filter: function(type, query, filter) {
var promise;
var length = arguments.length;
var array;
var hasQuery = length === 3;
// allow an optional server query
if (hasQuery) {
promise = this.findQuery(type, query);
} else if (arguments.length === 2) {
filter = query;
}
type = this.modelFor(type);
if (hasQuery) {
array = this.recordArrayManager.createFilteredRecordArray(type, filter, query);
} else {
array = this.recordArrayManager.createFilteredRecordArray(type, filter);
}
promise = promise || Promise.cast(array);
return promiseArray(promise.then(function() {
return array;
}, null, "DS: Store#filter of " + type));
},
/**
This method returns if a certain record is already loaded
in the store. Use this function to know beforehand if a find()
will result in a request or that it will be a cache hit.
Example
```javascript
store.recordIsLoaded('post', 1); // false
store.find('post', 1).then(function() {
store.recordIsLoaded('post', 1); // true
});
```
@method recordIsLoaded
@param {String or subclass of DS.Model} type
@param {string} id
@return {boolean}
*/
recordIsLoaded: function(type, id) {
if (!this.hasRecordForId(type, id)) { return false; }
return !get(this.recordForId(type, id), 'isEmpty');
},
/**
This method returns the metadata for a specific type.
@method metadataFor
@param {String or subclass of DS.Model} type
@return {object}
*/
metadataFor: function(type) {
type = this.modelFor(type);
return this.typeMapFor(type).metadata;
},
// ............
// . UPDATING .
// ............
/**
If the adapter updates attributes or acknowledges creation
or deletion, the record will notify the store to update its
membership in any filters.
To avoid thrashing, this method is invoked only once per
run loop per record.
@method dataWasUpdated
@private
@param {Class} type
@param {DS.Model} record
*/
dataWasUpdated: function(type, record) {
this.recordArrayManager.recordDidChange(record);
},
// ..............
// . PERSISTING .
// ..............
/**
This method is called by `record.save`, and gets passed a
resolver for the promise that `record.save` returns.
It schedules saving to happen at the end of the run loop.
@method scheduleSave
@private
@param {DS.Model} record
@param {Resolver} resolver
*/
scheduleSave: function(record, resolver) {
record.adapterWillCommit();
this._pendingSave.push([record, resolver]);
once(this, 'flushPendingSave');
},
/**
This method is called at the end of the run loop, and
flushes any records passed into `scheduleSave`
@method flushPendingSave
@private
*/
flushPendingSave: function() {
var pending = this._pendingSave.slice();
this._pendingSave = [];
forEach(pending, function(tuple) {
var record = tuple[0], resolver = tuple[1];
var adapter = this.adapterFor(record.constructor);
var operation;
if (get(record, 'currentState.stateName') === 'root.deleted.saved') {
return resolver.resolve(record);
} else if (get(record, 'isNew')) {
operation = 'createRecord';
} else if (get(record, 'isDeleted')) {
operation = 'deleteRecord';
} else {
operation = 'updateRecord';
}
resolver.resolve(_commit(adapter, this, operation, record));
}, this);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is resolved.
If the data provides a server-generated ID, it will
update the record and the store's indexes.
@method didSaveRecord
@private
@param {DS.Model} record the in-flight record
@param {Object} data optional data (see above)
*/
didSaveRecord: function(record, data) {
if (data) {
// normalize relationship IDs into records
data = normalizeRelationships(this, record.constructor, data, record);
this.updateId(record, data);
}
record.adapterDidCommit(data);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected with a `DS.InvalidError`.
@method recordWasInvalid
@private
@param {DS.Model} record
@param {Object} errors
*/
recordWasInvalid: function(record, errors) {
record.adapterDidInvalidate(errors);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected (with anything other than a `DS.InvalidError`).
@method recordWasError
@private
@param {DS.Model} record
*/
recordWasError: function(record) {
record.adapterDidError();
},
/**
When an adapter's `createRecord`, `updateRecord` or `deleteRecord`
resolves with data, this method extracts the ID from the supplied
data.
@method updateId
@private
@param {DS.Model} record
@param {Object} data
*/
updateId: function(record, data) {
var oldId = get(record, 'id');
var id = coerceId(data.id);
Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId);
this.typeMapFor(record.constructor).idToRecord[id] = record;
set(record, 'id', id);
},
/**
Returns a map of IDs to client IDs for a given type.
@method typeMapFor
@private
@param type
@return {Object} typeMap
*/
typeMapFor: function(type) {
var typeMaps = get(this, 'typeMaps');
var guid = Ember.guidFor(type);
var typeMap;
typeMap = typeMaps[guid];
if (typeMap) { return typeMap; }
typeMap = {
idToRecord: Object.create(null),
records: [],
metadata: Object.create(null),
type: type
};
typeMaps[guid] = typeMap;
return typeMap;
},
// ................
// . LOADING DATA .
// ................
/**
This internal method is used by `push`.
@method _load
@private
@param {String or subclass of DS.Model} type
@param {Object} data
@param {Boolean} partial the data should be merged into
the existing data, not replace it.
*/
_load: function(type, data, partial) {
var id = coerceId(data.id);
var record = this.recordForId(type, id);
record.setupData(data, partial);
this.recordArrayManager.recordDidChange(record);
return record;
},
/**
Returns a model class for a particular key. Used by
methods that take a type key (like `find`, `createRecord`,
etc.)
@method modelFor
@param {String or subclass of DS.Model} key
@return {subclass of DS.Model}
*/
modelFor: function(key) {
var factory;
if (typeof key === 'string') {
var normalizedKey = this.container.normalize('model:' + key);
factory = this.container.lookupFactory(normalizedKey);
if (!factory) { throw new Ember.Error("No model was found for '" + key + "'"); }
factory.typeKey = this._normalizeTypeKey(normalizedKey.split(':', 2)[1]);
} else {
// A factory already supplied. Ensure it has a normalized key.
factory = key;
if (factory.typeKey) {
factory.typeKey = this._normalizeTypeKey(factory.typeKey);
}
}
factory.store = this;
return factory;
},
/**
Push some data for a given type into the store.
This method expects normalized data:
* The ID is a key named `id` (an ID is mandatory)
* The names of attributes are the ones you used in
your model's `DS.attr`s.
* Your relationships must be:
* represented as IDs or Arrays of IDs
* represented as model instances
* represented as URLs, under the `links` key
For this model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr(),
children: DS.hasMany('person')
});
```
To represent the children as IDs:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
children: [1, 2, 3]
}
```
To represent the children relationship as a URL:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
links: {
children: "/people/1/children"
}
}
```
If you're streaming data or implementing an adapter,
make sure that you have converted the incoming data
into this form.
This method can be used both to push in brand new
records, as well as to update existing records.
@method push
@param {String or subclass of DS.Model} type
@param {Object} data
@return {DS.Model} the record that was created or
updated.
*/
push: function(typeName, data, _partial) {
// _partial is an internal param used by `update`.
// If passed, it means that the data should be
// merged into the existing data, not replace it.
Ember.assert("You must include an `id` for " + typeName+ " in a hash passed to `push`", data.id != null);
var type = this.modelFor(typeName);
// normalize relationship IDs into records
data = normalizeRelationships(this, type, data);
this._load(type, data, _partial);
return this.recordForId(type, data.id);
},
/**
Push some raw data into the store.
This method can be used both to push in brand new
records, as well as to update existing records. You
can push in more than one type of object at once.
All objects should be in the format expected by the
serializer.
```js
App.ApplicationSerializer = DS.ActiveModelSerializer;
var pushData = {
posts: [
{id: 1, post_title: "Great post", comment_ids: [2]}
],
comments: [
{id: 2, comment_body: "Insightful comment"}
]
}
store.pushPayload(pushData);
```
By default, the data will be deserialized using a default
serializer (the application serializer if it exists).
Alternatively, `pushPayload` will accept a model type which
will determine which serializer will process the payload.
However, the serializer itself (processing this data via
`normalizePayload`) will not know which model it is
deserializing.
```js
App.ApplicationSerializer = DS.ActiveModelSerializer;
App.PostSerializer = DS.JSONSerializer;
store.pushPayload('comment', pushData); // Will use the ApplicationSerializer
store.pushPayload('post', pushData); // Will use the PostSerializer
```
@method pushPayload
@param {String} type Optionally, a model used to determine which serializer will be used
@param {Object} payload
*/
pushPayload: function (type, inputPayload) {
var serializer;
var payload;
if (!inputPayload) {
payload = type;
serializer = defaultSerializer(this.container);
Ember.assert("You cannot use `store#pushPayload` without a type unless your default serializer defines `pushPayload`", serializer.pushPayload);
} else {
payload = inputPayload;
serializer = this.serializerFor(type);
}
serializer.pushPayload(this, payload);
},
/**
`normalize` converts a json payload into the normalized form that
[push](#method_push) expects.
Example
```js
socket.on('message', function(message) {
var modelName = message.model;
var data = message.data;
store.push(modelName, store.normalize(modelName, data));
});
```
@method normalize
@param {String} The name of the model type for this payload
@param {Object} payload
@return {Object} The normalized payload
*/
normalize: function (type, payload) {
var serializer = this.serializerFor(type);
var model = this.modelFor(type);
return serializer.normalize(model, payload);
},
/**
Update existing records in the store. Unlike [push](#method_push),
update will merge the new data properties with the existing
properties. This makes it safe to use with a subset of record
attributes. This method expects normalized data.
`update` is useful if your app broadcasts partial updates to
records.
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string')
});
store.get('person', 1).then(function(tom) {
tom.get('firstName'); // Tom
tom.get('lastName'); // Dale
var updateEvent = {id: 1, firstName: "TomHuda"};
store.update('person', updateEvent);
tom.get('firstName'); // TomHuda
tom.get('lastName'); // Dale
});
```
@method update
@param {String} type
@param {Object} data
@return {DS.Model} the record that was updated.
*/
update: function(type, data) {
Ember.assert("You must include an `id` for " + type + " in a hash passed to `update`", data.id != null);
return this.push(type, data, true);
},
/**
If you have an Array of normalized data to push,
you can call `pushMany` with the Array, and it will
call `push` repeatedly for you.
@method pushMany
@param {String or subclass of DS.Model} type
@param {Array} datas
@return {Array}
*/
pushMany: function(type, datas) {
return map(datas, function(data) {
return this.push(type, data);
}, this);
},
/**
If you have some metadata to set for a type
you can call `metaForType`.
@method metaForType
@param {String or subclass of DS.Model} type
@param {Object} metadata
*/
metaForType: function(typeName, metadata) {
var type = this.modelFor(typeName);
Ember.merge(this.typeMapFor(type).metadata, metadata);
},
/**
Build a brand new record for a given type, ID, and
initial data.
@method buildRecord
@private
@param {subclass of DS.Model} type
@param {String} id
@param {Object} data
@return {DS.Model} record
*/
buildRecord: function(type, id, data) {
var typeMap = this.typeMapFor(type);
var idToRecord = typeMap.idToRecord;
Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]);
Ember.assert("`" + Ember.inspect(type)+ "` does not appear to be an ember-data model", (typeof type._create === 'function') );
// lookupFactory should really return an object that creates
// instances with the injections applied
var record = type._create({
id: id,
store: this,
container: this.container
});
if (data) {
record.setupData(data);
}
// if we're creating an item, this process will be done
// later, once the object has been persisted.
if (id) {
idToRecord[id] = record;
}
typeMap.records.push(record);
return record;
},
// ...............
// . DESTRUCTION .
// ...............
/**
When a record is destroyed, this un-indexes it and
removes it from any record arrays so it can be GCed.
@method dematerializeRecord
@private
@param {DS.Model} record
*/
dematerializeRecord: function(record) {
var type = record.constructor;
var typeMap = this.typeMapFor(type);
var id = get(record, 'id');
record.updateRecordArrays();
if (id) {
delete typeMap.idToRecord[id];
}
var loc = indexOf(typeMap.records, record);
typeMap.records.splice(loc, 1);
},
// ........................
// . RELATIONSHIP CHANGES .
// ........................
addRelationshipChangeFor: function(childRecord, childKey, parentRecord, parentKey, change) {
var clientId = childRecord.clientId;
var parentClientId = parentRecord ? parentRecord : parentRecord;
var key = childKey + parentKey;
var changes = this._relationshipChanges;
if (!(clientId in changes)) {
changes[clientId] = {};
}
if (!(parentClientId in changes[clientId])) {
changes[clientId][parentClientId] = {};
}
if (!(key in changes[clientId][parentClientId])) {
changes[clientId][parentClientId][key] = {};
}
changes[clientId][parentClientId][key][change.changeType] = change;
},
removeRelationshipChangeFor: function(clientRecord, childKey, parentRecord, parentKey, type) {
var clientId = clientRecord.clientId;
var parentClientId = parentRecord ? parentRecord.clientId : parentRecord;
var changes = this._relationshipChanges;
var key = childKey + parentKey;
if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){
return;
}
delete changes[clientId][parentClientId][key][type];
},
relationshipChangePairsFor: function(record){
var toReturn = [];
if( !record ) { return toReturn; }
//TODO(Igor) What about the other side
var changesObject = this._relationshipChanges[record.clientId];
for (var objKey in changesObject){
if (changesObject.hasOwnProperty(objKey)){
for (var changeKey in changesObject[objKey]){
if (changesObject[objKey].hasOwnProperty(changeKey)){
toReturn.push(changesObject[objKey][changeKey]);
}
}
}
}
return toReturn;
},
// ......................
// . PER-TYPE ADAPTERS
// ......................
/**
Returns the adapter for a given type.
@method adapterFor
@private
@param {subclass of DS.Model} type
@return DS.Adapter
*/
adapterFor: function(type) {
var container = this.container, adapter;
if (container) {
adapter = container.lookup('adapter:' + type.typeKey) || container.lookup('adapter:application');
}
return adapter || get(this, 'defaultAdapter');
},
// ..............................
// . RECORD CHANGE NOTIFICATION .
// ..............................
/**
Returns an instance of the serializer for a given type. For
example, `serializerFor('person')` will return an instance of
`App.PersonSerializer`.
If no `App.PersonSerializer` is found, this method will look
for an `App.ApplicationSerializer` (the default serializer for
your entire application).
If no `App.ApplicationSerializer` is found, it will fall back
to an instance of `DS.JSONSerializer`.
@method serializerFor
@private
@param {String} type the record to serialize
@return {DS.Serializer}
*/
serializerFor: function(type) {
type = this.modelFor(type);
var adapter = this.adapterFor(type);
return serializerFor(this.container, type.typeKey, adapter && adapter.defaultSerializer);
},
willDestroy: function() {
var typeMaps = this.typeMaps;
var keys = Ember.keys(typeMaps);
var store = this;
var types = map(keys, byType);
this.recordArrayManager.destroy();
forEach(types, this.unloadAll, this);
function byType(entry) {
return typeMaps[entry]['type'];
}
},
/**
All typeKeys are camelCase internally. Changing this function may
require changes to other normalization hooks (such as typeForRoot).
@method _normalizeTypeKey
@private
@param {String} type
@return {String} if the adapter can generate one, an ID
*/
_normalizeTypeKey: function(key) {
return camelize(singularize(key));
}
});
function normalizeRelationships(store, type, data, record) {
type.eachRelationship(function(key, relationship) {
// A link (usually a URL) was already provided in
// normalized form
if (data.links && data.links[key]) {
if (record && relationship.options.async) { record._relationships[key] = null; }
return;
}
var kind = relationship.kind;
var value = data[key];
if (value == null) {
if (kind === 'hasMany' && record) {
value = data[key] = record.get(key).toArray();
}
return;
}
if (kind === 'belongsTo') {
deserializeRecordId(store, data, key, relationship, value);
} else if (kind === 'hasMany') {
deserializeRecordIds(store, data, key, relationship, value);
addUnsavedRecords(record, key, value);
}
});
return data;
}
function deserializeRecordId(store, data, key, relationship, id) {
if (!Model) { Model = requireModule("ember-data/system/model")["Model"]; }
if (isNone(id) || id instanceof Model) {
return;
}
var type;
if (typeof id === 'number' || typeof id === 'string') {
type = typeFor(relationship, key, data);
data[key] = store.recordForId(type, id);
} else if (typeof id === 'object') {
// polymorphic
data[key] = store.recordForId(id.type, id.id);
}
}
function typeFor(relationship, key, data) {
if (relationship.options.polymorphic) {
return data[key + "Type"];
} else {
return relationship.type;
}
}
function deserializeRecordIds(store, data, key, relationship, ids) {
for (var i=0, l=ids.length; i<l; i++) {
deserializeRecordId(store, ids, i, relationship, ids[i]);
}
}
// If there are any unsaved records that are in a hasMany they won't be
// in the payload, so add them back in manually.
function addUnsavedRecords(record, key, data) {
if(record) {
var unsavedRecords = uniqById(Ember.A(data), record.get(key).filterBy('isNew'));
Ember.A(data).pushObjects(unsavedRecords);
}
}
function uniqById(data, records) {
var currentIds = data.mapBy("id");
return records.reject(function(record) {
return Ember.A(currentIds).contains(record.id);
});
}
// Delegation to the adapter and promise management
/**
A `PromiseArray` is an object that acts like both an `Ember.Array`
and a promise. When the promise is resolved the resulting value
will be set to the `PromiseArray`'s `content` property. This makes
it easy to create data bindings with the `PromiseArray` that will be
updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
var promiseArray = DS.PromiseArray.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseArray.get('length'); // 0
promiseArray.then(function() {
promiseArray.get('length'); // 100
});
```
@class PromiseArray
@namespace DS
@extends Ember.ArrayProxy
@uses Ember.PromiseProxyMixin
*/
PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin);
/**
A `PromiseObject` is an object that acts like both an `Ember.Object`
and a promise. When the promise is resolved, then the resulting value
will be set to the `PromiseObject`'s `content` property. This makes
it easy to create data bindings with the `PromiseObject` that will
be updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
var promiseObject = DS.PromiseObject.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseObject.get('name'); // null
promiseObject.then(function() {
promiseObject.get('name'); // 'Tomster'
});
```
@class PromiseObject
@namespace DS
@extends Ember.ObjectProxy
@uses Ember.PromiseProxyMixin
*/
PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin);
function promiseObject(promise, label) {
return PromiseObject.create({
promise: Promise.cast(promise, label)
});
}
function promiseArray(promise, label) {
return PromiseArray.create({
promise: Promise.cast(promise, label)
});
}
function isThenable(object) {
return object && typeof object.then === 'function';
}
function serializerFor(container, type, defaultSerializer) {
return container.lookup('serializer:'+type) ||
container.lookup('serializer:application') ||
container.lookup('serializer:' + defaultSerializer) ||
container.lookup('serializer:-default');
}
function defaultSerializer(container) {
return container.lookup('serializer:application') ||
container.lookup('serializer:-default');
}
function serializerForAdapter(adapter, type) {
var serializer = adapter.serializer;
var defaultSerializer = adapter.defaultSerializer;
var container = adapter.container;
if (container && serializer === undefined) {
serializer = serializerFor(container, type.typeKey, defaultSerializer);
}
if (serializer === null || serializer === undefined) {
serializer = {
extract: function(store, type, payload) { return payload; }
};
}
return serializer;
}
function _objectIsAlive(object) {
return !(get(object, "isDestroyed") || get(object, "isDestroying"));
}
function _guard(promise, test) {
var guarded = promise['finally'](function() {
if (!test()) {
guarded._subscribers.length = 0;
}
});
return guarded;
}
function _bind(fn) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
return fn.apply(undefined, args);
};
}
function _find(adapter, store, type, id, record) {
var promise = adapter.find(store, type, id, record);
var serializer = serializerForAdapter(adapter, type);
var label = "DS: Handle Adapter#find of " + type + " with id: " + id;
promise = Promise.cast(promise, label);
promise = _guard(promise, _bind(_objectIsAlive, store));
return promise.then(function(adapterPayload) {
Ember.assert("You made a request for a " + type.typeKey + " with id " + id + ", but the adapter's response did not have any data", adapterPayload);
var payload = serializer.extract(store, type, adapterPayload, id, 'find');
return store.push(type, payload);
}, function(error) {
var record = store.getById(type, id);
if (record) {
record.notFound();
}
throw error;
}, "DS: Extract payload of '" + type + "'");
}
function _findMany(adapter, store, type, ids, records) {
var promise = adapter.findMany(store, type, ids, records);
var serializer = serializerForAdapter(adapter, type);
var label = "DS: Handle Adapter#findMany of " + type;
if (promise === undefined) {
throw new Error('adapter.findMany returned undefined, this was very likely a mistake');
}
var guardedPromise;
promise = Promise.cast(promise, label);
promise = _guard(promise, _bind(_objectIsAlive, store));
return promise.then(function(adapterPayload) {
var payload = serializer.extract(store, type, adapterPayload, null, 'findMany');
Ember.assert("The response from a findMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
return store.pushMany(type, payload);
}, null, "DS: Extract payload of " + type);
}
function _findHasMany(adapter, store, record, link, relationship) {
var promise = adapter.findHasMany(store, record, link, relationship);
var serializer = serializerForAdapter(adapter, relationship.type);
var label = "DS: Handle Adapter#findHasMany of " + record + " : " + relationship.type;
promise = Promise.cast(promise, label);
promise = _guard(promise, _bind(_objectIsAlive, store));
promise = _guard(promise, _bind(_objectIsAlive, record));
return promise.then(function(adapterPayload) {
var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findHasMany');
Ember.assert("The response from a findHasMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
var records = store.pushMany(relationship.type, payload);
record.updateHasMany(relationship.key, records);
}, null, "DS: Extract payload of " + record + " : hasMany " + relationship.type);
}
function _findBelongsTo(adapter, store, record, link, relationship) {
var promise = adapter.findBelongsTo(store, record, link, relationship);
var serializer = serializerForAdapter(adapter, relationship.type);
var label = "DS: Handle Adapter#findBelongsTo of " + record + " : " + relationship.type;
promise = Promise.cast(promise, label);
promise = _guard(promise, _bind(_objectIsAlive, store));
promise = _guard(promise, _bind(_objectIsAlive, record));
return promise.then(function(adapterPayload) {
var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findBelongsTo');
var record = store.push(relationship.type, payload);
record.updateBelongsTo(relationship.key, record);
return record;
}, null, "DS: Extract payload of " + record + " : " + relationship.type);
}
function _findAll(adapter, store, type, sinceToken) {
var promise = adapter.findAll(store, type, sinceToken);
var serializer = serializerForAdapter(adapter, type);
var label = "DS: Handle Adapter#findAll of " + type;
promise = Promise.cast(promise, label);
promise = _guard(promise, _bind(_objectIsAlive, store));
return promise.then(function(adapterPayload) {
var payload = serializer.extract(store, type, adapterPayload, null, 'findAll');
Ember.assert("The response from a findAll must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
store.pushMany(type, payload);
store.didUpdateAll(type);
return store.all(type);
}, null, "DS: Extract payload of findAll " + type);
}
function _findQuery(adapter, store, type, query, recordArray) {
var promise = adapter.findQuery(store, type, query, recordArray);
var serializer = serializerForAdapter(adapter, type);
var label = "DS: Handle Adapter#findQuery of " + type;
promise = Promise.cast(promise, label);
promise = _guard(promise, _bind(_objectIsAlive, store));
return promise.then(function(adapterPayload) {
var payload = serializer.extract(store, type, adapterPayload, null, 'findQuery');
Ember.assert("The response from a findQuery must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
recordArray.load(payload);
return recordArray;
}, null, "DS: Extract payload of findQuery " + type);
}
function _commit(adapter, store, operation, record) {
var type = record.constructor;
var promise = adapter[operation](store, type, record);
var serializer = serializerForAdapter(adapter, type);
var label = "DS: Extract and notify about " + operation + " completion of " + record;
Ember.assert("Your adapter's '" + operation + "' method must return a value, but it returned `undefined", promise !==undefined);
promise = Promise.cast(promise, label);
promise = _guard(promise, _bind(_objectIsAlive, store));
promise = _guard(promise, _bind(_objectIsAlive, record));
return promise.then(function(adapterPayload) {
var payload;
if (adapterPayload) {
payload = serializer.extract(store, type, adapterPayload, get(record, 'id'), operation);
} else {
payload = adapterPayload;
}
store.didSaveRecord(record, payload);
return record;
}, function(reason) {
if (reason instanceof InvalidError) {
store.recordWasInvalid(record, reason.errors);
} else {
store.recordWasError(record, reason);
}
throw reason;
}, label);
}
__exports__.Store = Store;
__exports__.PromiseArray = PromiseArray;
__exports__.PromiseObject = PromiseObject;
__exports__["default"] = Store;
});
define("ember-data/transforms",
["ember-data/transforms/base","ember-data/transforms/number","ember-data/transforms/date","ember-data/transforms/string","ember-data/transforms/boolean","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) {
"use strict";
var Transform = __dependency1__["default"];
var NumberTransform = __dependency2__["default"];
var DateTransform = __dependency3__["default"];
var StringTransform = __dependency4__["default"];
var BooleanTransform = __dependency5__["default"];
__exports__.Transform = Transform;
__exports__.NumberTransform = NumberTransform;
__exports__.DateTransform = DateTransform;
__exports__.StringTransform = StringTransform;
__exports__.BooleanTransform = BooleanTransform;
});
define("ember-data/transforms/base",
["exports"],
function(__exports__) {
"use strict";
/**
The `DS.Transform` class is used to serialize and deserialize model
attributes when they are saved or loaded from an
adapter. Subclassing `DS.Transform` is useful for creating custom
attributes. All subclasses of `DS.Transform` must implement a
`serialize` and a `deserialize` method.
Example
```javascript
// Converts centigrade in the JSON to fahrenheit in the app
App.TemperatureTransform = DS.Transform.extend({
deserialize: function(serialized) {
return (serialized * 1.8) + 32;
},
serialize: function(deserialized) {
return (deserialized - 32) / 1.8;
}
});
```
Usage
```javascript
var attr = DS.attr;
App.Requirement = DS.Model.extend({
name: attr('string'),
temperature: attr('temperature')
});
```
@class Transform
@namespace DS
*/
__exports__["default"] = Ember.Object.extend({
/**
When given a deserialized value from a record attribute this
method must return the serialized value.
Example
```javascript
serialize: function(deserialized) {
return Ember.isEmpty(deserialized) ? null : Number(deserialized);
}
```
@method serialize
@param deserialized The deserialized value
@return The serialized value
*/
serialize: Ember.required(),
/**
When given a serialize value from a JSON object this method must
return the deserialized value for the record attribute.
Example
```javascript
deserialize: function(serialized) {
return empty(serialized) ? null : Number(serialized);
}
```
@method deserialize
@param serialized The serialized value
@return The deserialized value
*/
deserialize: Ember.required()
});
});
define("ember-data/transforms/boolean",
["ember-data/transforms/base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Transform = __dependency1__["default"];
/**
The `DS.BooleanTransform` class is used to serialize and deserialize
boolean attributes on Ember Data record objects. This transform is
used when `boolean` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```javascript
var attr = DS.attr;
App.User = DS.Model.extend({
isAdmin: attr('boolean'),
name: attr('string'),
email: attr('string')
});
```
@class BooleanTransform
@extends DS.Transform
@namespace DS
*/
__exports__["default"] = Transform.extend({
deserialize: function(serialized) {
var type = typeof serialized;
if (type === "boolean") {
return serialized;
} else if (type === "string") {
return serialized.match(/^true$|^t$|^1$/i) !== null;
} else if (type === "number") {
return serialized === 1;
} else {
return false;
}
},
serialize: function(deserialized) {
return Boolean(deserialized);
}
});
});
define("ember-data/transforms/date",
["ember-data/transforms/base","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
The `DS.DateTransform` class is used to serialize and deserialize
date attributes on Ember Data record objects. This transform is used
when `date` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
```javascript
var attr = DS.attr;
App.Score = DS.Model.extend({
value: attr('number'),
player: DS.belongsTo('player'),
date: attr('date')
});
```
@class DateTransform
@extends DS.Transform
@namespace DS
*/
var Transform = __dependency1__["default"];
// Date.prototype.toISOString shim
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
var toISOString = Date.prototype.toISOString || function() {
function pad(number) {
if ( number < 10 ) {
return '0' + number;
}
return number;
}
return this.getUTCFullYear() +
'-' + pad( this.getUTCMonth() + 1 ) +
'-' + pad( this.getUTCDate() ) +
'T' + pad( this.getUTCHours() ) +
':' + pad( this.getUTCMinutes() ) +
':' + pad( this.getUTCSeconds() ) +
'.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
'Z';
};
if (Ember.SHIM_ES5) {
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = toISOString;
}
}
__exports__["default"] = Transform.extend({
deserialize: function(serialized) {
var type = typeof serialized;
if (type === "string") {
return new Date(Ember.Date.parse(serialized));
} else if (type === "number") {
return new Date(serialized);
} else if (serialized === null || serialized === undefined) {
// if the value is not present in the data,
// return undefined, not null.
return serialized;
} else {
return null;
}
},
serialize: function(date) {
if (date instanceof Date) {
return toISOString.call(date);
} else {
return null;
}
}
});
});
define("ember-data/transforms/number",
["ember-data/transforms/base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Transform = __dependency1__["default"];
var empty = Ember.isEmpty;
/**
The `DS.NumberTransform` class is used to serialize and deserialize
numeric attributes on Ember Data record objects. This transform is
used when `number` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```javascript
var attr = DS.attr;
App.Score = DS.Model.extend({
value: attr('number'),
player: DS.belongsTo('player'),
date: attr('date')
});
```
@class NumberTransform
@extends DS.Transform
@namespace DS
*/
__exports__["default"] = Transform.extend({
deserialize: function(serialized) {
return empty(serialized) ? null : Number(serialized);
},
serialize: function(deserialized) {
return empty(deserialized) ? null : Number(deserialized);
}
});
});
define("ember-data/transforms/string",
["ember-data/transforms/base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Transform = __dependency1__["default"];
var none = Ember.isNone;
/**
The `DS.StringTransform` class is used to serialize and deserialize
string attributes on Ember Data record objects. This transform is
used when `string` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```javascript
var attr = DS.attr;
App.User = DS.Model.extend({
isAdmin: attr('boolean'),
name: attr('string'),
email: attr('string')
});
```
@class StringTransform
@extends DS.Transform
@namespace DS
*/
__exports__["default"] = Transform.extend({
deserialize: function(serialized) {
return none(serialized) ? null : String(serialized);
},
serialize: function(deserialized) {
return none(deserialized) ? null : String(deserialized);
}
});
});
define("ember-inflector",
["./system","./helpers","./ext/string","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var Inflector = __dependency1__.Inflector;
var defaultRules = __dependency1__.defaultRules;
var pluralize = __dependency1__.pluralize;
var singularize = __dependency1__.singularize;
Inflector.defaultRules = defaultRules;
Ember.Inflector = Inflector;
Ember.String.pluralize = pluralize;
Ember.String.singularize = singularize;
__exports__["default"] = Inflector;
__exports__.pluralize = pluralize;
__exports__.singularize = singularize;
});
define("ember-inflector/ext/string",
["../system/string"],
function(__dependency1__) {
"use strict";
var pluralize = __dependency1__.pluralize;
var singularize = __dependency1__.singularize;
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) {
/**
See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}}
@method pluralize
@for String
*/
String.prototype.pluralize = function() {
return pluralize(this);
};
/**
See {{#crossLink "Ember.String/singularize"}}{{/crossLink}}
@method singularize
@for String
*/
String.prototype.singularize = function() {
return singularize(this);
};
}
});
define("ember-inflector/helpers",
["./system/string"],
function(__dependency1__) {
"use strict";
var singularize = __dependency1__.singularize;
var pluralize = __dependency1__.pluralize;
/**
*
* If you have Ember Inflector (such as if Ember Data is present),
* singularize a word. For example, turn "oxen" into "ox".
*
* Example:
*
* {{singularize myProperty}}
* {{singularize "oxen"}}
*
* @for Ember.Handlebars.helpers
* @method singularize
* @param {String|Property} word word to singularize
*/
Ember.Handlebars.helper('singularize', singularize);
/**
*
* If you have Ember Inflector (such as if Ember Data is present),
* pluralize a word. For example, turn "ox" into "oxen".
*
* Example:
*
* {{pluralize myProperty}}
* {{pluralize "oxen"}}
*
* @for Ember.Handlebars.helpers
* @method pluralize
* @param {String|Property} word word to pluralize
*/
Ember.Handlebars.helper('pluralize', pluralize);
});
define("ember-inflector/system",
["./system/inflector","./system/string","./system/inflections","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var Inflector = __dependency1__["default"];
var pluralize = __dependency2__.pluralize;
var singularize = __dependency2__.singularize;
var defaultRules = __dependency3__["default"];
Inflector.inflector = new Inflector(defaultRules);
__exports__.Inflector = Inflector;
__exports__.singularize = singularize;
__exports__.pluralize = pluralize;
__exports__.defaultRules = defaultRules;
});
define("ember-inflector/system/inflections",
["exports"],
function(__exports__) {
"use strict";
__exports__["default"] = {
plurals: [
[/$/, 's'],
[/s$/i, 's'],
[/^(ax|test)is$/i, '$1es'],
[/(octop|vir)us$/i, '$1i'],
[/(octop|vir)i$/i, '$1i'],
[/(alias|status)$/i, '$1es'],
[/(bu)s$/i, '$1ses'],
[/(buffal|tomat)o$/i, '$1oes'],
[/([ti])um$/i, '$1a'],
[/([ti])a$/i, '$1a'],
[/sis$/i, 'ses'],
[/(?:([^f])fe|([lr])f)$/i, '$1$2ves'],
[/(hive)$/i, '$1s'],
[/([^aeiouy]|qu)y$/i, '$1ies'],
[/(x|ch|ss|sh)$/i, '$1es'],
[/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'],
[/^(m|l)ouse$/i, '$1ice'],
[/^(m|l)ice$/i, '$1ice'],
[/^(ox)$/i, '$1en'],
[/^(oxen)$/i, '$1'],
[/(quiz)$/i, '$1zes']
],
singular: [
[/s$/i, ''],
[/(ss)$/i, '$1'],
[/(n)ews$/i, '$1ews'],
[/([ti])a$/i, '$1um'],
[/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'],
[/(^analy)(sis|ses)$/i, '$1sis'],
[/([^f])ves$/i, '$1fe'],
[/(hive)s$/i, '$1'],
[/(tive)s$/i, '$1'],
[/([lr])ves$/i, '$1f'],
[/([^aeiouy]|qu)ies$/i, '$1y'],
[/(s)eries$/i, '$1eries'],
[/(m)ovies$/i, '$1ovie'],
[/(x|ch|ss|sh)es$/i, '$1'],
[/^(m|l)ice$/i, '$1ouse'],
[/(bus)(es)?$/i, '$1'],
[/(o)es$/i, '$1'],
[/(shoe)s$/i, '$1'],
[/(cris|test)(is|es)$/i, '$1is'],
[/^(a)x[ie]s$/i, '$1xis'],
[/(octop|vir)(us|i)$/i, '$1us'],
[/(alias|status)(es)?$/i, '$1'],
[/^(ox)en/i, '$1'],
[/(vert|ind)ices$/i, '$1ex'],
[/(matr)ices$/i, '$1ix'],
[/(quiz)zes$/i, '$1'],
[/(database)s$/i, '$1']
],
irregularPairs: [
['person', 'people'],
['man', 'men'],
['child', 'children'],
['sex', 'sexes'],
['move', 'moves'],
['cow', 'kine'],
['zombie', 'zombies']
],
uncountable: [
'equipment',
'information',
'rice',
'money',
'species',
'series',
'fish',
'sheep',
'jeans',
'police'
]
};
});
define("ember-inflector/system/inflector",
["exports"],
function(__exports__) {
"use strict";
var BLANK_REGEX = /^\s*$/;
var LAST_WORD_DASHED_REGEX = /(\w+[_-])([a-z\d]+$)/;
var LAST_WORD_CAMELIZED_REGEX = /(\w+)([A-Z][a-z\d]*$)/;
var CAMELIZED_REGEX = /[A-Z][a-z\d]*$/;
function loadUncountable(rules, uncountable) {
for (var i = 0, length = uncountable.length; i < length; i++) {
rules.uncountable[uncountable[i].toLowerCase()] = true;
}
}
function loadIrregular(rules, irregularPairs) {
var pair;
for (var i = 0, length = irregularPairs.length; i < length; i++) {
pair = irregularPairs[i];
//pluralizing
rules.irregular[pair[0].toLowerCase()] = pair[1];
rules.irregular[pair[1].toLowerCase()] = pair[1];
//singularizing
rules.irregularInverse[pair[1].toLowerCase()] = pair[0];
rules.irregularInverse[pair[0].toLowerCase()] = pair[0];
}
}
/**
Inflector.Ember provides a mechanism for supplying inflection rules for your
application. Ember includes a default set of inflection rules, and provides an
API for providing additional rules.
Examples:
Creating an inflector with no rules.
```js
var inflector = new Ember.Inflector();
```
Creating an inflector with the default ember ruleset.
```js
var inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
inflector.pluralize('cow'); //=> 'kine'
inflector.singularize('kine'); //=> 'cow'
```
Creating an inflector and adding rules later.
```javascript
var inflector = Ember.Inflector.inflector;
inflector.pluralize('advice'); // => 'advices'
inflector.uncountable('advice');
inflector.pluralize('advice'); // => 'advice'
inflector.pluralize('formula'); // => 'formulas'
inflector.irregular('formula', 'formulae');
inflector.pluralize('formula'); // => 'formulae'
// you would not need to add these as they are the default rules
inflector.plural(/$/, 's');
inflector.singular(/s$/i, '');
```
Creating an inflector with a nondefault ruleset.
```javascript
var rules = {
plurals: [ /$/, 's' ],
singular: [ /\s$/, '' ],
irregularPairs: [
[ 'cow', 'kine' ]
],
uncountable: [ 'fish' ]
};
var inflector = new Ember.Inflector(rules);
```
@class Inflector
@namespace Ember
*/
function Inflector(ruleSet) {
ruleSet = ruleSet || {};
ruleSet.uncountable = ruleSet.uncountable || makeDictionary();
ruleSet.irregularPairs = ruleSet.irregularPairs || makeDictionary();
var rules = this.rules = {
plurals: ruleSet.plurals || [],
singular: ruleSet.singular || [],
irregular: makeDictionary(),
irregularInverse: makeDictionary(),
uncountable: makeDictionary()
};
loadUncountable(rules, ruleSet.uncountable);
loadIrregular(rules, ruleSet.irregularPairs);
this.enableCache();
}
if (!Object.create && !Object.create(null).hasOwnProperty) {
throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg");
}
function makeDictionary() {
var cache = Object.create(null);
cache['_dict'] = null;
delete cache['_dict'];
return cache;
}
Inflector.prototype = {
/**
@public
As inflections can be costly, and commonly the same subset of words are repeatedly
inflected an optional cache is provided.
@method enableCache
*/
enableCache: function() {
this.purgeCache();
this.singularize = function(word) {
this._cacheUsed = true;
return this._sCache[word] || (this._sCache[word] = this._singularize(word));
};
this.pluralize = function(word) {
this._cacheUsed = true;
return this._pCache[word] || (this._pCache[word] = this._pluralize(word));
};
},
/**
@public
@method purgedCache
*/
purgeCache: function() {
this._cacheUsed = false;
this._sCache = makeDictionary();
this._pCache = makeDictionary();
},
/**
@public
disable caching
@method disableCache;
*/
disableCache: function() {
this._sCache = null;
this._pCache = null;
this.singularize = function(word) {
return this._singularize(word);
};
this.pluralize = function(word) {
return this._pluralize(word);
};
},
/**
@method plural
@param {RegExp} regex
@param {String} string
*/
plural: function(regex, string) {
if (this._cacheUsed) { this.purgeCache(); }
this.rules.plurals.push([regex, string.toLowerCase()]);
},
/**
@method singular
@param {RegExp} regex
@param {String} string
*/
singular: function(regex, string) {
if (this._cacheUsed) { this.purgeCache(); }
this.rules.singular.push([regex, string.toLowerCase()]);
},
/**
@method uncountable
@param {String} regex
*/
uncountable: function(string) {
if (this._cacheUsed) { this.purgeCache(); }
loadUncountable(this.rules, [string.toLowerCase()]);
},
/**
@method irregular
@param {String} singular
@param {String} plural
*/
irregular: function (singular, plural) {
if (this._cacheUsed) { this.purgeCache(); }
loadIrregular(this.rules, [[singular, plural]]);
},
/**
@method pluralize
@param {String} word
*/
pluralize: function(word) {
return this._pluralize(word);
},
_pluralize: function(word) {
return this.inflect(word, this.rules.plurals, this.rules.irregular);
},
/**
@method singularize
@param {String} word
*/
singularize: function(word) {
return this._singularize(word);
},
_singularize: function(word) {
return this.inflect(word, this.rules.singular, this.rules.irregularInverse);
},
/**
@protected
@method inflect
@param {String} word
@param {Object} typeRules
@param {Object} irregular
*/
inflect: function(word, typeRules, irregular) {
var inflection, substitution, result, lowercase, wordSplit,
firstPhrase, lastWord, isBlank, isCamelized, isUncountable,
isIrregular, isIrregularInverse, rule;
isBlank = BLANK_REGEX.test(word);
isCamelized = CAMELIZED_REGEX.test(word);
firstPhrase = "";
if (isBlank) {
return word;
}
lowercase = word.toLowerCase();
wordSplit = LAST_WORD_DASHED_REGEX.exec(word) || LAST_WORD_CAMELIZED_REGEX.exec(word);
if (wordSplit){
firstPhrase = wordSplit[1];
lastWord = wordSplit[2].toLowerCase();
}
isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord];
if (isUncountable) {
return word;
}
isIrregular = irregular && (irregular[lowercase] || irregular[lastWord]);
if (isIrregular) {
if (irregular[lowercase]){
return isIrregular;
}
else {
isIrregular = (isCamelized) ? isIrregular.capitalize() : isIrregular;
return firstPhrase + isIrregular;
}
}
for (var i = typeRules.length, min = 0; i > min; i--) {
inflection = typeRules[i-1];
rule = inflection[0];
if (rule.test(word)) {
break;
}
}
inflection = inflection || [];
rule = inflection[0];
substitution = inflection[1];
result = word.replace(rule, substitution);
return result;
}
};
__exports__["default"] = Inflector;
});
define("ember-inflector/system/string",
["./inflector","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Inflector = __dependency1__["default"];
function pluralize(word) {
return Inflector.inflector.pluralize(word);
}
function singularize(word) {
return Inflector.inflector.singularize(word);
}
__exports__.pluralize = pluralize;
__exports__.singularize = singularize;
});
global.DS = requireModule('ember-data')['default'];
})(this); |
packages/material-ui-icons/src/Receipt.js | allanalexandre/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M18 17H6v-2h12v2zm0-4H6v-2h12v2zm0-4H6V7h12v2zM3 22l1.5-1.5L6 22l1.5-1.5L9 22l1.5-1.5L12 22l1.5-1.5L15 22l1.5-1.5L18 22l1.5-1.5L21 22V2l-1.5 1.5L18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2 4.5 3.5 3 2v20z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment>
, 'Receipt');
|
packages/wix-style-react/src/TrendIndicator/test/TrendIndicator.spec.js | wix/wix-style-react | import React from 'react';
import { createRendererWithUniDriver, cleanup } from '../../../test/utils/unit';
import TrendIndicator from '../TrendIndicator';
import { trendIndicatorPrivateDriverFactory } from './TrendIndicator.private.uni.driver';
describe(TrendIndicator.displayName, () => {
const render = createRendererWithUniDriver(
trendIndicatorPrivateDriverFactory,
);
afterEach(cleanup);
it('should render', async () => {
const { driver } = render(<TrendIndicator value={10} />);
expect(await driver.exists()).toBe(true);
});
it('should not render when value NaN', async () => {
const { driver } = render(<TrendIndicator value={NaN} />);
expect(await driver.exists()).toBe(false);
});
it('should render positive value', async () => {
const { driver } = render(<TrendIndicator value={10} />);
expect(await driver.getTrendValue()).toEqual(10);
expect(await driver.isTrendIndicatorIconUp()).toEqual(true);
expect(await driver.isTrendIndicatorIconDown()).toEqual(false);
});
it('should render negative value', async () => {
const { driver } = render(<TrendIndicator value={-23} />);
expect(await driver.getTrendValue()).toEqual(23);
expect(await driver.isTrendIndicatorIconUp()).toEqual(false);
expect(await driver.isTrendIndicatorIconDown()).toEqual(true);
});
it('should render 0 as neutral value', async () => {
const { driver } = render(<TrendIndicator value={0} />);
expect(await driver.getTrendValue()).toEqual(0);
expect(await driver.hasTrendIndicatorIcon()).toEqual(false);
});
it('should render inverted positive value', async () => {
const { driver } = render(<TrendIndicator value={10} inverted />);
expect(await driver.getTrendValue()).toEqual(10);
expect(await driver.isTrendIndicatorIconUp()).toEqual(true);
expect(await driver.isTrendIndicatorIconDown()).toEqual(false);
});
it('should render inverted negative value', async () => {
const { driver } = render(<TrendIndicator value={-23} inverted />);
expect(await driver.getTrendValue()).toEqual(23);
expect(await driver.isTrendIndicatorIconUp()).toEqual(false);
expect(await driver.isTrendIndicatorIconDown()).toEqual(true);
});
});
|
files/polymer/0.5.3/polymer.js | moay/jsdelivr | /**
* @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.5.3
window.PolymerGestures = {};
(function(scope) {
var hasFullPath = false;
// test for full event path support
var pathTest = document.createElement('meta');
if (pathTest.createShadowRoot) {
var sr = pathTest.createShadowRoot();
var s = document.createElement('span');
sr.appendChild(s);
pathTest.addEventListener('testpath', function(ev) {
if (ev.path) {
// if the span is in the event path, then path[0] is the real source for all events
hasFullPath = ev.path[0] === s;
}
ev.stopPropagation();
});
var ev = new CustomEvent('testpath', {bubbles: true});
// must add node to DOM to trigger event listener
document.head.appendChild(pathTest);
s.dispatchEvent(ev);
pathTest.parentNode.removeChild(pathTest);
sr = s = null;
}
pathTest = null;
var target = {
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 = [], s = this.shadow(element);
while(s) {
shadows.push(s);
s = this.olderShadow(s);
}
return shadows;
},
searchRoot: function(inRoot, x, y) {
var t, st, sr, os;
if (inRoot) {
t = inRoot.elementFromPoint(x, y);
if (t) {
// found element, check if it has a ShadowRoot
sr = this.targetingShadow(t);
} else if (inRoot !== document) {
// check for sibling roots
sr = this.olderShadow(inRoot);
}
// search other roots, fall back to light dom element
return this.searchRoot(sr, x, y) || t;
}
},
owner: function(element) {
if (!element) {
return document;
}
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) {
if (hasFullPath && inEvent.path && inEvent.path.length) {
return inEvent.path[0];
}
var x = inEvent.clientX, 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);
},
findTouchAction: function(inEvent) {
var n;
if (hasFullPath && inEvent.path && inEvent.path.length) {
var path = inEvent.path;
for (var i = 0; i < path.length; i++) {
n = path[i];
if (n.nodeType === Node.ELEMENT_NODE && n.hasAttribute('touch-action')) {
return n.getAttribute('touch-action');
}
}
} else {
n = inEvent.target;
while(n) {
if (n.nodeType === Node.ELEMENT_NODE && n.hasAttribute('touch-action')) {
return n.getAttribute('touch-action');
}
n = n.parentNode || n.host;
}
}
// auto is default
return "auto";
},
LCA: function(a, b) {
if (a === b) {
return a;
}
if (a && !b) {
return a;
}
if (b && !a) {
return b;
}
if (!b && !a) {
return document;
}
// fast case, a is a direct descendant of b or vice versa
if (a.contains && a.contains(b)) {
return a;
}
if (b.contains && b.contains(a)) {
return b;
}
var adepth = this.depth(a);
var bdepth = this.depth(b);
var d = adepth - bdepth;
if (d >= 0) {
a = this.walk(a, d);
} else {
b = this.walk(b, -d);
}
while (a && b && a !== b) {
a = a.parentNode || a.host;
b = b.parentNode || b.host;
}
return a;
},
walk: function(n, u) {
for (var i = 0; n && (i < u); i++) {
n = n.parentNode || n.host;
}
return n;
},
depth: function(n) {
var d = 0;
while(n) {
d++;
n = n.parentNode || n.host;
}
return d;
},
deepContains: function(a, b) {
var common = this.LCA(a, b);
// if a is the common ancestor, it must "deeply" contain b
return common === a;
},
insideNode: function(node, x, y) {
var rect = node.getBoundingClientRect();
return (rect.left <= x) && (x <= rect.right) && (rect.top <= y) && (y <= rect.bottom);
},
path: function(event) {
var p;
if (hasFullPath && event.path && event.path.length) {
p = event.path;
} else {
p = [];
var n = this.findTarget(event);
while (n) {
p.push(n);
n = n.parentNode || n.host;
}
}
return p;
}
};
scope.targetFinding = target;
/**
* Given an event, finds the "deepest" node that could have been the original target before ShadowDOM retargetting
*
* @param {Event} Event An event object with clientX and clientY properties
* @return {Element} The probable event origninator
*/
scope.findTarget = target.findTarget.bind(target);
/**
* Determines if the "container" node deeply contains the "containee" node, including situations where the "containee" is contained by one or more ShadowDOM
* roots.
*
* @param {Node} container
* @param {Node} containee
* @return {Boolean}
*/
scope.deepContains = target.deepContains.bind(target);
/**
* Determines if the x/y position is inside the given node.
*
* Example:
*
* function upHandler(event) {
* var innode = PolymerGestures.insideNode(event.target, event.clientX, event.clientY);
* if (innode) {
* // wait for tap?
* } else {
* // tap will never happen
* }
* }
*
* @param {Node} node
* @param {Number} x Screen X position
* @param {Number} y screen Y position
* @return {Boolean}
*/
scope.insideNode = target.insideNode;
})(window.PolymerGestures);
(function() {
function shadowSelector(v) {
return 'html /deep/ ' + selector(v);
}
function selector(v) {
return '[touch-action="' + v + '"]';
}
function rule(v) {
return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + ';}';
}
var attrib2css = [
'none',
'auto',
'pan-x',
'pan-y',
{
rule: 'pan-x pan-y',
selectors: [
'pan-x pan-y',
'pan-y pan-x'
]
},
'manipulation'
];
var styles = '';
// only install stylesheet if the browser has touch action support
var hasTouchAction = typeof document.head.style.touchAction === 'string';
// only add shadow selectors if shadowdom is supported
var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;
if (hasTouchAction) {
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);
}
})();
/**
* 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` and initialized with properties from `inDict`.
*/
(function(scope) {
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
];
var NOP_FACTORY = function(){ return function(){}; };
var eventFactory = {
// TODO(dfreedm): this is overridden by tap recognizer, needs review
preventTap: NOP_FACTORY,
makeBaseEvent: function(inType, inDict) {
var e = document.createEvent('Event');
e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false);
e.preventTap = eventFactory.preventTap(e);
return e;
},
makeGestureEvent: function(inType, inDict) {
inDict = inDict || Object.create(null);
var e = this.makeBaseEvent(inType, inDict);
for (var i = 0, keys = Object.keys(inDict), k; i < keys.length; i++) {
k = keys[i];
e[k] = inDict[k];
}
return e;
},
makePointerEvent: function(inType, inDict) {
inDict = inDict || Object.create(null);
var e = this.makeBaseEvent(inType, inDict);
// define inherited MouseEvent properties
for(var i = 0, 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;
e._source = inDict._source || '';
return e;
}
};
scope.eventFactory = eventFactory;
})(window.PolymerGestures);
/**
* This module implements an map of pointer states
*/
(function(scope) {
var USE_MAP = window.Map && window.Map.prototype.forEach;
var POINTERS_FN = function(){ return this.size; };
function PointerMap() {
if (USE_MAP) {
var m = new Map();
m.pointers = POINTERS_FN;
return m;
} else {
this.keys = [];
this.values = [];
}
}
PointerMap.prototype = {
set: function(inId, inEvent) {
var i = this.keys.indexOf(inId);
if (i > -1) {
this.values[i] = inEvent;
} else {
this.keys.push(inId);
this.values.push(inEvent);
}
},
has: function(inId) {
return this.keys.indexOf(inId) > -1;
},
'delete': function(inId) {
var i = this.keys.indexOf(inId);
if (i > -1) {
this.keys.splice(i, 1);
this.values.splice(i, 1);
}
},
get: function(inId) {
var i = this.keys.indexOf(inId);
return this.values[i];
},
clear: function() {
this.keys.length = 0;
this.values.length = 0;
},
// return value, key, map
forEach: function(callback, thisArg) {
this.values.forEach(function(v, i) {
callback.call(thisArg, v, this.keys[i], this);
}, this);
},
pointers: function() {
return this.keys.length;
}
};
scope.PointerMap = PointerMap;
})(window.PolymerGestures);
(function(scope) {
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',
// gesture addons
'preventTap',
'tapPrevented',
'_source'
];
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,
function(){},
false
];
var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined');
var eventFactory = scope.eventFactory;
// set of recognizers to run for the currently handled event
var currentGestures;
/**
* 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 = {
IS_IOS: false,
pointermap: new scope.PointerMap(),
requiredGestures: new scope.PointerMap(),
eventMap: Object.create(null),
// Scope objects for native events.
// This exists for ease of testing.
eventSources: Object.create(null),
eventSourceList: [],
gestures: [],
// map gesture event -> {listeners: int, index: gestures[int]}
dependencyMap: {
// make sure down and up are in the map to trigger "register"
down: {listeners: 0, index: -1},
up: {listeners: 0, index: -1}
},
gestureQueue: [],
/**
* 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);
}
},
registerGesture: function(name, source) {
var obj = Object.create(null);
obj.listeners = 0;
obj.index = this.gestures.length;
for (var i = 0, g; i < source.exposes.length; i++) {
g = source.exposes[i].toLowerCase();
this.dependencyMap[g] = obj;
}
this.gestures.push(source);
},
register: function(element, initial) {
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, initial);
}
},
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);
}
},
// EVENTS
down: function(inEvent) {
this.requiredGestures.set(inEvent.pointerId, currentGestures);
this.fireEvent('down', inEvent);
},
move: function(inEvent) {
// pipe move events into gesture queue directly
inEvent.type = 'move';
this.fillGestureQueue(inEvent);
},
up: function(inEvent) {
this.fireEvent('up', inEvent);
this.requiredGestures.delete(inEvent.pointerId);
},
cancel: function(inEvent) {
inEvent.tapPrevented = true;
this.fireEvent('up', inEvent);
this.requiredGestures.delete(inEvent.pointerId);
},
addGestureDependency: function(node, currentGestures) {
var gesturesWanted = node._pgEvents;
if (gesturesWanted && currentGestures) {
var gk = Object.keys(gesturesWanted);
for (var i = 0, r, ri, g; i < gk.length; i++) {
// gesture
g = gk[i];
if (gesturesWanted[g] > 0) {
// lookup gesture recognizer
r = this.dependencyMap[g];
// recognizer index
ri = r ? r.index : -1;
currentGestures[ri] = true;
}
}
}
},
// LISTENER LOGIC
eventHandler: function(inEvent) {
// This is used to prevent multiple dispatch of events 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.
var type = inEvent.type;
// only generate the list of desired events on "down"
if (type === 'touchstart' || type === 'mousedown' || type === 'pointerdown' || type === 'MSPointerDown') {
if (!inEvent._handledByPG) {
currentGestures = {};
}
// in IOS mode, there is only a listener on the document, so this is not re-entrant
if (this.IS_IOS) {
var ev = inEvent;
if (type === 'touchstart') {
var ct = inEvent.changedTouches[0];
// set up a fake event to give to the path builder
ev = {target: inEvent.target, clientX: ct.clientX, clientY: ct.clientY, path: inEvent.path};
}
// use event path if available, otherwise build a path from target finding
var nodes = inEvent.path || scope.targetFinding.path(ev);
for (var i = 0, n; i < nodes.length; i++) {
n = nodes[i];
this.addGestureDependency(n, currentGestures);
}
} else {
this.addGestureDependency(inEvent.currentTarget, currentGestures);
}
}
if (inEvent._handledByPG) {
return;
}
var fn = this.eventMap && this.eventMap[type];
if (fn) {
fn(inEvent);
}
inEvent._handledByPG = true;
},
// set up event listeners
listen: function(target, events) {
for (var i = 0, l = events.length, e; (i < l) && (e = events[i]); i++) {
this.addEvent(target, e);
}
},
// remove event listeners
unlisten: function(target, events) {
for (var i = 0, l = events.length, e; (i < l) && (e = events[i]); i++) {
this.removeEvent(target, e);
}
},
addEvent: function(target, eventName) {
target.addEventListener(eventName, this.boundHandler);
},
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) {
var e = eventFactory.makePointerEvent(inType, inEvent);
e.preventDefault = inEvent.preventDefault;
e.tapPrevented = inEvent.tapPrevented;
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), 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 <use> element that is represented by the instance for Safari, Chrome, IE.
// This is the behavior implemented by Firefox.
if (p === 'target' || p === 'relatedTarget') {
if (HAS_SVG_INSTANCE && eventCopy[p] instanceof SVGElementInstance) {
eventCopy[p] = eventCopy[p].correspondingUseElement;
}
}
}
// keep the semantics of preventDefault
eventCopy.preventDefault = function() {
inEvent.preventDefault();
};
return eventCopy;
},
/**
* 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: function(inEvent) {
var t = inEvent._target;
if (t) {
t.dispatchEvent(inEvent);
// clone the event for the gesture system to process
// clone after dispatch to pick up gesture prevention code
var clone = this.cloneEvent(inEvent);
clone.target = t;
this.fillGestureQueue(clone);
}
},
gestureTrigger: function() {
// process the gesture queue
for (var i = 0, e, rg; i < this.gestureQueue.length; i++) {
e = this.gestureQueue[i];
rg = e._requiredGestures;
if (rg) {
for (var j = 0, g, fn; j < this.gestures.length; j++) {
// only run recognizer if an element in the source event's path is listening for those gestures
if (rg[j]) {
g = this.gestures[j];
fn = g[e.type];
if (fn) {
fn.call(g, e);
}
}
}
}
}
this.gestureQueue.length = 0;
},
fillGestureQueue: function(ev) {
// only trigger the gesture queue once
if (!this.gestureQueue.length) {
requestAnimationFrame(this.boundGestureTrigger);
}
ev._requiredGestures = this.requiredGestures.get(ev.pointerId);
this.gestureQueue.push(ev);
}
};
dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
dispatcher.boundGestureTrigger = dispatcher.gestureTrigger.bind(dispatcher);
scope.dispatcher = dispatcher;
/**
* Listen for `gesture` on `node` with the `handler` function
*
* If `handler` is the first listener for `gesture`, the underlying gesture recognizer is then enabled.
*
* @param {Element} node
* @param {string} gesture
* @return Boolean `gesture` is a valid gesture
*/
scope.activateGesture = function(node, gesture) {
var g = gesture.toLowerCase();
var dep = dispatcher.dependencyMap[g];
if (dep) {
var recognizer = dispatcher.gestures[dep.index];
if (!node._pgListeners) {
dispatcher.register(node);
node._pgListeners = 0;
}
// TODO(dfreedm): re-evaluate bookkeeping to avoid using attributes
if (recognizer) {
var touchAction = recognizer.defaultActions && recognizer.defaultActions[g];
var actionNode;
switch(node.nodeType) {
case Node.ELEMENT_NODE:
actionNode = node;
break;
case Node.DOCUMENT_FRAGMENT_NODE:
actionNode = node.host;
break;
default:
actionNode = null;
break;
}
if (touchAction && actionNode && !actionNode.hasAttribute('touch-action')) {
actionNode.setAttribute('touch-action', touchAction);
}
}
if (!node._pgEvents) {
node._pgEvents = {};
}
node._pgEvents[g] = (node._pgEvents[g] || 0) + 1;
node._pgListeners++;
}
return Boolean(dep);
};
/**
*
* Listen for `gesture` from `node` with `handler` function.
*
* @param {Element} node
* @param {string} gesture
* @param {Function} handler
* @param {Boolean} capture
*/
scope.addEventListener = function(node, gesture, handler, capture) {
if (handler) {
scope.activateGesture(node, gesture);
node.addEventListener(gesture, handler, capture);
}
};
/**
* Tears down the gesture configuration for `node`
*
* If `handler` is the last listener for `gesture`, the underlying gesture recognizer is disabled.
*
* @param {Element} node
* @param {string} gesture
* @return Boolean `gesture` is a valid gesture
*/
scope.deactivateGesture = function(node, gesture) {
var g = gesture.toLowerCase();
var dep = dispatcher.dependencyMap[g];
if (dep) {
if (node._pgListeners > 0) {
node._pgListeners--;
}
if (node._pgListeners === 0) {
dispatcher.unregister(node);
}
if (node._pgEvents) {
if (node._pgEvents[g] > 0) {
node._pgEvents[g]--;
} else {
node._pgEvents[g] = 0;
}
}
}
return Boolean(dep);
};
/**
* Stop listening for `gesture` from `node` with `handler` function.
*
* @param {Element} node
* @param {string} gesture
* @param {Function} handler
* @param {Boolean} capture
*/
scope.removeEventListener = function(node, gesture, handler, capture) {
if (handler) {
scope.deactivateGesture(node, gesture);
node.removeEventListener(gesture, handler, capture);
}
};
})(window.PolymerGestures);
(function(scope) {
var dispatcher = scope.dispatcher;
var pointermap = dispatcher.pointermap;
// radius around touchend that swallows mouse events
var DEDUP_DIST = 25;
var WHICH_TO_BUTTONS = [0, 1, 4, 2];
var currentButtons = 0;
var FIREFOX_LINUX = /Linux.*Firefox\//i;
var HAS_BUTTONS = (function() {
// firefox on linux returns spec-incorrect values for mouseup.buttons
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.buttons#See_also
// https://codereview.chromium.org/727593003/#msg16
if (FIREFOX_LINUX.test(navigator.userAgent)) {
return false;
}
try {
return new MouseEvent('test', {buttons: 1}).buttons === 1;
} catch (e) {
return false;
}
})();
// handler block for native mouse events
var mouseEvents = {
POINTER_ID: 1,
POINTER_TYPE: 'mouse',
events: [
'mousedown',
'mousemove',
'mouseup'
],
exposes: [
'down',
'up',
'move'
],
register: function(target) {
dispatcher.listen(target, this.events);
},
unregister: function(target) {
if (target === document) {
return;
}
dispatcher.unlisten(target, this.events);
},
lastTouches: [],
// collide with the global mouse listener
isEventSimulatedFromTouch: function(inEvent) {
var lts = this.lastTouches;
var x = inEvent.clientX, 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), dy = Math.abs(y - t.y);
if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
return true;
}
}
},
prepareEvent: function(inEvent) {
var e = dispatcher.cloneEvent(inEvent);
e.pointerId = this.POINTER_ID;
e.isPrimary = true;
e.pointerType = this.POINTER_TYPE;
e._source = 'mouse';
if (!HAS_BUTTONS) {
var type = inEvent.type;
var bit = WHICH_TO_BUTTONS[inEvent.which] || 0;
if (type === 'mousedown') {
currentButtons |= bit;
} else if (type === 'mouseup') {
currentButtons &= ~bit;
}
e.buttons = currentButtons;
}
return e;
},
mousedown: function(inEvent) {
if (!this.isEventSimulatedFromTouch(inEvent)) {
var p = pointermap.has(this.POINTER_ID);
var e = this.prepareEvent(inEvent);
e.target = scope.findTarget(inEvent);
pointermap.set(this.POINTER_ID, e.target);
dispatcher.down(e);
}
},
mousemove: function(inEvent) {
if (!this.isEventSimulatedFromTouch(inEvent)) {
var target = pointermap.get(this.POINTER_ID);
if (target) {
var e = this.prepareEvent(inEvent);
e.target = target;
// handle case where we missed a mouseup
if ((HAS_BUTTONS ? e.buttons : e.which) === 0) {
if (!HAS_BUTTONS) {
currentButtons = e.buttons = 0;
}
dispatcher.cancel(e);
this.cleanupMouse(e.buttons);
} else {
dispatcher.move(e);
}
}
}
},
mouseup: function(inEvent) {
if (!this.isEventSimulatedFromTouch(inEvent)) {
var e = this.prepareEvent(inEvent);
e.relatedTarget = scope.findTarget(inEvent);
e.target = pointermap.get(this.POINTER_ID);
dispatcher.up(e);
this.cleanupMouse(e.buttons);
}
},
cleanupMouse: function(buttons) {
if (buttons === 0) {
pointermap.delete(this.POINTER_ID);
}
}
};
scope.mouseEvents = mouseEvents;
})(window.PolymerGestures);
(function(scope) {
var dispatcher = scope.dispatcher;
var allShadows = scope.targetFinding.allShadows.bind(scope.targetFinding);
var pointermap = dispatcher.pointermap;
var touchMap = Array.prototype.map.call.bind(Array.prototype.map);
// This should be long enough to ignore compat mouse events made by touch
var DEDUP_TIMEOUT = 2500;
var DEDUP_DIST = 25;
var CLICK_COUNT_TIMEOUT = 200;
var HYSTERESIS = 20;
var ATTRIB = 'touch-action';
// TODO(dfreedm): disable until http://crbug.com/399765 is resolved
// var HAS_TOUCH_ACTION = ATTRIB in document.head.style;
var HAS_TOUCH_ACTION = false;
// handler block for native touch events
var touchEvents = {
IS_IOS: false,
events: [
'touchstart',
'touchmove',
'touchend',
'touchcancel'
],
exposes: [
'down',
'up',
'move'
],
register: function(target, initial) {
if (this.IS_IOS ? initial : !initial) {
dispatcher.listen(target, this.events);
}
},
unregister: function(target) {
if (!this.IS_IOS) {
dispatcher.unlisten(target, this.events);
}
},
scrollTypes: {
EMITTER: 'none',
XSCROLLER: 'pan-x',
YSCROLLER: 'pan-y',
},
touchActionToScrollType: function(touchAction) {
var t = touchAction;
var st = this.scrollTypes;
if (t === st.EMITTER) {
return 'none';
} else if (t === st.XSCROLLER) {
return 'X';
} else if (t === st.YSCROLLER) {
return 'Y';
} else {
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 (pointermap.pointers() === 0 || (pointermap.pointers() === 1 && pointermap.has(1))) {
this.firstTouch = inTouch.identifier;
this.firstXY = {X: inTouch.clientX, Y: inTouch.clientY};
this.firstTarget = inTouch.target;
this.scrolling = null;
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;
},
findTarget: function(touch, id) {
if (this.currentTouchEvent.type === 'touchstart') {
if (this.isPrimaryTouch(touch)) {
var fastPath = {
clientX: touch.clientX,
clientY: touch.clientY,
path: this.currentTouchEvent.path,
target: this.currentTouchEvent.target
};
return scope.findTarget(fastPath);
} else {
return scope.findTarget(touch);
}
}
// reuse target we found in touchstart
return pointermap.get(id);
},
touchToPointer: function(inTouch) {
var cte = this.currentTouchEvent;
var e = dispatcher.cloneEvent(inTouch);
// Spec specifies that pointerId 1 is reserved 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 = this.findTarget(inTouch, id);
e.bubbles = true;
e.cancelable = true;
e.detail = this.clickCount;
e.buttons = this.typeToButtons(cte.type);
e.width = inTouch.webkitRadiusX || inTouch.radiusX || 0;
e.height = inTouch.webkitRadiusY || inTouch.radiusY || 0;
e.pressure = inTouch.webkitForce || inTouch.force || 0.5;
e.isPrimary = this.isPrimaryTouch(inTouch);
e.pointerType = this.POINTER_TYPE;
e._source = 'touch';
// 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, p; i < tl.length; i++) {
t = tl[i];
p = this.touchToPointer(t);
if (inEvent.type === 'touchstart') {
pointermap.set(p.pointerId, p.target);
}
if (pointermap.has(p.pointerId)) {
inFunction.call(this, p);
}
if (inEvent.type === 'touchend' || inEvent._cancel) {
this.cleanUpPointer(p);
}
}
},
// 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 touchAction = scope.targetFinding.findTouchAction(inEvent);
var scrollAxis = this.touchActionToScrollType(touchAction);
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;
}
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.pointers() should be < tl.length here, as the touchstart has not
// been processed yet.
if (pointermap.pointers() >= tl.length) {
var d = [];
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;
d.push(p);
}
}, this);
d.forEach(function(p) {
this.cancel(p);
pointermap.delete(p.pointerId);
}, this);
}
},
touchstart: function(inEvent) {
this.vacuumTouches(inEvent);
this.setPrimaryTouch(inEvent.changedTouches[0]);
this.dedupSynthMouse(inEvent);
if (!this.scrolling) {
this.clickCount++;
this.processTouches(inEvent, this.down);
}
},
down: function(inPointer) {
dispatcher.down(inPointer);
},
touchmove: function(inEvent) {
if (HAS_TOUCH_ACTION) {
// touchevent.cancelable == false is sent when the page is scrolling under native Touch Action in Chrome 36
// https://groups.google.com/a/chromium.org/d/msg/input-dev/wHnyukcYBcA/b9kmtwM1jJQJ
if (inEvent.cancelable) {
this.processTouches(inEvent, this.move);
}
} else {
if (!this.scrolling) {
if (this.scrolling === null && this.shouldScroll(inEvent)) {
this.scrolling = true;
} else {
this.scrolling = false;
inEvent.preventDefault();
this.processTouches(inEvent, this.move);
}
} else if (this.firstXY) {
var t = inEvent.changedTouches[0];
var dx = t.clientX - this.firstXY.X;
var dy = t.clientY - this.firstXY.Y;
var dd = Math.sqrt(dx * dx + dy * dy);
if (dd >= HYSTERESIS) {
this.touchcancel(inEvent);
this.scrolling = true;
this.firstXY = null;
}
}
}
},
move: function(inPointer) {
dispatcher.move(inPointer);
},
touchend: function(inEvent) {
this.dedupSynthMouse(inEvent);
this.processTouches(inEvent, this.up);
},
up: function(inPointer) {
inPointer.relatedTarget = scope.findTarget(inPointer);
dispatcher.up(inPointer);
},
cancel: function(inPointer) {
dispatcher.cancel(inPointer);
},
touchcancel: function(inEvent) {
inEvent._cancel = true;
this.processTouches(inEvent, this.cancel);
},
cleanUpPointer: function(inPointer) {
pointermap['delete'](inPointer.pointerId);
this.removePrimaryPointer(inPointer);
},
// prevent synth mouse events from creating pointer events
dedupSynthMouse: function(inEvent) {
var lts = scope.mouseEvents.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);
}
}
};
// prevent "ghost clicks" that come from elements that were removed in a touch handler
var STOP_PROP_FN = Event.prototype.stopImmediatePropagation || Event.prototype.stopPropagation;
document.addEventListener('click', function(ev) {
var x = ev.clientX, y = ev.clientY;
// check if a click is within DEDUP_DIST px radius of the touchstart
var closeTo = function(touch) {
var dx = Math.abs(x - touch.x), dy = Math.abs(y - touch.y);
return (dx <= DEDUP_DIST && dy <= DEDUP_DIST);
};
// if click coordinates are close to touch coordinates, assume the click came from a touch
var wasTouched = scope.mouseEvents.lastTouches.some(closeTo);
// if the click came from touch, and the touchstart target is not in the path of the click event,
// then the touchstart target was probably removed, and the click should be "busted"
var path = scope.targetFinding.path(ev);
if (wasTouched) {
for (var i = 0; i < path.length; i++) {
if (path[i] === touchEvents.firstTarget) {
return;
}
}
ev.preventDefault();
STOP_PROP_FN.call(ev);
}
}, true);
scope.touchEvents = touchEvents;
})(window.PolymerGestures);
(function(scope) {
var dispatcher = scope.dispatcher;
var pointermap = dispatcher.pointermap;
var HAS_BITMAP_TYPE = window.MSPointerEvent && typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
var msEvents = {
events: [
'MSPointerDown',
'MSPointerMove',
'MSPointerUp',
'MSPointerCancel',
],
register: function(target) {
dispatcher.listen(target, this.events);
},
unregister: function(target) {
if (target === document) {
return;
}
dispatcher.unlisten(target, this.events);
},
POINTER_TYPES: [
'',
'unavailable',
'touch',
'pen',
'mouse'
],
prepareEvent: function(inEvent) {
var e = inEvent;
e = dispatcher.cloneEvent(inEvent);
if (HAS_BITMAP_TYPE) {
e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
}
e._source = 'ms';
return e;
},
cleanup: function(id) {
pointermap['delete'](id);
},
MSPointerDown: function(inEvent) {
var e = this.prepareEvent(inEvent);
e.target = scope.findTarget(inEvent);
pointermap.set(inEvent.pointerId, e.target);
dispatcher.down(e);
},
MSPointerMove: function(inEvent) {
var target = pointermap.get(inEvent.pointerId);
if (target) {
var e = this.prepareEvent(inEvent);
e.target = target;
dispatcher.move(e);
}
},
MSPointerUp: function(inEvent) {
var e = this.prepareEvent(inEvent);
e.relatedTarget = scope.findTarget(inEvent);
e.target = pointermap.get(e.pointerId);
dispatcher.up(e);
this.cleanup(inEvent.pointerId);
},
MSPointerCancel: function(inEvent) {
var e = this.prepareEvent(inEvent);
e.relatedTarget = scope.findTarget(inEvent);
e.target = pointermap.get(e.pointerId);
dispatcher.cancel(e);
this.cleanup(inEvent.pointerId);
}
};
scope.msEvents = msEvents;
})(window.PolymerGestures);
(function(scope) {
var dispatcher = scope.dispatcher;
var pointermap = dispatcher.pointermap;
var pointerEvents = {
events: [
'pointerdown',
'pointermove',
'pointerup',
'pointercancel'
],
prepareEvent: function(inEvent) {
var e = dispatcher.cloneEvent(inEvent);
e._source = 'pointer';
return e;
},
register: function(target) {
dispatcher.listen(target, this.events);
},
unregister: function(target) {
if (target === document) {
return;
}
dispatcher.unlisten(target, this.events);
},
cleanup: function(id) {
pointermap['delete'](id);
},
pointerdown: function(inEvent) {
var e = this.prepareEvent(inEvent);
e.target = scope.findTarget(inEvent);
pointermap.set(e.pointerId, e.target);
dispatcher.down(e);
},
pointermove: function(inEvent) {
var target = pointermap.get(inEvent.pointerId);
if (target) {
var e = this.prepareEvent(inEvent);
e.target = target;
dispatcher.move(e);
}
},
pointerup: function(inEvent) {
var e = this.prepareEvent(inEvent);
e.relatedTarget = scope.findTarget(inEvent);
e.target = pointermap.get(e.pointerId);
dispatcher.up(e);
this.cleanup(inEvent.pointerId);
},
pointercancel: function(inEvent) {
var e = this.prepareEvent(inEvent);
e.relatedTarget = scope.findTarget(inEvent);
e.target = pointermap.get(e.pointerId);
dispatcher.cancel(e);
this.cleanup(inEvent.pointerId);
}
};
scope.pointerEvents = pointerEvents;
})(window.PolymerGestures);
/**
* This module contains the handlers for native platform events.
* From here, the dispatcher is called to create unified pointer events.
* Included are touch events (v1), mouse events, and MSPointerEvents.
*/
(function(scope) {
var dispatcher = scope.dispatcher;
var nav = window.navigator;
if (window.PointerEvent) {
dispatcher.registerSource('pointer', scope.pointerEvents);
} else if (nav.msPointerEnabled) {
dispatcher.registerSource('ms', scope.msEvents);
} else {
dispatcher.registerSource('mouse', scope.mouseEvents);
if (window.ontouchstart !== undefined) {
dispatcher.registerSource('touch', scope.touchEvents);
}
}
// Work around iOS bugs https://bugs.webkit.org/show_bug.cgi?id=135628 and https://bugs.webkit.org/show_bug.cgi?id=136506
var ua = navigator.userAgent;
var IS_IOS = ua.match(/iPad|iPhone|iPod/) && 'ontouchstart' in window;
dispatcher.IS_IOS = IS_IOS;
scope.touchEvents.IS_IOS = IS_IOS;
dispatcher.register(document, true);
})(window.PolymerGestures);
/**
* This event denotes the beginning of a series of tracking events.
*
* @module PointerGestures
* @submodule Events
* @class trackstart
*/
/**
* Pixels moved in the x direction since trackstart.
* @type Number
* @property dx
*/
/**
* Pixes moved in the y direction since trackstart.
* @type Number
* @property dy
*/
/**
* Pixels moved in the x direction since the last track.
* @type Number
* @property ddx
*/
/**
* Pixles moved in the y direction since the last track.
* @type Number
* @property ddy
*/
/**
* The clientX position of the track gesture.
* @type Number
* @property clientX
*/
/**
* The clientY position of the track gesture.
* @type Number
* @property clientY
*/
/**
* The pageX position of the track gesture.
* @type Number
* @property pageX
*/
/**
* The pageY position of the track gesture.
* @type Number
* @property pageY
*/
/**
* The screenX position of the track gesture.
* @type Number
* @property screenX
*/
/**
* The screenY position of the track gesture.
* @type Number
* @property screenY
*/
/**
* The last x axis direction of the pointer.
* @type Number
* @property xDirection
*/
/**
* The last y axis direction of the pointer.
* @type Number
* @property yDirection
*/
/**
* A shared object between all tracking events.
* @type Object
* @property trackInfo
*/
/**
* The element currently under the pointer.
* @type Element
* @property relatedTarget
*/
/**
* The type of pointer that make the track gesture.
* @type String
* @property pointerType
*/
/**
*
* This event fires for all pointer movement being tracked.
*
* @class track
* @extends trackstart
*/
/**
* This event fires when the pointer is no longer being tracked.
*
* @class trackend
* @extends trackstart
*/
(function(scope) {
var dispatcher = scope.dispatcher;
var eventFactory = scope.eventFactory;
var pointermap = new scope.PointerMap();
var track = {
events: [
'down',
'move',
'up',
],
exposes: [
'trackstart',
'track',
'trackx',
'tracky',
'trackend'
],
defaultActions: {
'track': 'none',
'trackx': 'pan-y',
'tracky': 'pan-x'
},
WIGGLE_THRESHOLD: 4,
clampDir: function(inDelta) {
return inDelta > 0 ? 1 : -1;
},
calcPositionDelta: function(inA, inB) {
var x = 0, y = 0;
if (inA && inB) {
x = inB.pageX - inA.pageX;
y = inB.pageY - inA.pageY;
}
return {x: x, y: y};
},
fireTrack: function(inType, inEvent, inTrackingData) {
var t = inTrackingData;
var d = this.calcPositionDelta(t.downEvent, inEvent);
var dd = this.calcPositionDelta(t.lastMoveEvent, inEvent);
if (dd.x) {
t.xDirection = this.clampDir(dd.x);
} else if (inType === 'trackx') {
return;
}
if (dd.y) {
t.yDirection = this.clampDir(dd.y);
} else if (inType === 'tracky') {
return;
}
var gestureProto = {
bubbles: true,
cancelable: true,
trackInfo: t.trackInfo,
relatedTarget: inEvent.relatedTarget,
pointerType: inEvent.pointerType,
pointerId: inEvent.pointerId,
_source: 'track'
};
if (inType !== 'tracky') {
gestureProto.x = inEvent.x;
gestureProto.dx = d.x;
gestureProto.ddx = dd.x;
gestureProto.clientX = inEvent.clientX;
gestureProto.pageX = inEvent.pageX;
gestureProto.screenX = inEvent.screenX;
gestureProto.xDirection = t.xDirection;
}
if (inType !== 'trackx') {
gestureProto.dy = d.y;
gestureProto.ddy = dd.y;
gestureProto.y = inEvent.y;
gestureProto.clientY = inEvent.clientY;
gestureProto.pageY = inEvent.pageY;
gestureProto.screenY = inEvent.screenY;
gestureProto.yDirection = t.yDirection;
}
var e = eventFactory.makeGestureEvent(inType, gestureProto);
t.downTarget.dispatchEvent(e);
},
down: function(inEvent) {
if (inEvent.isPrimary && (inEvent.pointerType === 'mouse' ? inEvent.buttons === 1 : true)) {
var p = {
downEvent: inEvent,
downTarget: inEvent.target,
trackInfo: {},
lastMoveEvent: null,
xDirection: 0,
yDirection: 0,
tracking: false
};
pointermap.set(inEvent.pointerId, p);
}
},
move: function(inEvent) {
var p = pointermap.get(inEvent.pointerId);
if (p) {
if (!p.tracking) {
var d = this.calcPositionDelta(p.downEvent, inEvent);
var move = d.x * d.x + d.y * d.y;
// start tracking only if finger moves more than WIGGLE_THRESHOLD
if (move > this.WIGGLE_THRESHOLD) {
p.tracking = true;
p.lastMoveEvent = p.downEvent;
this.fireTrack('trackstart', inEvent, p);
}
}
if (p.tracking) {
this.fireTrack('track', inEvent, p);
this.fireTrack('trackx', inEvent, p);
this.fireTrack('tracky', inEvent, p);
}
p.lastMoveEvent = inEvent;
}
},
up: function(inEvent) {
var p = pointermap.get(inEvent.pointerId);
if (p) {
if (p.tracking) {
this.fireTrack('trackend', inEvent, p);
}
pointermap.delete(inEvent.pointerId);
}
}
};
dispatcher.registerGesture('track', track);
})(window.PolymerGestures);
/**
* This event is fired when a pointer is held down for 200ms.
*
* @module PointerGestures
* @submodule Events
* @class hold
*/
/**
* Type of pointer that made the holding event.
* @type String
* @property pointerType
*/
/**
* Screen X axis position of the held pointer
* @type Number
* @property clientX
*/
/**
* Screen Y axis position of the held pointer
* @type Number
* @property clientY
*/
/**
* Type of pointer that made the holding event.
* @type String
* @property pointerType
*/
/**
* This event is fired every 200ms while a pointer is held down.
*
* @class holdpulse
* @extends hold
*/
/**
* Milliseconds pointer has been held down.
* @type Number
* @property holdTime
*/
/**
* This event is fired when a held pointer is released or moved.
*
* @class release
*/
(function(scope) {
var dispatcher = scope.dispatcher;
var eventFactory = scope.eventFactory;
var hold = {
// wait at least HOLD_DELAY ms between hold and pulse events
HOLD_DELAY: 200,
// pointer can move WIGGLE_THRESHOLD pixels before not counting as a hold
WIGGLE_THRESHOLD: 16,
events: [
'down',
'move',
'up',
],
exposes: [
'hold',
'holdpulse',
'release'
],
heldPointer: null,
holdJob: null,
pulse: function() {
var hold = Date.now() - this.heldPointer.timeStamp;
var type = this.held ? 'holdpulse' : 'hold';
this.fireHold(type, hold);
this.held = true;
},
cancel: function() {
clearInterval(this.holdJob);
if (this.held) {
this.fireHold('release');
}
this.held = false;
this.heldPointer = null;
this.target = null;
this.holdJob = null;
},
down: function(inEvent) {
if (inEvent.isPrimary && !this.heldPointer) {
this.heldPointer = inEvent;
this.target = inEvent.target;
this.holdJob = setInterval(this.pulse.bind(this), this.HOLD_DELAY);
}
},
up: function(inEvent) {
if (this.heldPointer && this.heldPointer.pointerId === inEvent.pointerId) {
this.cancel();
}
},
move: function(inEvent) {
if (this.heldPointer && this.heldPointer.pointerId === inEvent.pointerId) {
var x = inEvent.clientX - this.heldPointer.clientX;
var y = inEvent.clientY - this.heldPointer.clientY;
if ((x * x + y * y) > this.WIGGLE_THRESHOLD) {
this.cancel();
}
}
},
fireHold: function(inType, inHoldTime) {
var p = {
bubbles: true,
cancelable: true,
pointerType: this.heldPointer.pointerType,
pointerId: this.heldPointer.pointerId,
x: this.heldPointer.clientX,
y: this.heldPointer.clientY,
_source: 'hold'
};
if (inHoldTime) {
p.holdTime = inHoldTime;
}
var e = eventFactory.makeGestureEvent(inType, p);
this.target.dispatchEvent(e);
}
};
dispatcher.registerGesture('hold', hold);
})(window.PolymerGestures);
/**
* This event is fired when a pointer quickly goes down and up, and is used to
* denote activation.
*
* Any gesture event can prevent the tap event from being created by calling
* `event.preventTap`.
*
* Any pointer event can prevent the tap by setting the `tapPrevented` property
* on itself.
*
* @module PointerGestures
* @submodule Events
* @class tap
*/
/**
* X axis position of the tap.
* @property x
* @type Number
*/
/**
* Y axis position of the tap.
* @property y
* @type Number
*/
/**
* Type of the pointer that made the tap.
* @property pointerType
* @type String
*/
(function(scope) {
var dispatcher = scope.dispatcher;
var eventFactory = scope.eventFactory;
var pointermap = new scope.PointerMap();
var tap = {
events: [
'down',
'up'
],
exposes: [
'tap'
],
down: function(inEvent) {
if (inEvent.isPrimary && !inEvent.tapPrevented) {
pointermap.set(inEvent.pointerId, {
target: inEvent.target,
buttons: inEvent.buttons,
x: inEvent.clientX,
y: inEvent.clientY
});
}
},
shouldTap: function(e, downState) {
var tap = true;
if (e.pointerType === 'mouse') {
// only allow left click to tap for mouse
tap = (e.buttons ^ 1) && (downState.buttons & 1);
}
return tap && !e.tapPrevented;
},
up: function(inEvent) {
var start = pointermap.get(inEvent.pointerId);
if (start && this.shouldTap(inEvent, start)) {
// up.relatedTarget is target currently under finger
var t = scope.targetFinding.LCA(start.target, inEvent.relatedTarget);
if (t) {
var e = eventFactory.makeGestureEvent('tap', {
bubbles: true,
cancelable: true,
x: inEvent.clientX,
y: inEvent.clientY,
detail: inEvent.detail,
pointerType: inEvent.pointerType,
pointerId: inEvent.pointerId,
altKey: inEvent.altKey,
ctrlKey: inEvent.ctrlKey,
metaKey: inEvent.metaKey,
shiftKey: inEvent.shiftKey,
_source: 'tap'
});
t.dispatchEvent(e);
}
}
pointermap.delete(inEvent.pointerId);
}
};
// patch eventFactory to remove id from tap's pointermap for preventTap calls
eventFactory.preventTap = function(e) {
return function() {
e.tapPrevented = true;
pointermap.delete(e.pointerId);
};
};
dispatcher.registerGesture('tap', tap);
})(window.PolymerGestures);
/*
* Basic strategy: find the farthest apart points, use as diameter of circle
* react to size change and rotation of the chord
*/
/**
* @module pointer-gestures
* @submodule Events
* @class pinch
*/
/**
* Scale of the pinch zoom gesture
* @property scale
* @type Number
*/
/**
* Center X position of pointers causing pinch
* @property centerX
* @type Number
*/
/**
* Center Y position of pointers causing pinch
* @property centerY
* @type Number
*/
/**
* @module pointer-gestures
* @submodule Events
* @class rotate
*/
/**
* Angle (in degrees) of rotation. Measured from starting positions of pointers.
* @property angle
* @type Number
*/
/**
* Center X position of pointers causing rotation
* @property centerX
* @type Number
*/
/**
* Center Y position of pointers causing rotation
* @property centerY
* @type Number
*/
(function(scope) {
var dispatcher = scope.dispatcher;
var eventFactory = scope.eventFactory;
var pointermap = new scope.PointerMap();
var RAD_TO_DEG = 180 / Math.PI;
var pinch = {
events: [
'down',
'up',
'move',
'cancel'
],
exposes: [
'pinchstart',
'pinch',
'pinchend',
'rotate'
],
defaultActions: {
'pinch': 'none',
'rotate': 'none'
},
reference: {},
down: function(inEvent) {
pointermap.set(inEvent.pointerId, inEvent);
if (pointermap.pointers() == 2) {
var points = this.calcChord();
var angle = this.calcAngle(points);
this.reference = {
angle: angle,
diameter: points.diameter,
target: scope.targetFinding.LCA(points.a.target, points.b.target)
};
this.firePinch('pinchstart', points.diameter, points);
}
},
up: function(inEvent) {
var p = pointermap.get(inEvent.pointerId);
var num = pointermap.pointers();
if (p) {
if (num === 2) {
// fire 'pinchend' before deleting pointer
var points = this.calcChord();
this.firePinch('pinchend', points.diameter, points);
}
pointermap.delete(inEvent.pointerId);
}
},
move: function(inEvent) {
if (pointermap.has(inEvent.pointerId)) {
pointermap.set(inEvent.pointerId, inEvent);
if (pointermap.pointers() > 1) {
this.calcPinchRotate();
}
}
},
cancel: function(inEvent) {
this.up(inEvent);
},
firePinch: function(type, diameter, points) {
var zoom = diameter / this.reference.diameter;
var e = eventFactory.makeGestureEvent(type, {
bubbles: true,
cancelable: true,
scale: zoom,
centerX: points.center.x,
centerY: points.center.y,
_source: 'pinch'
});
this.reference.target.dispatchEvent(e);
},
fireRotate: function(angle, points) {
var diff = Math.round((angle - this.reference.angle) % 360);
var e = eventFactory.makeGestureEvent('rotate', {
bubbles: true,
cancelable: true,
angle: diff,
centerX: points.center.x,
centerY: points.center.y,
_source: 'pinch'
});
this.reference.target.dispatchEvent(e);
},
calcPinchRotate: function() {
var points = this.calcChord();
var diameter = points.diameter;
var angle = this.calcAngle(points);
if (diameter != this.reference.diameter) {
this.firePinch('pinch', diameter, points);
}
if (angle != this.reference.angle) {
this.fireRotate(angle, points);
}
},
calcChord: function() {
var pointers = [];
pointermap.forEach(function(p) {
pointers.push(p);
});
var dist = 0;
// start with at least two pointers
var points = {a: pointers[0], b: pointers[1]};
var x, y, d;
for (var i = 0; i < pointers.length; i++) {
var a = pointers[i];
for (var j = i + 1; j < pointers.length; j++) {
var b = pointers[j];
x = Math.abs(a.clientX - b.clientX);
y = Math.abs(a.clientY - b.clientY);
d = x + y;
if (d > dist) {
dist = d;
points = {a: a, b: b};
}
}
}
x = Math.abs(points.a.clientX + points.b.clientX) / 2;
y = Math.abs(points.a.clientY + points.b.clientY) / 2;
points.center = { x: x, y: y };
points.diameter = dist;
return points;
},
calcAngle: function(points) {
var x = points.a.clientX - points.b.clientX;
var y = points.a.clientY - points.b.clientY;
return (360 + Math.atan2(y, x) * RAD_TO_DEG) % 360;
}
};
dispatcher.registerGesture('pinch', pinch);
})(window.PolymerGestures);
(function (global) {
'use strict';
var Token,
TokenName,
Syntax,
Messages,
source,
index,
length,
delegate,
lookahead,
state;
Token = {
BooleanLiteral: 1,
EOF: 2,
Identifier: 3,
Keyword: 4,
NullLiteral: 5,
NumericLiteral: 6,
Punctuator: 7,
StringLiteral: 8
};
TokenName = {};
TokenName[Token.BooleanLiteral] = 'Boolean';
TokenName[Token.EOF] = '<end>';
TokenName[Token.Identifier] = 'Identifier';
TokenName[Token.Keyword] = 'Keyword';
TokenName[Token.NullLiteral] = 'Null';
TokenName[Token.NumericLiteral] = 'Numeric';
TokenName[Token.Punctuator] = 'Punctuator';
TokenName[Token.StringLiteral] = 'String';
Syntax = {
ArrayExpression: 'ArrayExpression',
BinaryExpression: 'BinaryExpression',
CallExpression: 'CallExpression',
ConditionalExpression: 'ConditionalExpression',
EmptyStatement: 'EmptyStatement',
ExpressionStatement: 'ExpressionStatement',
Identifier: 'Identifier',
Literal: 'Literal',
LabeledStatement: 'LabeledStatement',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
ObjectExpression: 'ObjectExpression',
Program: 'Program',
Property: 'Property',
ThisExpression: 'ThisExpression',
UnaryExpression: 'UnaryExpression'
};
// Error messages should be identical to V8.
Messages = {
UnexpectedToken: 'Unexpected token %0',
UnknownLabel: 'Undefined label \'%0\'',
Redeclaration: '%0 \'%1\' has already been declared'
};
// Ensure the condition is true, otherwise throw an error.
// This is only to have a better contract semantic, i.e. another safety net
// to catch a logic error. The condition shall be fulfilled in normal case.
// Do NOT use this to enforce a certain condition on any user input.
function assert(condition, message) {
if (!condition) {
throw new Error('ASSERT: ' + message);
}
}
function isDecimalDigit(ch) {
return (ch >= 48 && ch <= 57); // 0..9
}
// 7.2 White Space
function isWhiteSpace(ch) {
return (ch === 32) || // space
(ch === 9) || // tab
(ch === 0xB) ||
(ch === 0xC) ||
(ch === 0xA0) ||
(ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0);
}
// 7.3 Line Terminators
function isLineTerminator(ch) {
return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029);
}
// 7.6 Identifier Names and Identifiers
function isIdentifierStart(ch) {
return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
(ch >= 65 && ch <= 90) || // A..Z
(ch >= 97 && ch <= 122); // a..z
}
function isIdentifierPart(ch) {
return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
(ch >= 65 && ch <= 90) || // A..Z
(ch >= 97 && ch <= 122) || // a..z
(ch >= 48 && ch <= 57); // 0..9
}
// 7.6.1.1 Keywords
function isKeyword(id) {
return (id === 'this')
}
// 7.4 Comments
function skipWhitespace() {
while (index < length && isWhiteSpace(source.charCodeAt(index))) {
++index;
}
}
function getIdentifier() {
var start, ch;
start = index++;
while (index < length) {
ch = source.charCodeAt(index);
if (isIdentifierPart(ch)) {
++index;
} else {
break;
}
}
return source.slice(start, index);
}
function scanIdentifier() {
var start, id, type;
start = index;
id = getIdentifier();
// There is no keyword or literal with only one character.
// Thus, it must be an identifier.
if (id.length === 1) {
type = Token.Identifier;
} else if (isKeyword(id)) {
type = Token.Keyword;
} else if (id === 'null') {
type = Token.NullLiteral;
} else if (id === 'true' || id === 'false') {
type = Token.BooleanLiteral;
} else {
type = Token.Identifier;
}
return {
type: type,
value: id,
range: [start, index]
};
}
// 7.7 Punctuators
function scanPunctuator() {
var start = index,
code = source.charCodeAt(index),
code2,
ch1 = source[index],
ch2;
switch (code) {
// Check for most common single-character punctuators.
case 46: // . dot
case 40: // ( open bracket
case 41: // ) close bracket
case 59: // ; semicolon
case 44: // , comma
case 123: // { open curly brace
case 125: // } close curly brace
case 91: // [
case 93: // ]
case 58: // :
case 63: // ?
++index;
return {
type: Token.Punctuator,
value: String.fromCharCode(code),
range: [start, index]
};
default:
code2 = source.charCodeAt(index + 1);
// '=' (char #61) marks an assignment or comparison operator.
if (code2 === 61) {
switch (code) {
case 37: // %
case 38: // &
case 42: // *:
case 43: // +
case 45: // -
case 47: // /
case 60: // <
case 62: // >
case 124: // |
index += 2;
return {
type: Token.Punctuator,
value: String.fromCharCode(code) + String.fromCharCode(code2),
range: [start, index]
};
case 33: // !
case 61: // =
index += 2;
// !== and ===
if (source.charCodeAt(index) === 61) {
++index;
}
return {
type: Token.Punctuator,
value: source.slice(start, index),
range: [start, index]
};
default:
break;
}
}
break;
}
// Peek more characters.
ch2 = source[index + 1];
// Other 2-character punctuators: && ||
if (ch1 === ch2 && ('&|'.indexOf(ch1) >= 0)) {
index += 2;
return {
type: Token.Punctuator,
value: ch1 + ch2,
range: [start, index]
};
}
if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
++index;
return {
type: Token.Punctuator,
value: ch1,
range: [start, index]
};
}
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// 7.8.3 Numeric Literals
function scanNumericLiteral() {
var number, start, ch;
ch = source[index];
assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
'Numeric literal must start with a decimal digit or a decimal point');
start = index;
number = '';
if (ch !== '.') {
number = source[index++];
ch = source[index];
// Hex number starts with '0x'.
// Octal number starts with '0'.
if (number === '0') {
// decimal number starts with '0' such as '09' is illegal.
if (ch && isDecimalDigit(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
ch = source[index];
}
if (ch === '.') {
number += source[index++];
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
ch = source[index];
}
if (ch === 'e' || ch === 'E') {
number += source[index++];
ch = source[index];
if (ch === '+' || ch === '-') {
number += source[index++];
}
if (isDecimalDigit(source.charCodeAt(index))) {
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
} else {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
if (isIdentifierStart(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseFloat(number),
range: [start, index]
};
}
// 7.8.4 String Literals
function scanStringLiteral() {
var str = '', quote, start, ch, octal = false;
quote = source[index];
assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = index;
++index;
while (index < length) {
ch = source[index++];
if (ch === quote) {
quote = '';
break;
} else if (ch === '\\') {
ch = source[index++];
if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
str += '\n';
break;
case 'r':
str += '\r';
break;
case 't':
str += '\t';
break;
case 'b':
str += '\b';
break;
case 'f':
str += '\f';
break;
case 'v':
str += '\x0B';
break;
default:
str += ch;
break;
}
} else {
if (ch === '\r' && source[index] === '\n') {
++index;
}
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
break;
} else {
str += ch;
}
}
if (quote !== '') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.StringLiteral,
value: str,
octal: octal,
range: [start, index]
};
}
function isIdentifierName(token) {
return token.type === Token.Identifier ||
token.type === Token.Keyword ||
token.type === Token.BooleanLiteral ||
token.type === Token.NullLiteral;
}
function advance() {
var ch;
skipWhitespace();
if (index >= length) {
return {
type: Token.EOF,
range: [index, index]
};
}
ch = source.charCodeAt(index);
// Very common: ( and ) and ;
if (ch === 40 || ch === 41 || ch === 58) {
return scanPunctuator();
}
// String literal starts with single quote (#39) or double quote (#34).
if (ch === 39 || ch === 34) {
return scanStringLiteral();
}
if (isIdentifierStart(ch)) {
return scanIdentifier();
}
// Dot (.) char #46 can also start a floating-point number, hence the need
// to check the next character.
if (ch === 46) {
if (isDecimalDigit(source.charCodeAt(index + 1))) {
return scanNumericLiteral();
}
return scanPunctuator();
}
if (isDecimalDigit(ch)) {
return scanNumericLiteral();
}
return scanPunctuator();
}
function lex() {
var token;
token = lookahead;
index = token.range[1];
lookahead = advance();
index = token.range[1];
return token;
}
function peek() {
var pos;
pos = index;
lookahead = advance();
index = pos;
}
// Throw an exception
function throwError(token, messageFormat) {
var error,
args = Array.prototype.slice.call(arguments, 2),
msg = messageFormat.replace(
/%(\d)/g,
function (whole, index) {
assert(index < args.length, 'Message reference must be in range');
return args[index];
}
);
error = new Error(msg);
error.index = index;
error.description = msg;
throw error;
}
// Throw an exception because of the token.
function throwUnexpected(token) {
throwError(token, Messages.UnexpectedToken, token.value);
}
// Expect the next token to match the specified punctuator.
// If not, an exception will be thrown.
function expect(value) {
var token = lex();
if (token.type !== Token.Punctuator || token.value !== value) {
throwUnexpected(token);
}
}
// Return true if the next token matches the specified punctuator.
function match(value) {
return lookahead.type === Token.Punctuator && lookahead.value === value;
}
// Return true if the next token matches the specified keyword
function matchKeyword(keyword) {
return lookahead.type === Token.Keyword && lookahead.value === keyword;
}
function consumeSemicolon() {
// Catch the very common case first: immediately a semicolon (char #59).
if (source.charCodeAt(index) === 59) {
lex();
return;
}
skipWhitespace();
if (match(';')) {
lex();
return;
}
if (lookahead.type !== Token.EOF && !match('}')) {
throwUnexpected(lookahead);
}
}
// 11.1.4 Array Initialiser
function parseArrayInitialiser() {
var elements = [];
expect('[');
while (!match(']')) {
if (match(',')) {
lex();
elements.push(null);
} else {
elements.push(parseExpression());
if (!match(']')) {
expect(',');
}
}
}
expect(']');
return delegate.createArrayExpression(elements);
}
// 11.1.5 Object Initialiser
function parseObjectPropertyKey() {
var token;
skipWhitespace();
token = lex();
// Note: This function is called only from parseObjectProperty(), where
// EOF and Punctuator tokens are already filtered out.
if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
return delegate.createLiteral(token);
}
return delegate.createIdentifier(token.value);
}
function parseObjectProperty() {
var token, key;
token = lookahead;
skipWhitespace();
if (token.type === Token.EOF || token.type === Token.Punctuator) {
throwUnexpected(token);
}
key = parseObjectPropertyKey();
expect(':');
return delegate.createProperty('init', key, parseExpression());
}
function parseObjectInitialiser() {
var properties = [];
expect('{');
while (!match('}')) {
properties.push(parseObjectProperty());
if (!match('}')) {
expect(',');
}
}
expect('}');
return delegate.createObjectExpression(properties);
}
// 11.1.6 The Grouping Operator
function parseGroupExpression() {
var expr;
expect('(');
expr = parseExpression();
expect(')');
return expr;
}
// 11.1 Primary Expressions
function parsePrimaryExpression() {
var type, token, expr;
if (match('(')) {
return parseGroupExpression();
}
type = lookahead.type;
if (type === Token.Identifier) {
expr = delegate.createIdentifier(lex().value);
} else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
expr = delegate.createLiteral(lex());
} else if (type === Token.Keyword) {
if (matchKeyword('this')) {
lex();
expr = delegate.createThisExpression();
}
} else if (type === Token.BooleanLiteral) {
token = lex();
token.value = (token.value === 'true');
expr = delegate.createLiteral(token);
} else if (type === Token.NullLiteral) {
token = lex();
token.value = null;
expr = delegate.createLiteral(token);
} else if (match('[')) {
expr = parseArrayInitialiser();
} else if (match('{')) {
expr = parseObjectInitialiser();
}
if (expr) {
return expr;
}
throwUnexpected(lex());
}
// 11.2 Left-Hand-Side Expressions
function parseArguments() {
var args = [];
expect('(');
if (!match(')')) {
while (index < length) {
args.push(parseExpression());
if (match(')')) {
break;
}
expect(',');
}
}
expect(')');
return args;
}
function parseNonComputedProperty() {
var token;
token = lex();
if (!isIdentifierName(token)) {
throwUnexpected(token);
}
return delegate.createIdentifier(token.value);
}
function parseNonComputedMember() {
expect('.');
return parseNonComputedProperty();
}
function parseComputedMember() {
var expr;
expect('[');
expr = parseExpression();
expect(']');
return expr;
}
function parseLeftHandSideExpression() {
var expr, args, property;
expr = parsePrimaryExpression();
while (true) {
if (match('[')) {
property = parseComputedMember();
expr = delegate.createMemberExpression('[', expr, property);
} else if (match('.')) {
property = parseNonComputedMember();
expr = delegate.createMemberExpression('.', expr, property);
} else if (match('(')) {
args = parseArguments();
expr = delegate.createCallExpression(expr, args);
} else {
break;
}
}
return expr;
}
// 11.3 Postfix Expressions
var parsePostfixExpression = parseLeftHandSideExpression;
// 11.4 Unary Operators
function parseUnaryExpression() {
var token, expr;
if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
expr = parsePostfixExpression();
} else if (match('+') || match('-') || match('!')) {
token = lex();
expr = parseUnaryExpression();
expr = delegate.createUnaryExpression(token.value, expr);
} else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
throwError({}, Messages.UnexpectedToken);
} else {
expr = parsePostfixExpression();
}
return expr;
}
function binaryPrecedence(token) {
var prec = 0;
if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
return 0;
}
switch (token.value) {
case '||':
prec = 1;
break;
case '&&':
prec = 2;
break;
case '==':
case '!=':
case '===':
case '!==':
prec = 6;
break;
case '<':
case '>':
case '<=':
case '>=':
case 'instanceof':
prec = 7;
break;
case 'in':
prec = 7;
break;
case '+':
case '-':
prec = 9;
break;
case '*':
case '/':
case '%':
prec = 11;
break;
default:
break;
}
return prec;
}
// 11.5 Multiplicative Operators
// 11.6 Additive Operators
// 11.7 Bitwise Shift Operators
// 11.8 Relational Operators
// 11.9 Equality Operators
// 11.10 Binary Bitwise Operators
// 11.11 Binary Logical Operators
function parseBinaryExpression() {
var expr, token, prec, stack, right, operator, left, i;
left = parseUnaryExpression();
token = lookahead;
prec = binaryPrecedence(token);
if (prec === 0) {
return left;
}
token.prec = prec;
lex();
right = parseUnaryExpression();
stack = [left, token, right];
while ((prec = binaryPrecedence(lookahead)) > 0) {
// Reduce: make a binary expression from the three topmost entries.
while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
right = stack.pop();
operator = stack.pop().value;
left = stack.pop();
expr = delegate.createBinaryExpression(operator, left, right);
stack.push(expr);
}
// Shift.
token = lex();
token.prec = prec;
stack.push(token);
expr = parseUnaryExpression();
stack.push(expr);
}
// Final reduce to clean-up the stack.
i = stack.length - 1;
expr = stack[i];
while (i > 1) {
expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
i -= 2;
}
return expr;
}
// 11.12 Conditional Operator
function parseConditionalExpression() {
var expr, consequent, alternate;
expr = parseBinaryExpression();
if (match('?')) {
lex();
consequent = parseConditionalExpression();
expect(':');
alternate = parseConditionalExpression();
expr = delegate.createConditionalExpression(expr, consequent, alternate);
}
return expr;
}
// Simplification since we do not support AssignmentExpression.
var parseExpression = parseConditionalExpression;
// Polymer Syntax extensions
// Filter ::
// Identifier
// Identifier "(" ")"
// Identifier "(" FilterArguments ")"
function parseFilter() {
var identifier, args;
identifier = lex();
if (identifier.type !== Token.Identifier) {
throwUnexpected(identifier);
}
args = match('(') ? parseArguments() : [];
return delegate.createFilter(identifier.value, args);
}
// Filters ::
// "|" Filter
// Filters "|" Filter
function parseFilters() {
while (match('|')) {
lex();
parseFilter();
}
}
// TopLevel ::
// LabelledExpressions
// AsExpression
// InExpression
// FilterExpression
// AsExpression ::
// FilterExpression as Identifier
// InExpression ::
// Identifier, Identifier in FilterExpression
// Identifier in FilterExpression
// FilterExpression ::
// Expression
// Expression Filters
function parseTopLevel() {
skipWhitespace();
peek();
var expr = parseExpression();
if (expr) {
if (lookahead.value === ',' || lookahead.value == 'in' &&
expr.type === Syntax.Identifier) {
parseInExpression(expr);
} else {
parseFilters();
if (lookahead.value === 'as') {
parseAsExpression(expr);
} else {
delegate.createTopLevel(expr);
}
}
}
if (lookahead.type !== Token.EOF) {
throwUnexpected(lookahead);
}
}
function parseAsExpression(expr) {
lex(); // as
var identifier = lex().value;
delegate.createAsExpression(expr, identifier);
}
function parseInExpression(identifier) {
var indexName;
if (lookahead.value === ',') {
lex();
if (lookahead.type !== Token.Identifier)
throwUnexpected(lookahead);
indexName = lex().value;
}
lex(); // in
var expr = parseExpression();
parseFilters();
delegate.createInExpression(identifier.name, indexName, expr);
}
function parse(code, inDelegate) {
delegate = inDelegate;
source = code;
index = 0;
length = source.length;
lookahead = null;
state = {
labelSet: {}
};
return parseTopLevel();
}
global.esprima = {
parse: parse
};
})(this);
// 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
(function (global) {
'use strict';
function prepareBinding(expressionText, name, node, filterRegistry) {
var expression;
try {
expression = getExpression(expressionText);
if (expression.scopeIdent &&
(node.nodeType !== Node.ELEMENT_NODE ||
node.tagName !== 'TEMPLATE' ||
(name !== 'bind' && name !== 'repeat'))) {
throw Error('as and in can only be used within <template bind/repeat>');
}
} catch (ex) {
console.error('Invalid expression syntax: ' + expressionText, ex);
return;
}
return function(model, node, oneTime) {
var binding = expression.getBinding(model, filterRegistry, oneTime);
if (expression.scopeIdent && binding) {
node.polymerExpressionScopeIdent_ = expression.scopeIdent;
if (expression.indexIdent)
node.polymerExpressionIndexIdent_ = expression.indexIdent;
}
return binding;
}
}
// TODO(rafaelw): Implement simple LRU.
var expressionParseCache = Object.create(null);
function getExpression(expressionText) {
var expression = expressionParseCache[expressionText];
if (!expression) {
var delegate = new ASTDelegate();
esprima.parse(expressionText, delegate);
expression = new Expression(delegate);
expressionParseCache[expressionText] = expression;
}
return expression;
}
function Literal(value) {
this.value = value;
this.valueFn_ = undefined;
}
Literal.prototype = {
valueFn: function() {
if (!this.valueFn_) {
var value = this.value;
this.valueFn_ = function() {
return value;
}
}
return this.valueFn_;
}
}
function IdentPath(name) {
this.name = name;
this.path = Path.get(name);
}
IdentPath.prototype = {
valueFn: function() {
if (!this.valueFn_) {
var name = this.name;
var path = this.path;
this.valueFn_ = function(model, observer) {
if (observer)
observer.addPath(model, path);
return path.getValueFrom(model);
}
}
return this.valueFn_;
},
setValue: function(model, newValue) {
if (this.path.length == 1)
model = findScope(model, this.path[0]);
return this.path.setValueFrom(model, newValue);
}
};
function MemberExpression(object, property, accessor) {
this.computed = accessor == '[';
this.dynamicDeps = typeof object == 'function' ||
object.dynamicDeps ||
(this.computed && !(property instanceof Literal));
this.simplePath =
!this.dynamicDeps &&
(property instanceof IdentPath || property instanceof Literal) &&
(object instanceof MemberExpression || object instanceof IdentPath);
this.object = this.simplePath ? object : getFn(object);
this.property = !this.computed || this.simplePath ?
property : getFn(property);
}
MemberExpression.prototype = {
get fullPath() {
if (!this.fullPath_) {
var parts = this.object instanceof MemberExpression ?
this.object.fullPath.slice() : [this.object.name];
parts.push(this.property instanceof IdentPath ?
this.property.name : this.property.value);
this.fullPath_ = Path.get(parts);
}
return this.fullPath_;
},
valueFn: function() {
if (!this.valueFn_) {
var object = this.object;
if (this.simplePath) {
var path = this.fullPath;
this.valueFn_ = function(model, observer) {
if (observer)
observer.addPath(model, path);
return path.getValueFrom(model);
};
} else if (!this.computed) {
var path = Path.get(this.property.name);
this.valueFn_ = function(model, observer, filterRegistry) {
var context = object(model, observer, filterRegistry);
if (observer)
observer.addPath(context, path);
return path.getValueFrom(context);
}
} else {
// Computed property.
var property = this.property;
this.valueFn_ = function(model, observer, filterRegistry) {
var context = object(model, observer, filterRegistry);
var propName = property(model, observer, filterRegistry);
if (observer)
observer.addPath(context, [propName]);
return context ? context[propName] : undefined;
};
}
}
return this.valueFn_;
},
setValue: function(model, newValue) {
if (this.simplePath) {
this.fullPath.setValueFrom(model, newValue);
return newValue;
}
var object = this.object(model);
var propName = this.property instanceof IdentPath ? this.property.name :
this.property(model);
return object[propName] = newValue;
}
};
function Filter(name, args) {
this.name = name;
this.args = [];
for (var i = 0; i < args.length; i++) {
this.args[i] = getFn(args[i]);
}
}
Filter.prototype = {
transform: function(model, observer, filterRegistry, toModelDirection,
initialArgs) {
var fn = filterRegistry[this.name];
var context = model;
if (fn) {
context = undefined;
} else {
fn = context[this.name];
if (!fn) {
console.error('Cannot find function or filter: ' + this.name);
return;
}
}
// If toModelDirection is falsey, then the "normal" (dom-bound) direction
// is used. Otherwise, it looks for a 'toModel' property function on the
// object.
if (toModelDirection) {
fn = fn.toModel;
} else if (typeof fn.toDOM == 'function') {
fn = fn.toDOM;
}
if (typeof fn != 'function') {
console.error('Cannot find function or filter: ' + this.name);
return;
}
var args = initialArgs || [];
for (var i = 0; i < this.args.length; i++) {
args.push(getFn(this.args[i])(model, observer, filterRegistry));
}
return fn.apply(context, args);
}
};
function notImplemented() { throw Error('Not Implemented'); }
var unaryOperators = {
'+': function(v) { return +v; },
'-': function(v) { return -v; },
'!': function(v) { return !v; }
};
var binaryOperators = {
'+': function(l, r) { return l+r; },
'-': function(l, r) { return l-r; },
'*': function(l, r) { return l*r; },
'/': function(l, r) { return l/r; },
'%': function(l, r) { return l%r; },
'<': function(l, r) { return l<r; },
'>': function(l, r) { return l>r; },
'<=': function(l, r) { return l<=r; },
'>=': function(l, r) { return l>=r; },
'==': function(l, r) { return l==r; },
'!=': function(l, r) { return l!=r; },
'===': function(l, r) { return l===r; },
'!==': function(l, r) { return l!==r; },
'&&': function(l, r) { return l&&r; },
'||': function(l, r) { return l||r; },
};
function getFn(arg) {
return typeof arg == 'function' ? arg : arg.valueFn();
}
function ASTDelegate() {
this.expression = null;
this.filters = [];
this.deps = {};
this.currentPath = undefined;
this.scopeIdent = undefined;
this.indexIdent = undefined;
this.dynamicDeps = false;
}
ASTDelegate.prototype = {
createUnaryExpression: function(op, argument) {
if (!unaryOperators[op])
throw Error('Disallowed operator: ' + op);
argument = getFn(argument);
return function(model, observer, filterRegistry) {
return unaryOperators[op](argument(model, observer, filterRegistry));
};
},
createBinaryExpression: function(op, left, right) {
if (!binaryOperators[op])
throw Error('Disallowed operator: ' + op);
left = getFn(left);
right = getFn(right);
switch (op) {
case '||':
this.dynamicDeps = true;
return function(model, observer, filterRegistry) {
return left(model, observer, filterRegistry) ||
right(model, observer, filterRegistry);
};
case '&&':
this.dynamicDeps = true;
return function(model, observer, filterRegistry) {
return left(model, observer, filterRegistry) &&
right(model, observer, filterRegistry);
};
}
return function(model, observer, filterRegistry) {
return binaryOperators[op](left(model, observer, filterRegistry),
right(model, observer, filterRegistry));
};
},
createConditionalExpression: function(test, consequent, alternate) {
test = getFn(test);
consequent = getFn(consequent);
alternate = getFn(alternate);
this.dynamicDeps = true;
return function(model, observer, filterRegistry) {
return test(model, observer, filterRegistry) ?
consequent(model, observer, filterRegistry) :
alternate(model, observer, filterRegistry);
}
},
createIdentifier: function(name) {
var ident = new IdentPath(name);
ident.type = 'Identifier';
return ident;
},
createMemberExpression: function(accessor, object, property) {
var ex = new MemberExpression(object, property, accessor);
if (ex.dynamicDeps)
this.dynamicDeps = true;
return ex;
},
createCallExpression: function(expression, args) {
if (!(expression instanceof IdentPath))
throw Error('Only identifier function invocations are allowed');
var filter = new Filter(expression.name, args);
return function(model, observer, filterRegistry) {
return filter.transform(model, observer, filterRegistry, false);
};
},
createLiteral: function(token) {
return new Literal(token.value);
},
createArrayExpression: function(elements) {
for (var i = 0; i < elements.length; i++)
elements[i] = getFn(elements[i]);
return function(model, observer, filterRegistry) {
var arr = []
for (var i = 0; i < elements.length; i++)
arr.push(elements[i](model, observer, filterRegistry));
return arr;
}
},
createProperty: function(kind, key, value) {
return {
key: key instanceof IdentPath ? key.name : key.value,
value: value
};
},
createObjectExpression: function(properties) {
for (var i = 0; i < properties.length; i++)
properties[i].value = getFn(properties[i].value);
return function(model, observer, filterRegistry) {
var obj = {};
for (var i = 0; i < properties.length; i++)
obj[properties[i].key] =
properties[i].value(model, observer, filterRegistry);
return obj;
}
},
createFilter: function(name, args) {
this.filters.push(new Filter(name, args));
},
createAsExpression: function(expression, scopeIdent) {
this.expression = expression;
this.scopeIdent = scopeIdent;
},
createInExpression: function(scopeIdent, indexIdent, expression) {
this.expression = expression;
this.scopeIdent = scopeIdent;
this.indexIdent = indexIdent;
},
createTopLevel: function(expression) {
this.expression = expression;
},
createThisExpression: notImplemented
}
function ConstantObservable(value) {
this.value_ = value;
}
ConstantObservable.prototype = {
open: function() { return this.value_; },
discardChanges: function() { return this.value_; },
deliver: function() {},
close: function() {},
}
function Expression(delegate) {
this.scopeIdent = delegate.scopeIdent;
this.indexIdent = delegate.indexIdent;
if (!delegate.expression)
throw Error('No expression found.');
this.expression = delegate.expression;
getFn(this.expression); // forces enumeration of path dependencies
this.filters = delegate.filters;
this.dynamicDeps = delegate.dynamicDeps;
}
Expression.prototype = {
getBinding: function(model, filterRegistry, oneTime) {
if (oneTime)
return this.getValue(model, undefined, filterRegistry);
var observer = new CompoundObserver();
// captures deps.
var firstValue = this.getValue(model, observer, filterRegistry);
var firstTime = true;
var self = this;
function valueFn() {
// deps cannot have changed on first value retrieval.
if (firstTime) {
firstTime = false;
return firstValue;
}
if (self.dynamicDeps)
observer.startReset();
var value = self.getValue(model,
self.dynamicDeps ? observer : undefined,
filterRegistry);
if (self.dynamicDeps)
observer.finishReset();
return value;
}
function setValueFn(newValue) {
self.setValue(model, newValue, filterRegistry);
return newValue;
}
return new ObserverTransform(observer, valueFn, setValueFn, true);
},
getValue: function(model, observer, filterRegistry) {
var value = getFn(this.expression)(model, observer, filterRegistry);
for (var i = 0; i < this.filters.length; i++) {
value = this.filters[i].transform(model, observer, filterRegistry,
false, [value]);
}
return value;
},
setValue: function(model, newValue, filterRegistry) {
var count = this.filters ? this.filters.length : 0;
while (count-- > 0) {
newValue = this.filters[count].transform(model, undefined,
filterRegistry, true, [newValue]);
}
if (this.expression.setValue)
return this.expression.setValue(model, newValue);
}
}
/**
* Converts a style property name to a css property name. For example:
* "WebkitUserSelect" to "-webkit-user-select"
*/
function convertStylePropertyName(name) {
return String(name).replace(/[A-Z]/g, function(c) {
return '-' + c.toLowerCase();
});
}
var parentScopeName = '@' + Math.random().toString(36).slice(2);
// Single ident paths must bind directly to the appropriate scope object.
// I.e. Pushed values in two-bindings need to be assigned to the actual model
// object.
function findScope(model, prop) {
while (model[parentScopeName] &&
!Object.prototype.hasOwnProperty.call(model, prop)) {
model = model[parentScopeName];
}
return model;
}
function isLiteralExpression(pathString) {
switch (pathString) {
case '':
return false;
case 'false':
case 'null':
case 'true':
return true;
}
if (!isNaN(Number(pathString)))
return true;
return false;
};
function PolymerExpressions() {}
PolymerExpressions.prototype = {
// "built-in" filters
styleObject: function(value) {
var parts = [];
for (var key in value) {
parts.push(convertStylePropertyName(key) + ': ' + value[key]);
}
return parts.join('; ');
},
tokenList: function(value) {
var tokens = [];
for (var key in value) {
if (value[key])
tokens.push(key);
}
return tokens.join(' ');
},
// binding delegate API
prepareInstancePositionChanged: function(template) {
var indexIdent = template.polymerExpressionIndexIdent_;
if (!indexIdent)
return;
return function(templateInstance, index) {
templateInstance.model[indexIdent] = index;
};
},
prepareBinding: function(pathString, name, node) {
var path = Path.get(pathString);
if (!isLiteralExpression(pathString) && path.valid) {
if (path.length == 1) {
return function(model, node, oneTime) {
if (oneTime)
return path.getValueFrom(model);
var scope = findScope(model, path[0]);
return new PathObserver(scope, path);
};
}
return; // bail out early if pathString is simple path.
}
return prepareBinding(pathString, name, node, this);
},
prepareInstanceModel: function(template) {
var scopeName = template.polymerExpressionScopeIdent_;
if (!scopeName)
return;
var parentScope = template.templateInstance ?
template.templateInstance.model :
template.model;
var indexName = template.polymerExpressionIndexIdent_;
return function(model) {
return createScopeObject(parentScope, model, scopeName, indexName);
};
}
};
var createScopeObject = ('__proto__' in {}) ?
function(parentScope, model, scopeName, indexName) {
var scope = {};
scope[scopeName] = model;
scope[indexName] = undefined;
scope[parentScopeName] = parentScope;
scope.__proto__ = parentScope;
return scope;
} :
function(parentScope, model, scopeName, indexName) {
var scope = Object.create(parentScope);
Object.defineProperty(scope, scopeName,
{ value: model, configurable: true, writable: true });
Object.defineProperty(scope, indexName,
{ value: undefined, configurable: true, writable: true });
Object.defineProperty(scope, parentScopeName,
{ value: parentScope, configurable: true, writable: true });
return scope;
};
global.PolymerExpressions = PolymerExpressions;
PolymerExpressions.getExpression = getExpression;
})(this);
Polymer = {
version: '0.5.3'
};
// TODO(sorvell): this ensures Polymer is an object and not a function
// Platform is currently defining it as a function to allow for async loading
// of polymer; once we refine the loading process this likely goes away.
if (typeof window.Polymer === 'function') {
Polymer = {};
}
(function(scope) {
function withDependencies(task, depends) {
depends = depends || [];
if (!depends.map) {
depends = [depends];
}
return task.apply(this, depends.map(marshal));
}
function module(name, dependsOrFactory, moduleFactory) {
var module;
switch (arguments.length) {
case 0:
return;
case 1:
module = null;
break;
case 2:
// dependsOrFactory is `factory` in this case
module = dependsOrFactory.apply(this);
break;
default:
// dependsOrFactory is `depends` in this case
module = withDependencies(moduleFactory, dependsOrFactory);
break;
}
modules[name] = module;
};
function marshal(name) {
return modules[name];
}
var modules = {};
function using(depends, task) {
HTMLImports.whenImportsReady(function() {
withDependencies(task, depends);
});
};
// exports
scope.marshal = marshal;
// `module` confuses commonjs detectors
scope.modularize = module;
scope.using = using;
})(window);
/*
Build only script.
Ensures scripts needed for basic x-platform compatibility
will be run when platform.js is not loaded.
*/
if (!window.WebComponents) {
/*
On supported platforms, platform.js is not needed. To retain compatibility
with the polyfills, we stub out minimal functionality.
*/
if (!window.WebComponents) {
WebComponents = {
flush: function() {},
flags: {log: {}}
};
Platform = WebComponents;
CustomElements = {
useNative: true,
ready: true,
takeRecords: function() {},
instanceof: function(obj, base) {
return obj instanceof base;
}
};
HTMLImports = {
useNative: true
};
addEventListener('HTMLImportsLoaded', function() {
document.dispatchEvent(
new CustomEvent('WebComponentsReady', {bubbles: true})
);
});
// ShadowDOM
ShadowDOMPolyfill = null;
wrap = unwrap = function(n){
return n;
};
}
/*
Create polyfill scope and feature detect native support.
*/
window.HTMLImports = window.HTMLImports || {flags:{}};
(function(scope) {
/**
Basic setup and simple module executer. We collect modules and then execute
the code later, only if it's necessary for polyfilling.
*/
var IMPORT_LINK_TYPE = 'import';
var useNative = Boolean(IMPORT_LINK_TYPE in document.createElement('link'));
/**
Support `currentScript` on all browsers as `document._currentScript.`
NOTE: We cannot polyfill `document.currentScript` because it's not possible
both to override and maintain the ability to capture the native value.
Therefore we choose to expose `_currentScript` both when native imports
and the polyfill are in use.
*/
// NOTE: ShadowDOMPolyfill intrusion.
var hasShadowDOMPolyfill = Boolean(window.ShadowDOMPolyfill);
var wrap = function(node) {
return hasShadowDOMPolyfill ? ShadowDOMPolyfill.wrapIfNeeded(node) : node;
};
var rootDocument = wrap(document);
var currentScriptDescriptor = {
get: function() {
var script = HTMLImports.currentScript || document.currentScript ||
// NOTE: only works when called in synchronously executing code.
// readyState should check if `loading` but IE10 is
// interactive when scripts run so we cheat.
(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);
/**
Add support for the `HTMLImportsLoaded` event and the `HTMLImports.whenReady`
method. This api is necessary because unlike the native implementation,
script elements do not force imports to resolve. Instead, users should wrap
code in either an `HTMLImportsLoaded` hander or after load time in an
`HTMLImports.whenReady(callback)` call.
NOTE: This module also supports these apis under the native implementation.
Therefore, if this file is loaded, the same code can be used under both
the polyfill and native implementation.
*/
var isIE = /Trident/.test(navigator.userAgent);
// call a callback when all HTMLImports in the document at call time
// (or at least document ready) have loaded.
// 1. ensure the document is in a ready state (has dom), then
// 2. watch for loading of imports and call callback when done
function whenReady(callback, doc) {
doc = doc || rootDocument;
// if document is loading, wait and try again
whenDocumentReady(function() {
watchImportsLoad(callback, doc);
}, doc);
}
// call the callback when the document is in a ready state (has dom)
var requiredReadyState = isIE ? 'complete' : 'interactive';
var READY_EVENT = 'readystatechange';
function isDocumentReady(doc) {
return (doc.readyState === 'complete' ||
doc.readyState === requiredReadyState);
}
// call <callback> when we ensure the document is in a ready state
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;
}
// call <callback> when we ensure all imports have loaded
function watchImportsLoad(callback, doc) {
var imports = doc.querySelectorAll('link[rel=import]');
var loaded = 0, l = imports.length;
function checkDone(d) {
if ((loaded == l) && callback) {
callback();
}
}
function loadedImport(e) {
markTargetLoaded(e);
loaded++;
checkDone();
}
if (l) {
for (var i=0, imp; (i<l) && (imp=imports[i]); i++) {
if (isImportLoaded(imp)) {
loadedImport.call(imp, {target: imp});
} else {
imp.addEventListener('load', loadedImport);
imp.addEventListener('error', loadedImport);
}
}
} else {
checkDone();
}
}
// NOTE: test for native imports loading is based on explicitly watching
// all imports (see below).
// However, we cannot rely on this entirely without watching the entire document
// for import links. For perf reasons, currently only head is watched.
// Instead, we fallback to checking if the import property is available
// and the document is not itself loading.
function isImportLoaded(link) {
return useNative ? link.__loaded ||
(link.import && link.import.readyState !== 'loading') :
link.__importParsed;
}
// TODO(sorvell): Workaround for
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=25007, should be removed when
// this bug is addressed.
// (1) Install a mutation observer to see when HTMLImports have loaded
// (2) if this script is run during document load it will watch any existing
// imports for loading.
//
// NOTE: The workaround has restricted functionality: (1) it's only compatible
// with imports that are added to document.head since the mutation observer
// watches only head for perf reasons, (2) it requires this script
// to run before any imports have completed loading.
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);
}
}
// make sure to catch any imports that are in the process of loading
// when this script is run.
(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);
}
}
})();
}
// Fire the 'HTMLImportsLoaded' event when imports in document at load time
// have loaded. This event is required to simulate the script blocking
// behavior of native imports. A main document script that needs to be sure
// imports have loaded should wait for this event.
whenReady(function() {
HTMLImports.ready = true;
HTMLImports.readyTime = new Date().getTime();
rootDocument.dispatchEvent(
new CustomEvent('HTMLImportsLoaded', {bubbles: true})
);
});
// exports
scope.IMPORT_LINK_TYPE = IMPORT_LINK_TYPE;
scope.useNative = useNative;
scope.rootDocument = rootDocument;
scope.whenReady = whenReady;
scope.isIE = isIE;
})(HTMLImports);
(function(scope) {
// TODO(sorvell): It's desireable to provide a default stylesheet
// that's convenient for styling unresolved elements, but
// it's cumbersome to have to include this manually in every page.
// It would make sense to put inside some HTMLImport but
// the HTMLImports polyfill does not allow loading of stylesheets
// that block rendering. Therefore this injection is tolerated here.
var style = document.createElement('style');
style.textContent = ''
+ 'body {'
+ 'transition: opacity ease-in 0.2s;'
+ ' } \n'
+ 'body[unresolved] {'
+ 'opacity: 0; display: block; overflow: hidden;'
+ ' } \n'
;
var head = document.querySelector('head');
head.insertBefore(style, head.firstChild);
})(Platform);
/*
Build only script.
Ensures scripts needed for basic x-platform compatibility
will be run when platform.js is not loaded.
*/
}
(function(global) {
'use strict';
var testingExposeCycleCount = global.testingExposeCycleCount;
// Detect and do basic sanity checking on Object/Array.observe.
function detectObjectObserve() {
if (typeof Object.observe !== 'function' ||
typeof Array.observe !== 'function') {
return false;
}
var records = [];
function callback(recs) {
records = recs;
}
var test = {};
var arr = [];
Object.observe(test, callback);
Array.observe(arr, callback);
test.id = 1;
test.id = 2;
delete test.id;
arr.push(1, 2);
arr.length = 0;
Object.deliverChangeRecords(callback);
if (records.length !== 5)
return false;
if (records[0].type != 'add' ||
records[1].type != 'update' ||
records[2].type != 'delete' ||
records[3].type != 'splice' ||
records[4].type != 'splice') {
return false;
}
Object.unobserve(test, callback);
Array.unobserve(arr, callback);
return true;
}
var hasObserve = detectObjectObserve();
function detectEval() {
// Don't test for eval if we're running in a Chrome App environment.
// We check for APIs set that only exist in a Chrome App context.
if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) {
return false;
}
// Firefox OS Apps do not allow eval. This feature detection is very hacky
// but even if some other platform adds support for this function this code
// will continue to work.
if (typeof navigator != 'undefined' && navigator.getDeviceStorage) {
return false;
}
try {
var f = new Function('', 'return true;');
return f();
} catch (ex) {
return false;
}
}
var hasEval = detectEval();
function isIndex(s) {
return +s === s >>> 0 && s !== '';
}
function toNumber(s) {
return +s;
}
function isObject(obj) {
return obj === Object(obj);
}
var numberIsNaN = global.Number.isNaN || function(value) {
return typeof value === 'number' && global.isNaN(value);
}
function areSameValue(left, right) {
if (left === right)
return left !== 0 || 1 / left === 1 / right;
if (numberIsNaN(left) && numberIsNaN(right))
return true;
return left !== left && right !== right;
}
var createObject = ('__proto__' in {}) ?
function(obj) { return obj; } :
function(obj) {
var proto = obj.__proto__;
if (!proto)
return obj;
var newObject = Object.create(proto);
Object.getOwnPropertyNames(obj).forEach(function(name) {
Object.defineProperty(newObject, name,
Object.getOwnPropertyDescriptor(obj, name));
});
return newObject;
};
var identStart = '[\$_a-zA-Z]';
var identPart = '[\$_a-zA-Z0-9]';
var identRegExp = new RegExp('^' + identStart + '+' + identPart + '*' + '$');
function getPathCharType(char) {
if (char === undefined)
return 'eof';
var code = char.charCodeAt(0);
switch(code) {
case 0x5B: // [
case 0x5D: // ]
case 0x2E: // .
case 0x22: // "
case 0x27: // '
case 0x30: // 0
return char;
case 0x5F: // _
case 0x24: // $
return 'ident';
case 0x20: // Space
case 0x09: // Tab
case 0x0A: // Newline
case 0x0D: // Return
case 0xA0: // No-break space
case 0xFEFF: // Byte Order Mark
case 0x2028: // Line Separator
case 0x2029: // Paragraph Separator
return 'ws';
}
// a-z, A-Z
if ((0x61 <= code && code <= 0x7A) || (0x41 <= code && code <= 0x5A))
return 'ident';
// 1-9
if (0x31 <= code && code <= 0x39)
return 'number';
return 'else';
}
var pathStateMachine = {
'beforePath': {
'ws': ['beforePath'],
'ident': ['inIdent', 'append'],
'[': ['beforeElement'],
'eof': ['afterPath']
},
'inPath': {
'ws': ['inPath'],
'.': ['beforeIdent'],
'[': ['beforeElement'],
'eof': ['afterPath']
},
'beforeIdent': {
'ws': ['beforeIdent'],
'ident': ['inIdent', 'append']
},
'inIdent': {
'ident': ['inIdent', 'append'],
'0': ['inIdent', 'append'],
'number': ['inIdent', 'append'],
'ws': ['inPath', 'push'],
'.': ['beforeIdent', 'push'],
'[': ['beforeElement', 'push'],
'eof': ['afterPath', 'push']
},
'beforeElement': {
'ws': ['beforeElement'],
'0': ['afterZero', 'append'],
'number': ['inIndex', 'append'],
"'": ['inSingleQuote', 'append', ''],
'"': ['inDoubleQuote', 'append', '']
},
'afterZero': {
'ws': ['afterElement', 'push'],
']': ['inPath', 'push']
},
'inIndex': {
'0': ['inIndex', 'append'],
'number': ['inIndex', 'append'],
'ws': ['afterElement'],
']': ['inPath', 'push']
},
'inSingleQuote': {
"'": ['afterElement'],
'eof': ['error'],
'else': ['inSingleQuote', 'append']
},
'inDoubleQuote': {
'"': ['afterElement'],
'eof': ['error'],
'else': ['inDoubleQuote', 'append']
},
'afterElement': {
'ws': ['afterElement'],
']': ['inPath', 'push']
}
}
function noop() {}
function parsePath(path) {
var keys = [];
var index = -1;
var c, newChar, key, type, transition, action, typeMap, mode = 'beforePath';
var actions = {
push: function() {
if (key === undefined)
return;
keys.push(key);
key = undefined;
},
append: function() {
if (key === undefined)
key = newChar
else
key += newChar;
}
};
function maybeUnescapeQuote() {
if (index >= path.length)
return;
var nextChar = path[index + 1];
if ((mode == 'inSingleQuote' && nextChar == "'") ||
(mode == 'inDoubleQuote' && nextChar == '"')) {
index++;
newChar = nextChar;
actions.append();
return true;
}
}
while (mode) {
index++;
c = path[index];
if (c == '\\' && maybeUnescapeQuote(mode))
continue;
type = getPathCharType(c);
typeMap = pathStateMachine[mode];
transition = typeMap[type] || typeMap['else'] || 'error';
if (transition == 'error')
return; // parse error;
mode = transition[0];
action = actions[transition[1]] || noop;
newChar = transition[2] === undefined ? c : transition[2];
action();
if (mode === 'afterPath') {
return keys;
}
}
return; // parse error
}
function isIdent(s) {
return identRegExp.test(s);
}
var constructorIsPrivate = {};
function Path(parts, privateToken) {
if (privateToken !== constructorIsPrivate)
throw Error('Use Path.get to retrieve path objects');
for (var i = 0; i < parts.length; i++) {
this.push(String(parts[i]));
}
if (hasEval && this.length) {
this.getValueFrom = this.compiledGetValueFromFn();
}
}
// TODO(rafaelw): Make simple LRU cache
var pathCache = {};
function getPath(pathString) {
if (pathString instanceof Path)
return pathString;
if (pathString == null || pathString.length == 0)
pathString = '';
if (typeof pathString != 'string') {
if (isIndex(pathString.length)) {
// Constructed with array-like (pre-parsed) keys
return new Path(pathString, constructorIsPrivate);
}
pathString = String(pathString);
}
var path = pathCache[pathString];
if (path)
return path;
var parts = parsePath(pathString);
if (!parts)
return invalidPath;
var path = new Path(parts, constructorIsPrivate);
pathCache[pathString] = path;
return path;
}
Path.get = getPath;
function formatAccessor(key) {
if (isIndex(key)) {
return '[' + key + ']';
} else {
return '["' + key.replace(/"/g, '\\"') + '"]';
}
}
Path.prototype = createObject({
__proto__: [],
valid: true,
toString: function() {
var pathString = '';
for (var i = 0; i < this.length; i++) {
var key = this[i];
if (isIdent(key)) {
pathString += i ? '.' + key : key;
} else {
pathString += formatAccessor(key);
}
}
return pathString;
},
getValueFrom: function(obj, directObserver) {
for (var i = 0; i < this.length; i++) {
if (obj == null)
return;
obj = obj[this[i]];
}
return obj;
},
iterateObjects: function(obj, observe) {
for (var i = 0; i < this.length; i++) {
if (i)
obj = obj[this[i - 1]];
if (!isObject(obj))
return;
observe(obj, this[i]);
}
},
compiledGetValueFromFn: function() {
var str = '';
var pathString = 'obj';
str += 'if (obj != null';
var i = 0;
var key;
for (; i < (this.length - 1); i++) {
key = this[i];
pathString += isIdent(key) ? '.' + key : formatAccessor(key);
str += ' &&\n ' + pathString + ' != null';
}
str += ')\n';
var key = this[i];
pathString += isIdent(key) ? '.' + key : formatAccessor(key);
str += ' return ' + pathString + ';\nelse\n return undefined;';
return new Function('obj', str);
},
setValueFrom: function(obj, value) {
if (!this.length)
return false;
for (var i = 0; i < this.length - 1; i++) {
if (!isObject(obj))
return false;
obj = obj[this[i]];
}
if (!isObject(obj))
return false;
obj[this[i]] = value;
return true;
}
});
var invalidPath = new Path('', constructorIsPrivate);
invalidPath.valid = false;
invalidPath.getValueFrom = invalidPath.setValueFrom = function() {};
var MAX_DIRTY_CHECK_CYCLES = 1000;
function dirtyCheck(observer) {
var cycles = 0;
while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) {
cycles++;
}
if (testingExposeCycleCount)
global.dirtyCheckCycleCount = cycles;
return cycles > 0;
}
function objectIsEmpty(object) {
for (var prop in object)
return false;
return true;
}
function diffIsEmpty(diff) {
return objectIsEmpty(diff.added) &&
objectIsEmpty(diff.removed) &&
objectIsEmpty(diff.changed);
}
function diffObjectFromOldObject(object, oldObject) {
var added = {};
var removed = {};
var changed = {};
for (var prop in oldObject) {
var newValue = object[prop];
if (newValue !== undefined && newValue === oldObject[prop])
continue;
if (!(prop in object)) {
removed[prop] = undefined;
continue;
}
if (newValue !== oldObject[prop])
changed[prop] = newValue;
}
for (var prop in object) {
if (prop in oldObject)
continue;
added[prop] = object[prop];
}
if (Array.isArray(object) && object.length !== oldObject.length)
changed.length = object.length;
return {
added: added,
removed: removed,
changed: changed
};
}
var eomTasks = [];
function runEOMTasks() {
if (!eomTasks.length)
return false;
for (var i = 0; i < eomTasks.length; i++) {
eomTasks[i]();
}
eomTasks.length = 0;
return true;
}
var runEOM = hasObserve ? (function(){
return function(fn) {
return Promise.resolve().then(fn);
}
})() :
(function() {
return function(fn) {
eomTasks.push(fn);
};
})();
var observedObjectCache = [];
function newObservedObject() {
var observer;
var object;
var discardRecords = false;
var first = true;
function callback(records) {
if (observer && observer.state_ === OPENED && !discardRecords)
observer.check_(records);
}
return {
open: function(obs) {
if (observer)
throw Error('ObservedObject in use');
if (!first)
Object.deliverChangeRecords(callback);
observer = obs;
first = false;
},
observe: function(obj, arrayObserve) {
object = obj;
if (arrayObserve)
Array.observe(object, callback);
else
Object.observe(object, callback);
},
deliver: function(discard) {
discardRecords = discard;
Object.deliverChangeRecords(callback);
discardRecords = false;
},
close: function() {
observer = undefined;
Object.unobserve(object, callback);
observedObjectCache.push(this);
}
};
}
/*
* The observedSet abstraction is a perf optimization which reduces the total
* number of Object.observe observations of a set of objects. The idea is that
* groups of Observers will have some object dependencies in common and this
* observed set ensures that each object in the transitive closure of
* dependencies is only observed once. The observedSet acts as a write barrier
* such that whenever any change comes through, all Observers are checked for
* changed values.
*
* Note that this optimization is explicitly moving work from setup-time to
* change-time.
*
* TODO(rafaelw): Implement "garbage collection". In order to move work off
* the critical path, when Observers are closed, their observed objects are
* not Object.unobserve(d). As a result, it's possible that if the observedSet
* is kept open, but some Observers have been closed, it could cause "leaks"
* (prevent otherwise collectable objects from being collected). At some
* point, we should implement incremental "gc" which keeps a list of
* observedSets which may need clean-up and does small amounts of cleanup on a
* timeout until all is clean.
*/
function getObservedObject(observer, object, arrayObserve) {
var dir = observedObjectCache.pop() || newObservedObject();
dir.open(observer);
dir.observe(object, arrayObserve);
return dir;
}
var observedSetCache = [];
function newObservedSet() {
var observerCount = 0;
var observers = [];
var objects = [];
var rootObj;
var rootObjProps;
function observe(obj, prop) {
if (!obj)
return;
if (obj === rootObj)
rootObjProps[prop] = true;
if (objects.indexOf(obj) < 0) {
objects.push(obj);
Object.observe(obj, callback);
}
observe(Object.getPrototypeOf(obj), prop);
}
function allRootObjNonObservedProps(recs) {
for (var i = 0; i < recs.length; i++) {
var rec = recs[i];
if (rec.object !== rootObj ||
rootObjProps[rec.name] ||
rec.type === 'setPrototype') {
return false;
}
}
return true;
}
function callback(recs) {
if (allRootObjNonObservedProps(recs))
return;
var observer;
for (var i = 0; i < observers.length; i++) {
observer = observers[i];
if (observer.state_ == OPENED) {
observer.iterateObjects_(observe);
}
}
for (var i = 0; i < observers.length; i++) {
observer = observers[i];
if (observer.state_ == OPENED) {
observer.check_();
}
}
}
var record = {
objects: objects,
get rootObject() { return rootObj; },
set rootObject(value) {
rootObj = value;
rootObjProps = {};
},
open: function(obs, object) {
observers.push(obs);
observerCount++;
obs.iterateObjects_(observe);
},
close: function(obs) {
observerCount--;
if (observerCount > 0) {
return;
}
for (var i = 0; i < objects.length; i++) {
Object.unobserve(objects[i], callback);
Observer.unobservedCount++;
}
observers.length = 0;
objects.length = 0;
rootObj = undefined;
rootObjProps = undefined;
observedSetCache.push(this);
if (lastObservedSet === this)
lastObservedSet = null;
},
};
return record;
}
var lastObservedSet;
function getObservedSet(observer, obj) {
if (!lastObservedSet || lastObservedSet.rootObject !== obj) {
lastObservedSet = observedSetCache.pop() || newObservedSet();
lastObservedSet.rootObject = obj;
}
lastObservedSet.open(observer, obj);
return lastObservedSet;
}
var UNOPENED = 0;
var OPENED = 1;
var CLOSED = 2;
var RESETTING = 3;
var nextObserverId = 1;
function Observer() {
this.state_ = UNOPENED;
this.callback_ = undefined;
this.target_ = undefined; // TODO(rafaelw): Should be WeakRef
this.directObserver_ = undefined;
this.value_ = undefined;
this.id_ = nextObserverId++;
}
Observer.prototype = {
open: function(callback, target) {
if (this.state_ != UNOPENED)
throw Error('Observer has already been opened.');
addToAll(this);
this.callback_ = callback;
this.target_ = target;
this.connect_();
this.state_ = OPENED;
return this.value_;
},
close: function() {
if (this.state_ != OPENED)
return;
removeFromAll(this);
this.disconnect_();
this.value_ = undefined;
this.callback_ = undefined;
this.target_ = undefined;
this.state_ = CLOSED;
},
deliver: function() {
if (this.state_ != OPENED)
return;
dirtyCheck(this);
},
report_: function(changes) {
try {
this.callback_.apply(this.target_, changes);
} catch (ex) {
Observer._errorThrownDuringCallback = true;
console.error('Exception caught during observer callback: ' +
(ex.stack || ex));
}
},
discardChanges: function() {
this.check_(undefined, true);
return this.value_;
}
}
var collectObservers = !hasObserve;
var allObservers;
Observer._allObserversCount = 0;
if (collectObservers) {
allObservers = [];
}
function addToAll(observer) {
Observer._allObserversCount++;
if (!collectObservers)
return;
allObservers.push(observer);
}
function removeFromAll(observer) {
Observer._allObserversCount--;
}
var runningMicrotaskCheckpoint = false;
global.Platform = global.Platform || {};
global.Platform.performMicrotaskCheckpoint = function() {
if (runningMicrotaskCheckpoint)
return;
if (!collectObservers)
return;
runningMicrotaskCheckpoint = true;
var cycles = 0;
var anyChanged, toCheck;
do {
cycles++;
toCheck = allObservers;
allObservers = [];
anyChanged = false;
for (var i = 0; i < toCheck.length; i++) {
var observer = toCheck[i];
if (observer.state_ != OPENED)
continue;
if (observer.check_())
anyChanged = true;
allObservers.push(observer);
}
if (runEOMTasks())
anyChanged = true;
} while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged);
if (testingExposeCycleCount)
global.dirtyCheckCycleCount = cycles;
runningMicrotaskCheckpoint = false;
};
if (collectObservers) {
global.Platform.clearObservers = function() {
allObservers = [];
};
}
function ObjectObserver(object) {
Observer.call(this);
this.value_ = object;
this.oldObject_ = undefined;
}
ObjectObserver.prototype = createObject({
__proto__: Observer.prototype,
arrayObserve: false,
connect_: function(callback, target) {
if (hasObserve) {
this.directObserver_ = getObservedObject(this, this.value_,
this.arrayObserve);
} else {
this.oldObject_ = this.copyObject(this.value_);
}
},
copyObject: function(object) {
var copy = Array.isArray(object) ? [] : {};
for (var prop in object) {
copy[prop] = object[prop];
};
if (Array.isArray(object))
copy.length = object.length;
return copy;
},
check_: function(changeRecords, skipChanges) {
var diff;
var oldValues;
if (hasObserve) {
if (!changeRecords)
return false;
oldValues = {};
diff = diffObjectFromChangeRecords(this.value_, changeRecords,
oldValues);
} else {
oldValues = this.oldObject_;
diff = diffObjectFromOldObject(this.value_, this.oldObject_);
}
if (diffIsEmpty(diff))
return false;
if (!hasObserve)
this.oldObject_ = this.copyObject(this.value_);
this.report_([
diff.added || {},
diff.removed || {},
diff.changed || {},
function(property) {
return oldValues[property];
}
]);
return true;
},
disconnect_: function() {
if (hasObserve) {
this.directObserver_.close();
this.directObserver_ = undefined;
} else {
this.oldObject_ = undefined;
}
},
deliver: function() {
if (this.state_ != OPENED)
return;
if (hasObserve)
this.directObserver_.deliver(false);
else
dirtyCheck(this);
},
discardChanges: function() {
if (this.directObserver_)
this.directObserver_.deliver(true);
else
this.oldObject_ = this.copyObject(this.value_);
return this.value_;
}
});
function ArrayObserver(array) {
if (!Array.isArray(array))
throw Error('Provided object is not an Array');
ObjectObserver.call(this, array);
}
ArrayObserver.prototype = createObject({
__proto__: ObjectObserver.prototype,
arrayObserve: true,
copyObject: function(arr) {
return arr.slice();
},
check_: function(changeRecords) {
var splices;
if (hasObserve) {
if (!changeRecords)
return false;
splices = projectArraySplices(this.value_, changeRecords);
} else {
splices = calcSplices(this.value_, 0, this.value_.length,
this.oldObject_, 0, this.oldObject_.length);
}
if (!splices || !splices.length)
return false;
if (!hasObserve)
this.oldObject_ = this.copyObject(this.value_);
this.report_([splices]);
return true;
}
});
ArrayObserver.applySplices = function(previous, current, splices) {
splices.forEach(function(splice) {
var spliceArgs = [splice.index, splice.removed.length];
var addIndex = splice.index;
while (addIndex < splice.index + splice.addedCount) {
spliceArgs.push(current[addIndex]);
addIndex++;
}
Array.prototype.splice.apply(previous, spliceArgs);
});
};
function PathObserver(object, path) {
Observer.call(this);
this.object_ = object;
this.path_ = getPath(path);
this.directObserver_ = undefined;
}
PathObserver.prototype = createObject({
__proto__: Observer.prototype,
get path() {
return this.path_;
},
connect_: function() {
if (hasObserve)
this.directObserver_ = getObservedSet(this, this.object_);
this.check_(undefined, true);
},
disconnect_: function() {
this.value_ = undefined;
if (this.directObserver_) {
this.directObserver_.close(this);
this.directObserver_ = undefined;
}
},
iterateObjects_: function(observe) {
this.path_.iterateObjects(this.object_, observe);
},
check_: function(changeRecords, skipChanges) {
var oldValue = this.value_;
this.value_ = this.path_.getValueFrom(this.object_);
if (skipChanges || areSameValue(this.value_, oldValue))
return false;
this.report_([this.value_, oldValue, this]);
return true;
},
setValue: function(newValue) {
if (this.path_)
this.path_.setValueFrom(this.object_, newValue);
}
});
function CompoundObserver(reportChangesOnOpen) {
Observer.call(this);
this.reportChangesOnOpen_ = reportChangesOnOpen;
this.value_ = [];
this.directObserver_ = undefined;
this.observed_ = [];
}
var observerSentinel = {};
CompoundObserver.prototype = createObject({
__proto__: Observer.prototype,
connect_: function() {
if (hasObserve) {
var object;
var needsDirectObserver = false;
for (var i = 0; i < this.observed_.length; i += 2) {
object = this.observed_[i]
if (object !== observerSentinel) {
needsDirectObserver = true;
break;
}
}
if (needsDirectObserver)
this.directObserver_ = getObservedSet(this, object);
}
this.check_(undefined, !this.reportChangesOnOpen_);
},
disconnect_: function() {
for (var i = 0; i < this.observed_.length; i += 2) {
if (this.observed_[i] === observerSentinel)
this.observed_[i + 1].close();
}
this.observed_.length = 0;
this.value_.length = 0;
if (this.directObserver_) {
this.directObserver_.close(this);
this.directObserver_ = undefined;
}
},
addPath: function(object, path) {
if (this.state_ != UNOPENED && this.state_ != RESETTING)
throw Error('Cannot add paths once started.');
var path = getPath(path);
this.observed_.push(object, path);
if (!this.reportChangesOnOpen_)
return;
var index = this.observed_.length / 2 - 1;
this.value_[index] = path.getValueFrom(object);
},
addObserver: function(observer) {
if (this.state_ != UNOPENED && this.state_ != RESETTING)
throw Error('Cannot add observers once started.');
this.observed_.push(observerSentinel, observer);
if (!this.reportChangesOnOpen_)
return;
var index = this.observed_.length / 2 - 1;
this.value_[index] = observer.open(this.deliver, this);
},
startReset: function() {
if (this.state_ != OPENED)
throw Error('Can only reset while open');
this.state_ = RESETTING;
this.disconnect_();
},
finishReset: function() {
if (this.state_ != RESETTING)
throw Error('Can only finishReset after startReset');
this.state_ = OPENED;
this.connect_();
return this.value_;
},
iterateObjects_: function(observe) {
var object;
for (var i = 0; i < this.observed_.length; i += 2) {
object = this.observed_[i]
if (object !== observerSentinel)
this.observed_[i + 1].iterateObjects(object, observe)
}
},
check_: function(changeRecords, skipChanges) {
var oldValues;
for (var i = 0; i < this.observed_.length; i += 2) {
var object = this.observed_[i];
var path = this.observed_[i+1];
var value;
if (object === observerSentinel) {
var observable = path;
value = this.state_ === UNOPENED ?
observable.open(this.deliver, this) :
observable.discardChanges();
} else {
value = path.getValueFrom(object);
}
if (skipChanges) {
this.value_[i / 2] = value;
continue;
}
if (areSameValue(value, this.value_[i / 2]))
continue;
oldValues = oldValues || [];
oldValues[i / 2] = this.value_[i / 2];
this.value_[i / 2] = value;
}
if (!oldValues)
return false;
// TODO(rafaelw): Having observed_ as the third callback arg here is
// pretty lame API. Fix.
this.report_([this.value_, oldValues, this.observed_]);
return true;
}
});
function identFn(value) { return value; }
function ObserverTransform(observable, getValueFn, setValueFn,
dontPassThroughSet) {
this.callback_ = undefined;
this.target_ = undefined;
this.value_ = undefined;
this.observable_ = observable;
this.getValueFn_ = getValueFn || identFn;
this.setValueFn_ = setValueFn || identFn;
// TODO(rafaelw): This is a temporary hack. PolymerExpressions needs this
// at the moment because of a bug in it's dependency tracking.
this.dontPassThroughSet_ = dontPassThroughSet;
}
ObserverTransform.prototype = {
open: function(callback, target) {
this.callback_ = callback;
this.target_ = target;
this.value_ =
this.getValueFn_(this.observable_.open(this.observedCallback_, this));
return this.value_;
},
observedCallback_: function(value) {
value = this.getValueFn_(value);
if (areSameValue(value, this.value_))
return;
var oldValue = this.value_;
this.value_ = value;
this.callback_.call(this.target_, this.value_, oldValue);
},
discardChanges: function() {
this.value_ = this.getValueFn_(this.observable_.discardChanges());
return this.value_;
},
deliver: function() {
return this.observable_.deliver();
},
setValue: function(value) {
value = this.setValueFn_(value);
if (!this.dontPassThroughSet_ && this.observable_.setValue)
return this.observable_.setValue(value);
},
close: function() {
if (this.observable_)
this.observable_.close();
this.callback_ = undefined;
this.target_ = undefined;
this.observable_ = undefined;
this.value_ = undefined;
this.getValueFn_ = undefined;
this.setValueFn_ = undefined;
}
}
var expectedRecordTypes = {
add: true,
update: true,
delete: true
};
function diffObjectFromChangeRecords(object, changeRecords, oldValues) {
var added = {};
var removed = {};
for (var i = 0; i < changeRecords.length; i++) {
var record = changeRecords[i];
if (!expectedRecordTypes[record.type]) {
console.error('Unknown changeRecord type: ' + record.type);
console.error(record);
continue;
}
if (!(record.name in oldValues))
oldValues[record.name] = record.oldValue;
if (record.type == 'update')
continue;
if (record.type == 'add') {
if (record.name in removed)
delete removed[record.name];
else
added[record.name] = true;
continue;
}
// type = 'delete'
if (record.name in added) {
delete added[record.name];
delete oldValues[record.name];
} else {
removed[record.name] = true;
}
}
for (var prop in added)
added[prop] = object[prop];
for (var prop in removed)
removed[prop] = undefined;
var changed = {};
for (var prop in oldValues) {
if (prop in added || prop in removed)
continue;
var newValue = object[prop];
if (oldValues[prop] !== newValue)
changed[prop] = newValue;
}
return {
added: added,
removed: removed,
changed: changed
};
}
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 = {
// Note: This function is *based* on the computation of the Levenshtein
// "edit" distance. The one change is that "updates" are treated as two
// edits - not one. With Array splices, an update is really a delete
// followed by an add. By retaining this, we optimize for "keeping" the
// maximum array items in the original array. For example:
//
// 'xxxx123' -> '123yyyy'
//
// With 1-edit updates, the shortest path would be just to update all seven
// characters. With 2-edit updates, we delete 4, leave 3, and add 4. This
// leaves the substring '123' intact.
calcEditDistances: function(current, currentStart, currentEnd,
old, oldStart, oldEnd) {
// "Deletion" columns
var rowCount = oldEnd - oldStart + 1;
var columnCount = currentEnd - currentStart + 1;
var distances = new Array(rowCount);
// "Addition" rows. Initialize null column.
for (var i = 0; i < rowCount; i++) {
distances[i] = new Array(columnCount);
distances[i][0] = i;
}
// Initialize null row
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;
},
// This starts at the final weight, and walks "backward" by finding
// the minimum previous weight recursively until the origin of the weight
// matrix.
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;
},
/**
* Splice Projection functions:
*
* A splice map is a representation of how a previous array of items
* was transformed into a new array of items. Conceptually it is a list of
* tuples of
*
* <index, removed, addedCount>
*
* which are kept in ascending index order of. The tuple represents that at
* the |index|, |removed| sequence of items were removed, and counting forward
* from |index|, |addedCount| items were added.
*/
/**
* Lacking individual splice mutation information, the minimal set of
* splices can be synthesized given the previous state and final state of an
* array. The basic approach is to calculate the edit distance matrix and
* choose the shortest path through it.
*
* Complexity: O(l * p)
* l: The length of the current array
* p: The length of the old array
*/
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;
}
};
var arraySplice = new ArraySplice();
function calcSplices(current, currentStart, currentEnd,
old, oldStart, oldEnd) {
return arraySplice.calcSplices(current, currentStart, currentEnd,
old, oldStart, oldEnd);
}
function intersect(start1, end1, start2, end2) {
// Disjoint
if (end1 < start2 || end2 < start1)
return -1;
// Adjacent
if (end1 == start2 || end2 == start1)
return 0;
// Non-zero intersect, span1 first
if (start1 < start2) {
if (end1 < end2)
return end1 - start2; // Overlap
else
return end2 - start2; // Contained
} else {
// Non-zero intersect, span2 first
if (end2 < end1)
return end2 - start1; // Overlap
else
return end1 - start1; // Contained
}
}
function mergeSplice(splices, index, removed, addedCount) {
var splice = newSplice(index, removed, addedCount);
var inserted = false;
var insertionOffset = 0;
for (var i = 0; i < splices.length; i++) {
var current = splices[i];
current.index += insertionOffset;
if (inserted)
continue;
var intersectCount = intersect(splice.index,
splice.index + splice.removed.length,
current.index,
current.index + current.addedCount);
if (intersectCount >= 0) {
// Merge the two splices
splices.splice(i, 1);
i--;
insertionOffset -= current.addedCount - current.removed.length;
splice.addedCount += current.addedCount - intersectCount;
var deleteCount = splice.removed.length +
current.removed.length - intersectCount;
if (!splice.addedCount && !deleteCount) {
// merged splice is a noop. discard.
inserted = true;
} else {
var removed = current.removed;
if (splice.index < current.index) {
// some prefix of splice.removed is prepended to current.removed.
var prepend = splice.removed.slice(0, current.index - splice.index);
Array.prototype.push.apply(prepend, removed);
removed = prepend;
}
if (splice.index + splice.removed.length > current.index + current.addedCount) {
// some suffix of splice.removed is appended to current.removed.
var append = splice.removed.slice(current.index + current.addedCount - splice.index);
Array.prototype.push.apply(removed, append);
}
splice.removed = removed;
if (current.index < splice.index) {
splice.index = current.index;
}
}
} else if (splice.index < current.index) {
// Insert splice here.
inserted = true;
splices.splice(i, 0, splice);
i++;
var offset = splice.addedCount - splice.removed.length
current.index += offset;
insertionOffset += offset;
}
}
if (!inserted)
splices.push(splice);
}
function createInitialSplices(array, changeRecords) {
var splices = [];
for (var i = 0; i < changeRecords.length; i++) {
var record = changeRecords[i];
switch(record.type) {
case 'splice':
mergeSplice(splices, record.index, record.removed.slice(), record.addedCount);
break;
case 'add':
case 'update':
case 'delete':
if (!isIndex(record.name))
continue;
var index = toNumber(record.name);
if (index < 0)
continue;
mergeSplice(splices, index, [record.oldValue], 1);
break;
default:
console.error('Unexpected record type: ' + JSON.stringify(record));
break;
}
}
return splices;
}
function projectArraySplices(array, changeRecords) {
var splices = [];
createInitialSplices(array, changeRecords).forEach(function(splice) {
if (splice.addedCount == 1 && splice.removed.length == 1) {
if (splice.removed[0] !== array[splice.index])
splices.push(splice);
return
};
splices = splices.concat(calcSplices(array, splice.index, splice.index + splice.addedCount,
splice.removed, 0, splice.removed.length));
});
return splices;
}
// Export the observe-js object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, export as a global object.
var expose = global;
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
expose = exports = module.exports;
}
expose = exports;
}
expose.Observer = Observer;
expose.Observer.runEOM_ = runEOM;
expose.Observer.observerSentinel_ = observerSentinel; // for testing.
expose.Observer.hasObjectObserve = hasObserve;
expose.ArrayObserver = ArrayObserver;
expose.ArrayObserver.calculateSplices = function(current, previous) {
return arraySplice.calculateSplices(current, previous);
};
expose.ArraySplice = ArraySplice;
expose.ObjectObserver = ObjectObserver;
expose.PathObserver = PathObserver;
expose.CompoundObserver = CompoundObserver;
expose.Path = Path;
expose.ObserverTransform = ObserverTransform;
})(typeof global !== 'undefined' && global && typeof module !== 'undefined' && module ? global : this || window);
// 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
(function(global) {
'use strict';
var filter = Array.prototype.filter.call.bind(Array.prototype.filter);
function getTreeScope(node) {
while (node.parentNode) {
node = node.parentNode;
}
return typeof node.getElementById === 'function' ? node : null;
}
Node.prototype.bind = function(name, observable) {
console.error('Unhandled binding to Node: ', this, name, observable);
};
Node.prototype.bindFinished = function() {};
function updateBindings(node, name, binding) {
var bindings = node.bindings_;
if (!bindings)
bindings = node.bindings_ = {};
if (bindings[name])
binding[name].close();
return bindings[name] = binding;
}
function returnBinding(node, name, binding) {
return binding;
}
function sanitizeValue(value) {
return value == null ? '' : value;
}
function updateText(node, value) {
node.data = sanitizeValue(value);
}
function textBinding(node) {
return function(value) {
return updateText(node, value);
};
}
var maybeUpdateBindings = returnBinding;
Object.defineProperty(Platform, 'enableBindingsReflection', {
get: function() {
return maybeUpdateBindings === updateBindings;
},
set: function(enable) {
maybeUpdateBindings = enable ? updateBindings : returnBinding;
return enable;
},
configurable: true
});
Text.prototype.bind = function(name, value, oneTime) {
if (name !== 'textContent')
return Node.prototype.bind.call(this, name, value, oneTime);
if (oneTime)
return updateText(this, value);
var observable = value;
updateText(this, observable.open(textBinding(this)));
return maybeUpdateBindings(this, name, observable);
}
function updateAttribute(el, name, conditional, value) {
if (conditional) {
if (value)
el.setAttribute(name, '');
else
el.removeAttribute(name);
return;
}
el.setAttribute(name, sanitizeValue(value));
}
function attributeBinding(el, name, conditional) {
return function(value) {
updateAttribute(el, name, conditional, value);
};
}
Element.prototype.bind = function(name, value, oneTime) {
var conditional = name[name.length - 1] == '?';
if (conditional) {
this.removeAttribute(name);
name = name.slice(0, -1);
}
if (oneTime)
return updateAttribute(this, name, conditional, value);
var observable = value;
updateAttribute(this, name, conditional,
observable.open(attributeBinding(this, name, conditional)));
return maybeUpdateBindings(this, name, observable);
};
var checkboxEventType;
(function() {
// Attempt to feature-detect which event (change or click) is fired first
// for checkboxes.
var div = document.createElement('div');
var checkbox = div.appendChild(document.createElement('input'));
checkbox.setAttribute('type', 'checkbox');
var first;
var count = 0;
checkbox.addEventListener('click', function(e) {
count++;
first = first || 'click';
});
checkbox.addEventListener('change', function() {
count++;
first = first || 'change';
});
var event = document.createEvent('MouseEvent');
event.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false,
false, false, false, 0, null);
checkbox.dispatchEvent(event);
// WebKit/Blink don't fire the change event if the element is outside the
// document, so assume 'change' for that case.
checkboxEventType = count == 1 ? 'change' : first;
})();
function getEventForInputType(element) {
switch (element.type) {
case 'checkbox':
return checkboxEventType;
case 'radio':
case 'select-multiple':
case 'select-one':
return 'change';
case 'range':
if (/Trident|MSIE/.test(navigator.userAgent))
return 'change';
default:
return 'input';
}
}
function updateInput(input, property, value, santizeFn) {
input[property] = (santizeFn || sanitizeValue)(value);
}
function inputBinding(input, property, santizeFn) {
return function(value) {
return updateInput(input, property, value, santizeFn);
}
}
function noop() {}
function bindInputEvent(input, property, observable, postEventFn) {
var eventType = getEventForInputType(input);
function eventHandler() {
observable.setValue(input[property]);
observable.discardChanges();
(postEventFn || noop)(input);
Platform.performMicrotaskCheckpoint();
}
input.addEventListener(eventType, eventHandler);
return {
close: function() {
input.removeEventListener(eventType, eventHandler);
observable.close();
},
observable_: observable
}
}
function booleanSanitize(value) {
return Boolean(value);
}
// |element| is assumed to be an HTMLInputElement with |type| == 'radio'.
// Returns an array containing all radio buttons other than |element| that
// have the same |name|, either in the form that |element| belongs to or,
// if no form, in the document tree to which |element| belongs.
//
// This implementation is based upon the HTML spec definition of a
// "radio button group":
// http://www.whatwg.org/specs/web-apps/current-work/multipage/number-state.html#radio-button-group
//
function getAssociatedRadioButtons(element) {
if (element.form) {
return filter(element.form.elements, function(el) {
return el != element &&
el.tagName == 'INPUT' &&
el.type == 'radio' &&
el.name == element.name;
});
} else {
var treeScope = getTreeScope(element);
if (!treeScope)
return [];
var radios = treeScope.querySelectorAll(
'input[type="radio"][name="' + element.name + '"]');
return filter(radios, function(el) {
return el != element && !el.form;
});
}
}
function checkedPostEvent(input) {
// Only the radio button that is getting checked gets an event. We
// therefore find all the associated radio buttons and update their
// check binding manually.
if (input.tagName === 'INPUT' &&
input.type === 'radio') {
getAssociatedRadioButtons(input).forEach(function(radio) {
var checkedBinding = radio.bindings_.checked;
if (checkedBinding) {
// Set the value directly to avoid an infinite call stack.
checkedBinding.observable_.setValue(false);
}
});
}
}
HTMLInputElement.prototype.bind = function(name, value, oneTime) {
if (name !== 'value' && name !== 'checked')
return HTMLElement.prototype.bind.call(this, name, value, oneTime);
this.removeAttribute(name);
var sanitizeFn = name == 'checked' ? booleanSanitize : sanitizeValue;
var postEventFn = name == 'checked' ? checkedPostEvent : noop;
if (oneTime)
return updateInput(this, name, value, sanitizeFn);
var observable = value;
var binding = bindInputEvent(this, name, observable, postEventFn);
updateInput(this, name,
observable.open(inputBinding(this, name, sanitizeFn)),
sanitizeFn);
// Checkboxes may need to update bindings of other checkboxes.
return updateBindings(this, name, binding);
}
HTMLTextAreaElement.prototype.bind = function(name, value, oneTime) {
if (name !== 'value')
return HTMLElement.prototype.bind.call(this, name, value, oneTime);
this.removeAttribute('value');
if (oneTime)
return updateInput(this, 'value', value);
var observable = value;
var binding = bindInputEvent(this, 'value', observable);
updateInput(this, 'value',
observable.open(inputBinding(this, 'value', sanitizeValue)));
return maybeUpdateBindings(this, name, binding);
}
function updateOption(option, value) {
var parentNode = option.parentNode;;
var select;
var selectBinding;
var oldValue;
if (parentNode instanceof HTMLSelectElement &&
parentNode.bindings_ &&
parentNode.bindings_.value) {
select = parentNode;
selectBinding = select.bindings_.value;
oldValue = select.value;
}
option.value = sanitizeValue(value);
if (select && select.value != oldValue) {
selectBinding.observable_.setValue(select.value);
selectBinding.observable_.discardChanges();
Platform.performMicrotaskCheckpoint();
}
}
function optionBinding(option) {
return function(value) {
updateOption(option, value);
}
}
HTMLOptionElement.prototype.bind = function(name, value, oneTime) {
if (name !== 'value')
return HTMLElement.prototype.bind.call(this, name, value, oneTime);
this.removeAttribute('value');
if (oneTime)
return updateOption(this, value);
var observable = value;
var binding = bindInputEvent(this, 'value', observable);
updateOption(this, observable.open(optionBinding(this)));
return maybeUpdateBindings(this, name, binding);
}
HTMLSelectElement.prototype.bind = function(name, value, oneTime) {
if (name === 'selectedindex')
name = 'selectedIndex';
if (name !== 'selectedIndex' && name !== 'value')
return HTMLElement.prototype.bind.call(this, name, value, oneTime);
this.removeAttribute(name);
if (oneTime)
return updateInput(this, name, value);
var observable = value;
var binding = bindInputEvent(this, name, observable);
updateInput(this, name,
observable.open(inputBinding(this, name)));
// Option update events may need to access select bindings.
return updateBindings(this, name, binding);
}
})(this);
// 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
(function(global) {
'use strict';
function assert(v) {
if (!v)
throw new Error('Assertion failed');
}
var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
function getFragmentRoot(node) {
var p;
while (p = node.parentNode) {
node = p;
}
return node;
}
function searchRefId(node, id) {
if (!id)
return;
var ref;
var selector = '#' + id;
while (!ref) {
node = getFragmentRoot(node);
if (node.protoContent_)
ref = node.protoContent_.querySelector(selector);
else if (node.getElementById)
ref = node.getElementById(id);
if (ref || !node.templateCreator_)
break
node = node.templateCreator_;
}
return ref;
}
function getInstanceRoot(node) {
while (node.parentNode) {
node = node.parentNode;
}
return node.templateCreator_ ? node : null;
}
var Map;
if (global.Map && typeof global.Map.prototype.forEach === 'function') {
Map = global.Map;
} else {
Map = function() {
this.keys = [];
this.values = [];
};
Map.prototype = {
set: function(key, value) {
var index = this.keys.indexOf(key);
if (index < 0) {
this.keys.push(key);
this.values.push(value);
} else {
this.values[index] = value;
}
},
get: function(key) {
var index = this.keys.indexOf(key);
if (index < 0)
return;
return this.values[index];
},
delete: function(key, value) {
var index = this.keys.indexOf(key);
if (index < 0)
return false;
this.keys.splice(index, 1);
this.values.splice(index, 1);
return true;
},
forEach: function(f, opt_this) {
for (var i = 0; i < this.keys.length; i++)
f.call(opt_this || this, this.values[i], this.keys[i], this);
}
};
}
// JScript does not have __proto__. We wrap all object literals with
// createObject which uses Object.create, Object.defineProperty and
// Object.getOwnPropertyDescriptor to create a new object that does the exact
// same thing. The main downside to this solution is that we have to extract
// all those property descriptors for IE.
var createObject = ('__proto__' in {}) ?
function(obj) { return obj; } :
function(obj) {
var proto = obj.__proto__;
if (!proto)
return obj;
var newObject = Object.create(proto);
Object.getOwnPropertyNames(obj).forEach(function(name) {
Object.defineProperty(newObject, name,
Object.getOwnPropertyDescriptor(obj, name));
});
return newObject;
};
// IE does not support have Document.prototype.contains.
if (typeof document.contains != 'function') {
Document.prototype.contains = function(node) {
if (node === this || node.parentNode === this)
return true;
return this.documentElement.contains(node);
}
}
var BIND = 'bind';
var REPEAT = 'repeat';
var IF = 'if';
var templateAttributeDirectives = {
'template': true,
'repeat': true,
'bind': true,
'ref': true,
'if': true
};
var semanticTemplateElements = {
'THEAD': true,
'TBODY': true,
'TFOOT': true,
'TH': true,
'TR': true,
'TD': true,
'COLGROUP': true,
'COL': true,
'CAPTION': true,
'OPTION': true,
'OPTGROUP': true
};
var hasTemplateElement = typeof HTMLTemplateElement !== 'undefined';
if (hasTemplateElement) {
// TODO(rafaelw): Remove when fix for
// https://codereview.chromium.org/164803002/
// makes it to Chrome release.
(function() {
var t = document.createElement('template');
var d = t.content.ownerDocument;
var html = d.appendChild(d.createElement('html'));
var head = html.appendChild(d.createElement('head'));
var base = d.createElement('base');
base.href = document.baseURI;
head.appendChild(base);
})();
}
var allTemplatesSelectors = 'template, ' +
Object.keys(semanticTemplateElements).map(function(tagName) {
return tagName.toLowerCase() + '[template]';
}).join(', ');
function isSVGTemplate(el) {
return el.tagName == 'template' &&
el.namespaceURI == 'http://www.w3.org/2000/svg';
}
function isHTMLTemplate(el) {
return el.tagName == 'TEMPLATE' &&
el.namespaceURI == 'http://www.w3.org/1999/xhtml';
}
function isAttributeTemplate(el) {
return Boolean(semanticTemplateElements[el.tagName] &&
el.hasAttribute('template'));
}
function isTemplate(el) {
if (el.isTemplate_ === undefined)
el.isTemplate_ = el.tagName == 'TEMPLATE' || isAttributeTemplate(el);
return el.isTemplate_;
}
// FIXME: Observe templates being added/removed from documents
// FIXME: Expose imperative API to decorate and observe templates in
// "disconnected tress" (e.g. ShadowRoot)
document.addEventListener('DOMContentLoaded', function(e) {
bootstrapTemplatesRecursivelyFrom(document);
// FIXME: Is this needed? Seems like it shouldn't be.
Platform.performMicrotaskCheckpoint();
}, false);
function forAllTemplatesFrom(node, fn) {
var subTemplates = node.querySelectorAll(allTemplatesSelectors);
if (isTemplate(node))
fn(node)
forEach(subTemplates, fn);
}
function bootstrapTemplatesRecursivelyFrom(node) {
function bootstrap(template) {
if (!HTMLTemplateElement.decorate(template))
bootstrapTemplatesRecursivelyFrom(template.content);
}
forAllTemplatesFrom(node, bootstrap);
}
if (!hasTemplateElement) {
/**
* This represents a <template> element.
* @constructor
* @extends {HTMLElement}
*/
global.HTMLTemplateElement = function() {
throw TypeError('Illegal constructor');
};
}
var hasProto = '__proto__' in {};
function mixin(to, from) {
Object.getOwnPropertyNames(from).forEach(function(name) {
Object.defineProperty(to, name,
Object.getOwnPropertyDescriptor(from, name));
});
}
// http://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/templates/index.html#dfn-template-contents-owner
function getOrCreateTemplateContentsOwner(template) {
var doc = template.ownerDocument
if (!doc.defaultView)
return doc;
var d = doc.templateContentsOwner_;
if (!d) {
// TODO(arv): This should either be a Document or HTMLDocument depending
// on doc.
d = doc.implementation.createHTMLDocument('');
while (d.lastChild) {
d.removeChild(d.lastChild);
}
doc.templateContentsOwner_ = d;
}
return d;
}
function getTemplateStagingDocument(template) {
if (!template.stagingDocument_) {
var owner = template.ownerDocument;
if (!owner.stagingDocument_) {
owner.stagingDocument_ = owner.implementation.createHTMLDocument('');
owner.stagingDocument_.isStagingDocument = true;
// TODO(rafaelw): Remove when fix for
// https://codereview.chromium.org/164803002/
// makes it to Chrome release.
var base = owner.stagingDocument_.createElement('base');
base.href = document.baseURI;
owner.stagingDocument_.head.appendChild(base);
owner.stagingDocument_.stagingDocument_ = owner.stagingDocument_;
}
template.stagingDocument_ = owner.stagingDocument_;
}
return template.stagingDocument_;
}
// For non-template browsers, the parser will disallow <template> in certain
// locations, so we allow "attribute templates" which combine the template
// element with the top-level container node of the content, e.g.
//
// <tr template repeat="{{ foo }}"" class="bar"><td>Bar</td></tr>
//
// becomes
//
// <template repeat="{{ foo }}">
// + #document-fragment
// + <tr class="bar">
// + <td>Bar</td>
//
function extractTemplateFromAttributeTemplate(el) {
var template = el.ownerDocument.createElement('template');
el.parentNode.insertBefore(template, el);
var attribs = el.attributes;
var count = attribs.length;
while (count-- > 0) {
var attrib = attribs[count];
if (templateAttributeDirectives[attrib.name]) {
if (attrib.name !== 'template')
template.setAttribute(attrib.name, attrib.value);
el.removeAttribute(attrib.name);
}
}
return template;
}
function extractTemplateFromSVGTemplate(el) {
var template = el.ownerDocument.createElement('template');
el.parentNode.insertBefore(template, el);
var attribs = el.attributes;
var count = attribs.length;
while (count-- > 0) {
var attrib = attribs[count];
template.setAttribute(attrib.name, attrib.value);
el.removeAttribute(attrib.name);
}
el.parentNode.removeChild(el);
return template;
}
function liftNonNativeTemplateChildrenIntoContent(template, el, useRoot) {
var content = template.content;
if (useRoot) {
content.appendChild(el);
return;
}
var child;
while (child = el.firstChild) {
content.appendChild(child);
}
}
var templateObserver;
if (typeof MutationObserver == 'function') {
templateObserver = new MutationObserver(function(records) {
for (var i = 0; i < records.length; i++) {
records[i].target.refChanged_();
}
});
}
/**
* Ensures proper API and content model for template elements.
* @param {HTMLTemplateElement} opt_instanceRef The template element which
* |el| template element will return as the value of its ref(), and whose
* content will be used as source when createInstance() is invoked.
*/
HTMLTemplateElement.decorate = function(el, opt_instanceRef) {
if (el.templateIsDecorated_)
return false;
var templateElement = el;
templateElement.templateIsDecorated_ = true;
var isNativeHTMLTemplate = isHTMLTemplate(templateElement) &&
hasTemplateElement;
var bootstrapContents = isNativeHTMLTemplate;
var liftContents = !isNativeHTMLTemplate;
var liftRoot = false;
if (!isNativeHTMLTemplate) {
if (isAttributeTemplate(templateElement)) {
assert(!opt_instanceRef);
templateElement = extractTemplateFromAttributeTemplate(el);
templateElement.templateIsDecorated_ = true;
isNativeHTMLTemplate = hasTemplateElement;
liftRoot = true;
} else if (isSVGTemplate(templateElement)) {
templateElement = extractTemplateFromSVGTemplate(el);
templateElement.templateIsDecorated_ = true;
isNativeHTMLTemplate = hasTemplateElement;
}
}
if (!isNativeHTMLTemplate) {
fixTemplateElementPrototype(templateElement);
var doc = getOrCreateTemplateContentsOwner(templateElement);
templateElement.content_ = doc.createDocumentFragment();
}
if (opt_instanceRef) {
// template is contained within an instance, its direct content must be
// empty
templateElement.instanceRef_ = opt_instanceRef;
} else if (liftContents) {
liftNonNativeTemplateChildrenIntoContent(templateElement,
el,
liftRoot);
} else if (bootstrapContents) {
bootstrapTemplatesRecursivelyFrom(templateElement.content);
}
return true;
};
// TODO(rafaelw): This used to decorate recursively all templates from a given
// node. This happens by default on 'DOMContentLoaded', but may be needed
// in subtrees not descendent from document (e.g. ShadowRoot).
// Review whether this is the right public API.
HTMLTemplateElement.bootstrap = bootstrapTemplatesRecursivelyFrom;
var htmlElement = global.HTMLUnknownElement || HTMLElement;
var contentDescriptor = {
get: function() {
return this.content_;
},
enumerable: true,
configurable: true
};
if (!hasTemplateElement) {
// Gecko is more picky with the prototype than WebKit. Make sure to use the
// same prototype as created in the constructor.
HTMLTemplateElement.prototype = Object.create(htmlElement.prototype);
Object.defineProperty(HTMLTemplateElement.prototype, 'content',
contentDescriptor);
}
function fixTemplateElementPrototype(el) {
if (hasProto)
el.__proto__ = HTMLTemplateElement.prototype;
else
mixin(el, HTMLTemplateElement.prototype);
}
function ensureSetModelScheduled(template) {
if (!template.setModelFn_) {
template.setModelFn_ = function() {
template.setModelFnScheduled_ = false;
var map = getBindings(template,
template.delegate_ && template.delegate_.prepareBinding);
processBindings(template, map, template.model_);
};
}
if (!template.setModelFnScheduled_) {
template.setModelFnScheduled_ = true;
Observer.runEOM_(template.setModelFn_);
}
}
mixin(HTMLTemplateElement.prototype, {
bind: function(name, value, oneTime) {
if (name != 'ref')
return Element.prototype.bind.call(this, name, value, oneTime);
var self = this;
var ref = oneTime ? value : value.open(function(ref) {
self.setAttribute('ref', ref);
self.refChanged_();
});
this.setAttribute('ref', ref);
this.refChanged_();
if (oneTime)
return;
if (!this.bindings_) {
this.bindings_ = { ref: value };
} else {
this.bindings_.ref = value;
}
return value;
},
processBindingDirectives_: function(directives) {
if (this.iterator_)
this.iterator_.closeDeps();
if (!directives.if && !directives.bind && !directives.repeat) {
if (this.iterator_) {
this.iterator_.close();
this.iterator_ = undefined;
}
return;
}
if (!this.iterator_) {
this.iterator_ = new TemplateIterator(this);
}
this.iterator_.updateDependencies(directives, this.model_);
if (templateObserver) {
templateObserver.observe(this, { attributes: true,
attributeFilter: ['ref'] });
}
return this.iterator_;
},
createInstance: function(model, bindingDelegate, delegate_) {
if (bindingDelegate)
delegate_ = this.newDelegate_(bindingDelegate);
else if (!delegate_)
delegate_ = this.delegate_;
if (!this.refContent_)
this.refContent_ = this.ref_.content;
var content = this.refContent_;
if (content.firstChild === null)
return emptyInstance;
var map = getInstanceBindingMap(content, delegate_);
var stagingDocument = getTemplateStagingDocument(this);
var instance = stagingDocument.createDocumentFragment();
instance.templateCreator_ = this;
instance.protoContent_ = content;
instance.bindings_ = [];
instance.terminator_ = null;
var instanceRecord = instance.templateInstance_ = {
firstNode: null,
lastNode: null,
model: model
};
var i = 0;
var collectTerminator = false;
for (var child = content.firstChild; child; child = child.nextSibling) {
// The terminator of the instance is the clone of the last child of the
// content. If the last child is an active template, it may produce
// instances as a result of production, so simply collecting the last
// child of the instance after it has finished producing may be wrong.
if (child.nextSibling === null)
collectTerminator = true;
var clone = cloneAndBindInstance(child, instance, stagingDocument,
map.children[i++],
model,
delegate_,
instance.bindings_);
clone.templateInstance_ = instanceRecord;
if (collectTerminator)
instance.terminator_ = clone;
}
instanceRecord.firstNode = instance.firstChild;
instanceRecord.lastNode = instance.lastChild;
instance.templateCreator_ = undefined;
instance.protoContent_ = undefined;
return instance;
},
get model() {
return this.model_;
},
set model(model) {
this.model_ = model;
ensureSetModelScheduled(this);
},
get bindingDelegate() {
return this.delegate_ && this.delegate_.raw;
},
refChanged_: function() {
if (!this.iterator_ || this.refContent_ === this.ref_.content)
return;
this.refContent_ = undefined;
this.iterator_.valueChanged();
this.iterator_.updateIteratedValue(this.iterator_.getUpdatedValue());
},
clear: function() {
this.model_ = undefined;
this.delegate_ = undefined;
if (this.bindings_ && this.bindings_.ref)
this.bindings_.ref.close()
this.refContent_ = undefined;
if (!this.iterator_)
return;
this.iterator_.valueChanged();
this.iterator_.close()
this.iterator_ = undefined;
},
setDelegate_: function(delegate) {
this.delegate_ = delegate;
this.bindingMap_ = undefined;
if (this.iterator_) {
this.iterator_.instancePositionChangedFn_ = undefined;
this.iterator_.instanceModelFn_ = undefined;
}
},
newDelegate_: function(bindingDelegate) {
if (!bindingDelegate)
return;
function delegateFn(name) {
var fn = bindingDelegate && bindingDelegate[name];
if (typeof fn != 'function')
return;
return function() {
return fn.apply(bindingDelegate, arguments);
};
}
return {
bindingMaps: {},
raw: bindingDelegate,
prepareBinding: delegateFn('prepareBinding'),
prepareInstanceModel: delegateFn('prepareInstanceModel'),
prepareInstancePositionChanged:
delegateFn('prepareInstancePositionChanged')
};
},
set bindingDelegate(bindingDelegate) {
if (this.delegate_) {
throw Error('Template must be cleared before a new bindingDelegate ' +
'can be assigned');
}
this.setDelegate_(this.newDelegate_(bindingDelegate));
},
get ref_() {
var ref = searchRefId(this, this.getAttribute('ref'));
if (!ref)
ref = this.instanceRef_;
if (!ref)
return this;
var nextRef = ref.ref_;
return nextRef ? nextRef : ref;
}
});
// Returns
// a) undefined if there are no mustaches.
// b) [TEXT, (ONE_TIME?, PATH, DELEGATE_FN, TEXT)+] if there is at least one mustache.
function parseMustaches(s, name, node, prepareBindingFn) {
if (!s || !s.length)
return;
var tokens;
var length = s.length;
var startIndex = 0, lastIndex = 0, endIndex = 0;
var onlyOneTime = true;
while (lastIndex < length) {
var startIndex = s.indexOf('{{', lastIndex);
var oneTimeStart = s.indexOf('[[', lastIndex);
var oneTime = false;
var terminator = '}}';
if (oneTimeStart >= 0 &&
(startIndex < 0 || oneTimeStart < startIndex)) {
startIndex = oneTimeStart;
oneTime = true;
terminator = ']]';
}
endIndex = startIndex < 0 ? -1 : s.indexOf(terminator, startIndex + 2);
if (endIndex < 0) {
if (!tokens)
return;
tokens.push(s.slice(lastIndex)); // TEXT
break;
}
tokens = tokens || [];
tokens.push(s.slice(lastIndex, startIndex)); // TEXT
var pathString = s.slice(startIndex + 2, endIndex).trim();
tokens.push(oneTime); // ONE_TIME?
onlyOneTime = onlyOneTime && oneTime;
var delegateFn = prepareBindingFn &&
prepareBindingFn(pathString, name, node);
// Don't try to parse the expression if there's a prepareBinding function
if (delegateFn == null) {
tokens.push(Path.get(pathString)); // PATH
} else {
tokens.push(null);
}
tokens.push(delegateFn); // DELEGATE_FN
lastIndex = endIndex + 2;
}
if (lastIndex === length)
tokens.push(''); // TEXT
tokens.hasOnePath = tokens.length === 5;
tokens.isSimplePath = tokens.hasOnePath &&
tokens[0] == '' &&
tokens[4] == '';
tokens.onlyOneTime = onlyOneTime;
tokens.combinator = function(values) {
var newValue = tokens[0];
for (var i = 1; i < tokens.length; i += 4) {
var value = tokens.hasOnePath ? values : values[(i - 1) / 4];
if (value !== undefined)
newValue += value;
newValue += tokens[i + 3];
}
return newValue;
}
return tokens;
};
function processOneTimeBinding(name, tokens, node, model) {
if (tokens.hasOnePath) {
var delegateFn = tokens[3];
var value = delegateFn ? delegateFn(model, node, true) :
tokens[2].getValueFrom(model);
return tokens.isSimplePath ? value : tokens.combinator(value);
}
var values = [];
for (var i = 1; i < tokens.length; i += 4) {
var delegateFn = tokens[i + 2];
values[(i - 1) / 4] = delegateFn ? delegateFn(model, node) :
tokens[i + 1].getValueFrom(model);
}
return tokens.combinator(values);
}
function processSinglePathBinding(name, tokens, node, model) {
var delegateFn = tokens[3];
var observer = delegateFn ? delegateFn(model, node, false) :
new PathObserver(model, tokens[2]);
return tokens.isSimplePath ? observer :
new ObserverTransform(observer, tokens.combinator);
}
function processBinding(name, tokens, node, model) {
if (tokens.onlyOneTime)
return processOneTimeBinding(name, tokens, node, model);
if (tokens.hasOnePath)
return processSinglePathBinding(name, tokens, node, model);
var observer = new CompoundObserver();
for (var i = 1; i < tokens.length; i += 4) {
var oneTime = tokens[i];
var delegateFn = tokens[i + 2];
if (delegateFn) {
var value = delegateFn(model, node, oneTime);
if (oneTime)
observer.addPath(value)
else
observer.addObserver(value);
continue;
}
var path = tokens[i + 1];
if (oneTime)
observer.addPath(path.getValueFrom(model))
else
observer.addPath(model, path);
}
return new ObserverTransform(observer, tokens.combinator);
}
function processBindings(node, bindings, model, instanceBindings) {
for (var i = 0; i < bindings.length; i += 2) {
var name = bindings[i]
var tokens = bindings[i + 1];
var value = processBinding(name, tokens, node, model);
var binding = node.bind(name, value, tokens.onlyOneTime);
if (binding && instanceBindings)
instanceBindings.push(binding);
}
node.bindFinished();
if (!bindings.isTemplate)
return;
node.model_ = model;
var iter = node.processBindingDirectives_(bindings);
if (instanceBindings && iter)
instanceBindings.push(iter);
}
function parseWithDefault(el, name, prepareBindingFn) {
var v = el.getAttribute(name);
return parseMustaches(v == '' ? '{{}}' : v, name, el, prepareBindingFn);
}
function parseAttributeBindings(element, prepareBindingFn) {
assert(element);
var bindings = [];
var ifFound = false;
var bindFound = false;
for (var i = 0; i < element.attributes.length; i++) {
var attr = element.attributes[i];
var name = attr.name;
var value = attr.value;
// Allow bindings expressed in attributes to be prefixed with underbars.
// We do this to allow correct semantics for browsers that don't implement
// <template> where certain attributes might trigger side-effects -- and
// for IE which sanitizes certain attributes, disallowing mustache
// replacements in their text.
while (name[0] === '_') {
name = name.substring(1);
}
if (isTemplate(element) &&
(name === IF || name === BIND || name === REPEAT)) {
continue;
}
var tokens = parseMustaches(value, name, element,
prepareBindingFn);
if (!tokens)
continue;
bindings.push(name, tokens);
}
if (isTemplate(element)) {
bindings.isTemplate = true;
bindings.if = parseWithDefault(element, IF, prepareBindingFn);
bindings.bind = parseWithDefault(element, BIND, prepareBindingFn);
bindings.repeat = parseWithDefault(element, REPEAT, prepareBindingFn);
if (bindings.if && !bindings.bind && !bindings.repeat)
bindings.bind = parseMustaches('{{}}', BIND, element, prepareBindingFn);
}
return bindings;
}
function getBindings(node, prepareBindingFn) {
if (node.nodeType === Node.ELEMENT_NODE)
return parseAttributeBindings(node, prepareBindingFn);
if (node.nodeType === Node.TEXT_NODE) {
var tokens = parseMustaches(node.data, 'textContent', node,
prepareBindingFn);
if (tokens)
return ['textContent', tokens];
}
return [];
}
function cloneAndBindInstance(node, parent, stagingDocument, bindings, model,
delegate,
instanceBindings,
instanceRecord) {
var clone = parent.appendChild(stagingDocument.importNode(node, false));
var i = 0;
for (var child = node.firstChild; child; child = child.nextSibling) {
cloneAndBindInstance(child, clone, stagingDocument,
bindings.children[i++],
model,
delegate,
instanceBindings);
}
if (bindings.isTemplate) {
HTMLTemplateElement.decorate(clone, node);
if (delegate)
clone.setDelegate_(delegate);
}
processBindings(clone, bindings, model, instanceBindings);
return clone;
}
function createInstanceBindingMap(node, prepareBindingFn) {
var map = getBindings(node, prepareBindingFn);
map.children = {};
var index = 0;
for (var child = node.firstChild; child; child = child.nextSibling) {
map.children[index++] = createInstanceBindingMap(child, prepareBindingFn);
}
return map;
}
var contentUidCounter = 1;
// TODO(rafaelw): Setup a MutationObserver on content which clears the id
// so that bindingMaps regenerate when the template.content changes.
function getContentUid(content) {
var id = content.id_;
if (!id)
id = content.id_ = contentUidCounter++;
return id;
}
// Each delegate is associated with a set of bindingMaps, one for each
// content which may be used by a template. The intent is that each binding
// delegate gets the opportunity to prepare the instance (via the prepare*
// delegate calls) once across all uses.
// TODO(rafaelw): Separate out the parse map from the binding map. In the
// current implementation, if two delegates need a binding map for the same
// content, the second will have to reparse.
function getInstanceBindingMap(content, delegate_) {
var contentId = getContentUid(content);
if (delegate_) {
var map = delegate_.bindingMaps[contentId];
if (!map) {
map = delegate_.bindingMaps[contentId] =
createInstanceBindingMap(content, delegate_.prepareBinding) || [];
}
return map;
}
var map = content.bindingMap_;
if (!map) {
map = content.bindingMap_ =
createInstanceBindingMap(content, undefined) || [];
}
return map;
}
Object.defineProperty(Node.prototype, 'templateInstance', {
get: function() {
var instance = this.templateInstance_;
return instance ? instance :
(this.parentNode ? this.parentNode.templateInstance : undefined);
}
});
var emptyInstance = document.createDocumentFragment();
emptyInstance.bindings_ = [];
emptyInstance.terminator_ = null;
function TemplateIterator(templateElement) {
this.closed = false;
this.templateElement_ = templateElement;
this.instances = [];
this.deps = undefined;
this.iteratedValue = [];
this.presentValue = undefined;
this.arrayObserver = undefined;
}
TemplateIterator.prototype = {
closeDeps: function() {
var deps = this.deps;
if (deps) {
if (deps.ifOneTime === false)
deps.ifValue.close();
if (deps.oneTime === false)
deps.value.close();
}
},
updateDependencies: function(directives, model) {
this.closeDeps();
var deps = this.deps = {};
var template = this.templateElement_;
var ifValue = true;
if (directives.if) {
deps.hasIf = true;
deps.ifOneTime = directives.if.onlyOneTime;
deps.ifValue = processBinding(IF, directives.if, template, model);
ifValue = deps.ifValue;
// oneTime if & predicate is false. nothing else to do.
if (deps.ifOneTime && !ifValue) {
this.valueChanged();
return;
}
if (!deps.ifOneTime)
ifValue = ifValue.open(this.updateIfValue, this);
}
if (directives.repeat) {
deps.repeat = true;
deps.oneTime = directives.repeat.onlyOneTime;
deps.value = processBinding(REPEAT, directives.repeat, template, model);
} else {
deps.repeat = false;
deps.oneTime = directives.bind.onlyOneTime;
deps.value = processBinding(BIND, directives.bind, template, model);
}
var value = deps.value;
if (!deps.oneTime)
value = value.open(this.updateIteratedValue, this);
if (!ifValue) {
this.valueChanged();
return;
}
this.updateValue(value);
},
/**
* Gets the updated value of the bind/repeat. This can potentially call
* user code (if a bindingDelegate is set up) so we try to avoid it if we
* already have the value in hand (from Observer.open).
*/
getUpdatedValue: function() {
var value = this.deps.value;
if (!this.deps.oneTime)
value = value.discardChanges();
return value;
},
updateIfValue: function(ifValue) {
if (!ifValue) {
this.valueChanged();
return;
}
this.updateValue(this.getUpdatedValue());
},
updateIteratedValue: function(value) {
if (this.deps.hasIf) {
var ifValue = this.deps.ifValue;
if (!this.deps.ifOneTime)
ifValue = ifValue.discardChanges();
if (!ifValue) {
this.valueChanged();
return;
}
}
this.updateValue(value);
},
updateValue: function(value) {
if (!this.deps.repeat)
value = [value];
var observe = this.deps.repeat &&
!this.deps.oneTime &&
Array.isArray(value);
this.valueChanged(value, observe);
},
valueChanged: function(value, observeValue) {
if (!Array.isArray(value))
value = [];
if (value === this.iteratedValue)
return;
this.unobserve();
this.presentValue = value;
if (observeValue) {
this.arrayObserver = new ArrayObserver(this.presentValue);
this.arrayObserver.open(this.handleSplices, this);
}
this.handleSplices(ArrayObserver.calculateSplices(this.presentValue,
this.iteratedValue));
},
getLastInstanceNode: function(index) {
if (index == -1)
return this.templateElement_;
var instance = this.instances[index];
var terminator = instance.terminator_;
if (!terminator)
return this.getLastInstanceNode(index - 1);
if (terminator.nodeType !== Node.ELEMENT_NODE ||
this.templateElement_ === terminator) {
return terminator;
}
var subtemplateIterator = terminator.iterator_;
if (!subtemplateIterator)
return terminator;
return subtemplateIterator.getLastTemplateNode();
},
getLastTemplateNode: function() {
return this.getLastInstanceNode(this.instances.length - 1);
},
insertInstanceAt: function(index, fragment) {
var previousInstanceLast = this.getLastInstanceNode(index - 1);
var parent = this.templateElement_.parentNode;
this.instances.splice(index, 0, fragment);
parent.insertBefore(fragment, previousInstanceLast.nextSibling);
},
extractInstanceAt: function(index) {
var previousInstanceLast = this.getLastInstanceNode(index - 1);
var lastNode = this.getLastInstanceNode(index);
var parent = this.templateElement_.parentNode;
var instance = this.instances.splice(index, 1)[0];
while (lastNode !== previousInstanceLast) {
var node = previousInstanceLast.nextSibling;
if (node == lastNode)
lastNode = previousInstanceLast;
instance.appendChild(parent.removeChild(node));
}
return instance;
},
getDelegateFn: function(fn) {
fn = fn && fn(this.templateElement_);
return typeof fn === 'function' ? fn : null;
},
handleSplices: function(splices) {
if (this.closed || !splices.length)
return;
var template = this.templateElement_;
if (!template.parentNode) {
this.close();
return;
}
ArrayObserver.applySplices(this.iteratedValue, this.presentValue,
splices);
var delegate = template.delegate_;
if (this.instanceModelFn_ === undefined) {
this.instanceModelFn_ =
this.getDelegateFn(delegate && delegate.prepareInstanceModel);
}
if (this.instancePositionChangedFn_ === undefined) {
this.instancePositionChangedFn_ =
this.getDelegateFn(delegate &&
delegate.prepareInstancePositionChanged);
}
// Instance Removals
var instanceCache = new Map;
var removeDelta = 0;
for (var i = 0; i < splices.length; i++) {
var splice = splices[i];
var removed = splice.removed;
for (var j = 0; j < removed.length; j++) {
var model = removed[j];
var instance = this.extractInstanceAt(splice.index + removeDelta);
if (instance !== emptyInstance) {
instanceCache.set(model, instance);
}
}
removeDelta -= splice.addedCount;
}
// Instance Insertions
for (var i = 0; i < splices.length; i++) {
var splice = splices[i];
var addIndex = splice.index;
for (; addIndex < splice.index + splice.addedCount; addIndex++) {
var model = this.iteratedValue[addIndex];
var instance = instanceCache.get(model);
if (instance) {
instanceCache.delete(model);
} else {
if (this.instanceModelFn_) {
model = this.instanceModelFn_(model);
}
if (model === undefined) {
instance = emptyInstance;
} else {
instance = template.createInstance(model, undefined, delegate);
}
}
this.insertInstanceAt(addIndex, instance);
}
}
instanceCache.forEach(function(instance) {
this.closeInstanceBindings(instance);
}, this);
if (this.instancePositionChangedFn_)
this.reportInstancesMoved(splices);
},
reportInstanceMoved: function(index) {
var instance = this.instances[index];
if (instance === emptyInstance)
return;
this.instancePositionChangedFn_(instance.templateInstance_, index);
},
reportInstancesMoved: function(splices) {
var index = 0;
var offset = 0;
for (var i = 0; i < splices.length; i++) {
var splice = splices[i];
if (offset != 0) {
while (index < splice.index) {
this.reportInstanceMoved(index);
index++;
}
} else {
index = splice.index;
}
while (index < splice.index + splice.addedCount) {
this.reportInstanceMoved(index);
index++;
}
offset += splice.addedCount - splice.removed.length;
}
if (offset == 0)
return;
var length = this.instances.length;
while (index < length) {
this.reportInstanceMoved(index);
index++;
}
},
closeInstanceBindings: function(instance) {
var bindings = instance.bindings_;
for (var i = 0; i < bindings.length; i++) {
bindings[i].close();
}
},
unobserve: function() {
if (!this.arrayObserver)
return;
this.arrayObserver.close();
this.arrayObserver = undefined;
},
close: function() {
if (this.closed)
return;
this.unobserve();
for (var i = 0; i < this.instances.length; i++) {
this.closeInstanceBindings(this.instances[i]);
}
this.instances.length = 0;
this.closeDeps();
this.templateElement_.iterator_ = undefined;
this.closed = true;
}
};
// Polyfill-specific API.
HTMLTemplateElement.forAllTemplatesFrom_ = forAllTemplatesFrom;
})(this);
(function(scope) {
'use strict';
// feature detect for URL constructor
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)
}
// XXX
return h.toLowerCase()
}
function percentEscape(c) {
var unicode = c.charCodeAt(0);
if (unicode > 0x20 &&
unicode < 0x7F &&
// " # < > ? `
[0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1
) {
return c;
}
return encodeURIComponent(c);
}
function percentEscapeQuery(c) {
// XXX This actually needs to encode c using encoding and then
// convert the bytes one-by-one.
var unicode = c.charCodeAt(0);
if (unicode > 0x20 &&
unicode < 0x7F &&
// " # < > ` (do not escape '?')
[0x22, 0x23, 0x3C, 0x3E, 0x60].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(); // ASCII-safe
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(); // ASCII-safe
} 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) {
query = '?';
state = 'query';
} else if ('#' == c) {
this._fragment = '#';
state = 'fragment';
} else {
// XXX error handling
if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
this._schemeData += percentEscape(c);
}
}
break;
case 'no scheme':
if (!base || !(isRelativeScheme(base._scheme))) {
err('Missing scheme.');
invalid.call(this);
} else {
state = 'relative';
continue;
}
break;
case 'relative or authority':
if ('/' == c && '/' == input[cursor+1]) {
state = 'authority ignore slashes';
} else {
err('Expected /, got: ' + c);
state = 'relative';
continue
}
break;
case 'relative':
this._isRelative = true;
if ('file' != this._scheme)
this._scheme = base._scheme;
if (EOF == c) {
this._host = base._host;
this._port = base._port;
this._path = base._path.slice();
this._query = base._query;
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 = '?';
state = 'query';
} else if ('#' == c) {
this._host = base._host;
this._port = base._port;
this._path = base._path.slice();
this._query = base._query;
this._fragment = '#';
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._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;
}
state = 'relative path';
continue;
}
break;
case 'authority first slash':
if ('/' == c) {
state = 'authority second slash';
} else {
err("Expected '/', got: " + c);
state = 'authority ignore slashes';
continue;
}
break;
case 'authority second slash':
state = 'authority ignore slashes';
if ('/' != c) {
err("Expected '/', got: " + c);
continue;
}
break;
case 'authority ignore slashes':
if ('/' != c && '\\' != c) {
state = 'authority';
continue;
} else {
err('Expected authority, got: ' + c);
}
break;
case 'authority':
if ('@' == c) {
if (seenAt) {
err('@ already seen.');
buffer += '%40';
}
seenAt = true;
for (var i = 0; i < buffer.length; i++) {
var cp = buffer[i];
if ('\t' == cp || '\n' == cp || '\r' == cp) {
err('Invalid whitespace in authority.');
continue;
}
// XXX check URL code points
if (':' == cp && null === this._password) {
this._password = '';
continue;
}
var tempC = percentEscape(cp);
(null !== this._password) ? this._password += tempC : this._username += tempC;
}
buffer = '';
} else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
cursor -= buffer.length;
buffer = '';
state = 'host';
continue;
} else {
buffer += c;
}
break;
case 'file host':
if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) {
state = 'relative path';
} else if (buffer.length == 0) {
state = 'relative path start';
} else {
this._host = IDNAToASCII.call(this, buffer);
buffer = '';
state = 'relative path start';
}
continue;
} else if ('\t' == c || '\n' == c || '\r' == c) {
err('Invalid whitespace in file host.');
} else {
buffer += c;
}
break;
case 'host':
case 'hostname':
if (':' == c && !seenBracket) {
// XXX host parsing
this._host = IDNAToASCII.call(this, buffer);
buffer = '';
state = 'port';
if ('hostname' == stateOverride) {
break loop;
}
} else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
this._host = IDNAToASCII.call(this, buffer);
buffer = '';
state = 'relative path start';
if (stateOverride) {
break loop;
}
continue;
} else if ('\t' != c && '\n' != c && '\r' != c) {
if ('[' == c) {
seenBracket = true;
} else if (']' == c) {
seenBracket = false;
}
buffer += c;
} else {
err('Invalid code point in host/hostname: ' + c);
}
break;
case 'port':
if (/[0-9]/.test(c)) {
buffer += c;
} else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) {
if ('' != buffer) {
var temp = parseInt(buffer, 10);
if (temp != relative[this._scheme]) {
this._port = temp + '';
}
buffer = '';
}
if (stateOverride) {
break loop;
}
state = 'relative path start';
continue;
} else if ('\t' == c || '\n' == c || '\r' == c) {
err('Invalid code point in port: ' + c);
} else {
invalid.call(this);
}
break;
case 'relative path start':
if ('\\' == c)
err("'\\' not allowed in path.");
state = 'relative path';
if ('/' != c && '\\' != c) {
continue;
}
break;
case 'relative path':
if (EOF == c || '/' == c || '\\' == c || (!stateOverride && ('?' == c || '#' == c))) {
if ('\\' == c) {
err('\\ not allowed in relative path.');
}
var tmp;
if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
buffer = tmp;
}
if ('..' == buffer) {
this._path.pop();
if ('/' != c && '\\' != c) {
this._path.push('');
}
} else if ('.' == buffer && '/' != c && '\\' != c) {
this._path.push('');
} else if ('.' != buffer) {
if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') {
buffer = buffer[0] + ':';
}
this._path.push(buffer);
}
buffer = '';
if ('?' == c) {
this._query = '?';
state = 'query';
} else if ('#' == c) {
this._fragment = '#';
state = 'fragment';
}
} else if ('\t' != c && '\n' != c && '\r' != c) {
buffer += percentEscape(c);
}
break;
case 'query':
if (!stateOverride && '#' == c) {
this._fragment = '#';
state = 'fragment';
} else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
this._query += percentEscapeQuery(c);
}
break;
case 'fragment':
if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
this._fragment += c;
}
break;
}
cursor++;
}
}
function clear() {
this._scheme = '';
this._schemeData = '';
this._username = '';
this._password = null;
this._host = '';
this._port = '';
this._path = [];
this._query = '';
this._fragment = '';
this._isInvalid = false;
this._isRelative = false;
}
// Does not process domain names or IP addresses.
// Does not handle encoding for the query parameter.
function jURL(url, base /* , encoding */) {
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, '');
// encoding = encoding || 'utf-8'
parse.call(this, input, null, base);
}
jURL.prototype = {
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 '';
}
// javascript: Gecko returns String(""), WebKit/Blink String("null")
// Gecko throws error for "data://"
// data: Gecko returns "", Blink returns "data://", WebKit returns "null"
// Gecko returns String("") for file: mailto:
// WebKit/Blink returns String("SCHEME://") for file: mailto:
switch (this._scheme) {
case 'data':
case 'file':
case 'javascript':
case 'mailto':
return 'null';
}
host = this.host;
if (!host) {
return '';
}
return this._scheme + '://' + host;
}
};
// Copy over the static methods
var OriginalURL = scope.URL;
if (OriginalURL) {
jURL.createObjectURL = function(blob) {
// IE extension allows a second optional options argument.
// http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
};
jURL.revokeObjectURL = function(url) {
OriginalURL.revokeObjectURL(url);
};
}
scope.URL = jURL;
})(this);
(function(scope) {
var iterations = 0;
var callbacks = [];
var twiddle = document.createTextNode('');
function endOfMicrotask(callback) {
twiddle.textContent = iterations++;
callbacks.push(callback);
}
function atEndOfMicrotask() {
while (callbacks.length) {
callbacks.shift()();
}
}
new (window.MutationObserver || JsMutationObserver)(atEndOfMicrotask)
.observe(twiddle, {characterData: true})
;
// exports
scope.endOfMicrotask = endOfMicrotask;
// bc
Platform.endOfMicrotask = endOfMicrotask;
})(Polymer);
(function(scope) {
/**
* @class Polymer
*/
// imports
var endOfMicrotask = scope.endOfMicrotask;
// logging
var log = window.WebComponents ? WebComponents.flags.log : {};
// inject style sheet
var style = document.createElement('style');
style.textContent = 'template {display: none !important;} /* injected by platform.js */';
var head = document.querySelector('head');
head.insertBefore(style, head.firstChild);
/**
* Force any pending data changes to be observed before
* the next task. Data changes are processed asynchronously but are guaranteed
* to be processed, for example, before painting. This method should rarely be
* needed. It does nothing when Object.observe is available;
* when Object.observe is not available, Polymer automatically flushes data
* changes approximately every 1/10 second.
* Therefore, `flush` should only be used when a data mutation should be
* observed sooner than this.
*
* @method flush
*/
// flush (with logging)
var flushing;
function flush() {
if (!flushing) {
flushing = true;
endOfMicrotask(function() {
flushing = false;
log.data && console.group('flush');
Platform.performMicrotaskCheckpoint();
log.data && console.groupEnd();
});
}
};
// polling dirty checker
// flush periodically if platform does not have object observe.
if (!Observer.hasObjectObserve) {
var FLUSH_POLL_INTERVAL = 125;
window.addEventListener('WebComponentsReady', function() {
flush();
// watch document visiblity to toggle dirty-checking
var visibilityHandler = function() {
// only flush if the page is visibile
if (document.visibilityState === 'hidden') {
if (scope.flushPoll) {
clearInterval(scope.flushPoll);
}
} else {
scope.flushPoll = setInterval(flush, FLUSH_POLL_INTERVAL);
}
};
if (typeof document.visibilityState === 'string') {
document.addEventListener('visibilitychange', visibilityHandler);
}
visibilityHandler();
});
} else {
// make flush a no-op when we have Object.observe
flush = function() {};
}
if (window.CustomElements && !CustomElements.useNative) {
var originalImportNode = Document.prototype.importNode;
Document.prototype.importNode = function(node, deep) {
var imported = originalImportNode.call(this, node, deep);
CustomElements.upgradeAll(imported);
return imported;
};
}
// exports
scope.flush = flush;
// bc
Platform.flush = flush;
})(window.Polymer);
(function(scope) {
var urlResolver = {
resolveDom: function(root, url) {
url = url || baseUrl(root);
this.resolveAttributes(root, url);
this.resolveStyles(root, url);
// handle template.content
var templates = root.querySelectorAll('template');
if (templates) {
for (var i = 0, l = templates.length, t; (i < l) && (t = templates[i]); i++) {
if (t.content) {
this.resolveDom(t.content, url);
}
}
}
},
resolveTemplate: function(template) {
this.resolveDom(template.content, baseUrl(template));
},
resolveStyles: function(root, url) {
var styles = root.querySelectorAll('style');
if (styles) {
for (var i = 0, l = styles.length, s; (i < l) && (s = styles[i]); i++) {
this.resolveStyle(s, url);
}
}
},
resolveStyle: function(style, url) {
url = url || baseUrl(style);
style.textContent = this.resolveCssText(style.textContent, url);
},
resolveCssText: function(cssText, baseUrl, keepAbsolute) {
cssText = replaceUrlsInCssText(cssText, baseUrl, keepAbsolute, CSS_URL_REGEXP);
return replaceUrlsInCssText(cssText, baseUrl, keepAbsolute, CSS_IMPORT_REGEXP);
},
resolveAttributes: function(root, url) {
if (root.hasAttributes && root.hasAttributes()) {
this.resolveElementAttributes(root, url);
}
// search for attributes that host urls
var nodes = root && root.querySelectorAll(URL_ATTRS_SELECTOR);
if (nodes) {
for (var i = 0, l = nodes.length, n; (i < l) && (n = nodes[i]); i++) {
this.resolveElementAttributes(n, url);
}
}
},
resolveElementAttributes: function(node, url) {
url = url || baseUrl(node);
URL_ATTRS.forEach(function(v) {
var attr = node.attributes[v];
var value = attr && attr.value;
var replacement;
if (value && value.search(URL_TEMPLATE_SEARCH) < 0) {
if (v === 'style') {
replacement = replaceUrlsInCssText(value, url, false, CSS_URL_REGEXP);
} else {
replacement = resolveRelativeUrl(url, value);
}
attr.value = replacement;
}
});
}
};
var CSS_URL_REGEXP = /(url\()([^)]*)(\))/g;
var CSS_IMPORT_REGEXP = /(@import[\s]+(?!url\())([^;]*)(;)/g;
var URL_ATTRS = ['href', 'src', 'action', 'style', 'url'];
var URL_ATTRS_SELECTOR = '[' + URL_ATTRS.join('],[') + ']';
var URL_TEMPLATE_SEARCH = '{{.*}}';
var URL_HASH = '#';
function baseUrl(node) {
var u = new URL(node.ownerDocument.baseURI);
u.search = '';
u.hash = '';
return u;
}
function replaceUrlsInCssText(cssText, baseUrl, keepAbsolute, regexp) {
return cssText.replace(regexp, function(m, pre, url, post) {
var urlPath = url.replace(/["']/g, '');
urlPath = resolveRelativeUrl(baseUrl, urlPath, keepAbsolute);
return pre + '\'' + urlPath + '\'' + post;
});
}
function resolveRelativeUrl(baseUrl, url, keepAbsolute) {
// do not resolve '/' absolute urls
if (url && url[0] === '/') {
return url;
}
// do not resolve '#' links, they are used for routing
if (url && url[0] === '#') {
return url;
}
var u = new URL(url, baseUrl);
return keepAbsolute ? u.href : makeDocumentRelPath(u.href);
}
function makeDocumentRelPath(url) {
var root = baseUrl(document.documentElement);
var u = new URL(url, root);
if (u.host === root.host && u.port === root.port &&
u.protocol === root.protocol) {
return makeRelPath(root, u);
} else {
return url;
}
}
// make a relative path from source to target
function makeRelPath(sourceUrl, targetUrl) {
var source = sourceUrl.pathname;
var target = targetUrl.pathname;
var s = source.split('/');
var t = target.split('/');
while (s.length && s[0] === t[0]){
s.shift();
t.shift();
}
for (var i = 0, l = s.length - 1; i < l; i++) {
t.unshift('..');
}
// empty '#' is discarded but we need to preserve it.
var hash = (targetUrl.href.slice(-1) === URL_HASH) ? URL_HASH : targetUrl.hash;
return t.join('/') + targetUrl.search + hash;
}
// exports
scope.urlResolver = urlResolver;
})(Polymer);
(function(scope) {
var endOfMicrotask = Polymer.endOfMicrotask;
// Generic url loader
function Loader(regex) {
this.cache = Object.create(null);
this.map = Object.create(null);
this.requests = 0;
this.regex = regex;
}
Loader.prototype = {
// TODO(dfreedm): there may be a better factoring here
// extract absolute urls from the text (full of relative urls)
extractUrls: function(text, base) {
var matches = [];
var matched, u;
while ((matched = this.regex.exec(text))) {
u = new URL(matched[1], base);
matches.push({matched: matched[0], url: u.href});
}
return matches;
},
// take a text blob, a root url, and a callback and load all the urls found within the text
// returns a map of absolute url to text
process: function(text, root, callback) {
var matches = this.extractUrls(text, root);
// every call to process returns all the text this loader has ever received
var done = callback.bind(null, this.map);
this.fetch(matches, done);
},
// build a mapping of url -> text from matches
fetch: function(matches, callback) {
var inflight = matches.length;
// return early if there is no fetching to be done
if (!inflight) {
return callback();
}
// wait for all subrequests to return
var done = function() {
if (--inflight === 0) {
callback();
}
};
// start fetching all subrequests
var m, req, url;
for (var i = 0; i < inflight; i++) {
m = matches[i];
url = m.url;
req = this.cache[url];
// if this url has already been requested, skip requesting it again
if (!req) {
req = this.xhr(url);
req.match = m;
this.cache[url] = req;
}
// wait for the request to process its subrequests
req.wait(done);
}
},
handleXhr: function(request) {
var match = request.match;
var url = match.url;
// handle errors with an empty string
var response = request.response || request.responseText || '';
this.map[url] = response;
this.fetch(this.extractUrls(response, url), request.resolve);
},
xhr: function(url) {
this.requests++;
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.send();
request.onerror = request.onload = this.handleXhr.bind(this, request);
// queue of tasks to run after XHR returns
request.pending = [];
request.resolve = function() {
var pending = request.pending;
for(var i = 0; i < pending.length; i++) {
pending[i]();
}
request.pending = null;
};
// if we have already resolved, pending is null, async call the callback
request.wait = function(fn) {
if (request.pending) {
request.pending.push(fn);
} else {
endOfMicrotask(fn);
}
};
return request;
}
};
scope.Loader = Loader;
})(Polymer);
(function(scope) {
var urlResolver = scope.urlResolver;
var Loader = scope.Loader;
function StyleResolver() {
this.loader = new Loader(this.regex);
}
StyleResolver.prototype = {
regex: /@import\s+(?:url)?["'\(]*([^'"\)]*)['"\)]*;/g,
// Recursively replace @imports with the text at that url
resolve: function(text, url, callback) {
var done = function(map) {
callback(this.flatten(text, url, map));
}.bind(this);
this.loader.process(text, url, done);
},
// resolve the textContent of a style node
resolveNode: function(style, url, callback) {
var text = style.textContent;
var done = function(text) {
style.textContent = text;
callback(style);
};
this.resolve(text, url, done);
},
// flatten all the @imports to text
flatten: function(text, base, map) {
var matches = this.loader.extractUrls(text, base);
var match, url, intermediate;
for (var i = 0; i < matches.length; i++) {
match = matches[i];
url = match.url;
// resolve any css text to be relative to the importer, keep absolute url
intermediate = urlResolver.resolveCssText(map[url], url, true);
// flatten intermediate @imports
intermediate = this.flatten(intermediate, base, map);
text = text.replace(match.matched, intermediate);
}
return text;
},
loadStyles: function(styles, base, callback) {
var loaded=0, l = styles.length;
// called in the context of the style
function loadedStyle(style) {
loaded++;
if (loaded === l && callback) {
callback();
}
}
for (var i=0, s; (i<l) && (s=styles[i]); i++) {
this.resolveNode(s, base, loadedStyle);
}
}
};
var styleResolver = new StyleResolver();
// exports
scope.styleResolver = styleResolver;
})(Polymer);
(function(scope) {
// copy own properties from 'api' to 'prototype, with name hinting for 'super'
function extend(prototype, api) {
if (prototype && api) {
// use only own properties of 'api'
Object.getOwnPropertyNames(api).forEach(function(n) {
// acquire property descriptor
var pd = Object.getOwnPropertyDescriptor(api, n);
if (pd) {
// clone property via descriptor
Object.defineProperty(prototype, n, pd);
// cache name-of-method for 'super' engine
if (typeof pd.value == 'function') {
// hint the 'super' engine
pd.value.nom = n;
}
}
});
}
return prototype;
}
// mixin
// copy all properties from inProps (et al) to inObj
function mixin(inObj/*, inProps, inMoreProps, ...*/) {
var obj = inObj || {};
for (var i = 1; i < arguments.length; i++) {
var p = arguments[i];
try {
for (var n in p) {
copyProperty(n, p, obj);
}
} catch(x) {
}
}
return obj;
}
// copy property inName from inSource object to inTarget object
function copyProperty(inName, inSource, inTarget) {
var pd = getPropertyDescriptor(inSource, inName);
Object.defineProperty(inTarget, inName, pd);
}
// get property descriptor for inName on inObject, even if
// inName exists on some link in inObject's prototype chain
function getPropertyDescriptor(inObject, inName) {
if (inObject) {
var pd = Object.getOwnPropertyDescriptor(inObject, inName);
return pd || getPropertyDescriptor(Object.getPrototypeOf(inObject), inName);
}
}
// exports
scope.extend = extend;
scope.mixin = mixin;
// for bc
Platform.mixin = mixin;
})(Polymer);
(function(scope) {
// usage
// invoke cb.call(this) in 100ms, unless the job is re-registered,
// which resets the timer
//
// this.myJob = this.job(this.myJob, cb, 100)
//
// returns a job handle which can be used to re-register a job
var Job = function(inContext) {
this.context = inContext;
this.boundComplete = this.complete.bind(this)
};
Job.prototype = {
go: function(callback, wait) {
this.callback = callback;
var h;
if (!wait) {
h = requestAnimationFrame(this.boundComplete);
this.handle = function() {
cancelAnimationFrame(h);
}
} else {
h = setTimeout(this.boundComplete, wait);
this.handle = function() {
clearTimeout(h);
}
}
},
stop: function() {
if (this.handle) {
this.handle();
this.handle = null;
}
},
complete: function() {
if (this.handle) {
this.stop();
this.callback.call(this.context);
}
}
};
function job(job, callback, wait) {
if (job) {
job.stop();
} else {
job = new Job(this);
}
job.go(callback, wait);
return job;
}
// exports
scope.job = job;
})(Polymer);
(function(scope) {
// dom polyfill, additions, and utility methods
var registry = {};
HTMLElement.register = function(tag, prototype) {
registry[tag] = prototype;
};
// get prototype mapped to node <tag>
HTMLElement.getPrototypeForTag = function(tag) {
var prototype = !tag ? HTMLElement.prototype : registry[tag];
// TODO(sjmiles): creating <tag> is likely to have wasteful side-effects
return prototype || Object.getPrototypeOf(document.createElement(tag));
};
// we have to flag propagation stoppage for the event dispatcher
var originalStopPropagation = Event.prototype.stopPropagation;
Event.prototype.stopPropagation = function() {
this.cancelBubble = true;
originalStopPropagation.apply(this, arguments);
};
// polyfill DOMTokenList
// * add/remove: allow these methods to take multiple classNames
// * toggle: add a 2nd argument which forces the given state rather
// than toggling.
var add = DOMTokenList.prototype.add;
var remove = DOMTokenList.prototype.remove;
DOMTokenList.prototype.add = function() {
for (var i = 0; i < arguments.length; i++) {
add.call(this, arguments[i]);
}
};
DOMTokenList.prototype.remove = function() {
for (var i = 0; i < arguments.length; i++) {
remove.call(this, arguments[i]);
}
};
DOMTokenList.prototype.toggle = function(name, bool) {
if (arguments.length == 1) {
bool = !this.contains(name);
}
bool ? this.add(name) : this.remove(name);
};
DOMTokenList.prototype.switch = function(oldName, newName) {
oldName && this.remove(oldName);
newName && this.add(newName);
};
// add array() to NodeList, NamedNodeMap, HTMLCollection
var ArraySlice = function() {
return Array.prototype.slice.call(this);
};
var namedNodeMap = (window.NamedNodeMap || window.MozNamedAttrMap || {});
NodeList.prototype.array = ArraySlice;
namedNodeMap.prototype.array = ArraySlice;
HTMLCollection.prototype.array = ArraySlice;
// utility
function createDOM(inTagOrNode, inHTML, inAttrs) {
var dom = typeof inTagOrNode == 'string' ?
document.createElement(inTagOrNode) : inTagOrNode.cloneNode(true);
dom.innerHTML = inHTML;
if (inAttrs) {
for (var n in inAttrs) {
dom.setAttribute(n, inAttrs[n]);
}
}
return dom;
}
// exports
scope.createDOM = createDOM;
})(Polymer);
(function(scope) {
// super
// `arrayOfArgs` is an optional array of args like one might pass
// to `Function.apply`
// TODO(sjmiles):
// $super must be installed on an instance or prototype chain
// as `super`, and invoked via `this`, e.g.
// `this.super();`
// will not work if function objects are not unique, for example,
// when using mixins.
// The memoization strategy assumes each function exists on only one
// prototype chain i.e. we use the function object for memoizing)
// perhaps we can bookkeep on the prototype itself instead
function $super(arrayOfArgs) {
// since we are thunking a method call, performance is important here:
// memoize all lookups, once memoized the fast path calls no other
// functions
//
// find the caller (cannot be `strict` because of 'caller')
var caller = $super.caller;
// memoized 'name of method'
var nom = caller.nom;
// memoized next implementation prototype
var _super = caller._super;
if (!_super) {
if (!nom) {
nom = caller.nom = nameInThis.call(this, caller);
}
if (!nom) {
console.warn('called super() on a method not installed declaratively (has no .nom property)');
}
// super prototype is either cached or we have to find it
// by searching __proto__ (at the 'top')
// invariant: because we cache _super on fn below, we never reach
// here from inside a series of calls to super(), so it's ok to
// start searching from the prototype of 'this' (at the 'top')
// we must never memoize a null super for this reason
_super = memoizeSuper(caller, nom, getPrototypeOf(this));
}
// our super function
var fn = _super[nom];
if (fn) {
// memoize information so 'fn' can call 'super'
if (!fn._super) {
// must not memoize null, or we lose our invariant above
memoizeSuper(fn, nom, _super);
}
// invoke the inherited method
// if 'fn' is not function valued, this will throw
return fn.apply(this, arrayOfArgs || []);
}
}
function nameInThis(value) {
var p = this.__proto__;
while (p && p !== HTMLElement.prototype) {
// TODO(sjmiles): getOwnPropertyNames is absurdly expensive
var n$ = Object.getOwnPropertyNames(p);
for (var i=0, l=n$.length, n; i<l && (n=n$[i]); i++) {
var d = Object.getOwnPropertyDescriptor(p, n);
if (typeof d.value === 'function' && d.value === value) {
return n;
}
}
p = p.__proto__;
}
}
function memoizeSuper(method, name, proto) {
// find and cache next prototype containing `name`
// we need the prototype so we can do another lookup
// from here
var s = nextSuper(proto, name, method);
if (s[name]) {
// `s` is a prototype, the actual method is `s[name]`
// tag super method with it's name for quicker lookups
s[name].nom = name;
}
return method._super = s;
}
function nextSuper(proto, name, caller) {
// look for an inherited prototype that implements name
while (proto) {
if ((proto[name] !== caller) && proto[name]) {
return proto;
}
proto = getPrototypeOf(proto);
}
// must not return null, or we lose our invariant above
// in this case, a super() call was invoked where no superclass
// method exists
// TODO(sjmiles): thow an exception?
return Object;
}
// NOTE: In some platforms (IE10) the prototype chain is faked via
// __proto__. Therefore, always get prototype via __proto__ instead of
// the more standard Object.getPrototypeOf.
function getPrototypeOf(prototype) {
return prototype.__proto__;
}
// utility function to precompute name tags for functions
// in a (unchained) prototype
function hintSuper(prototype) {
// tag functions with their prototype name to optimize
// super call invocations
for (var n in prototype) {
var pd = Object.getOwnPropertyDescriptor(prototype, n);
if (pd && typeof pd.value === 'function') {
pd.value.nom = n;
}
}
}
// exports
scope.super = $super;
})(Polymer);
(function(scope) {
function noopHandler(value) {
return value;
}
// helper for deserializing properties of various types to strings
var typeHandlers = {
string: noopHandler,
'undefined': noopHandler,
date: function(value) {
return new Date(Date.parse(value) || Date.now());
},
boolean: function(value) {
if (value === '') {
return true;
}
return value === 'false' ? false : !!value;
},
number: function(value) {
var n = parseFloat(value);
// hex values like "0xFFFF" parseFloat as 0
if (n === 0) {
n = parseInt(value);
}
return isNaN(n) ? value : n;
// this code disabled because encoded values (like "0xFFFF")
// do not round trip to their original format
//return (String(floatVal) === value) ? floatVal : value;
},
object: function(value, currentValue) {
if (currentValue === null) {
return value;
}
try {
// If the string is an object, we can parse is with the JSON library.
// include convenience replace for single-quotes. If the author omits
// quotes altogether, parse will fail.
return JSON.parse(value.replace(/'/g, '"'));
} catch(e) {
// The object isn't valid JSON, return the raw value
return value;
}
},
// avoid deserialization of functions
'function': function(value, currentValue) {
return currentValue;
}
};
function deserializeValue(value, currentValue) {
// attempt to infer type from default value
var inferredType = typeof currentValue;
// invent 'date' type value for Date
if (currentValue instanceof Date) {
inferredType = 'date';
}
// delegate deserialization via type string
return typeHandlers[inferredType](value, currentValue);
}
// exports
scope.deserializeValue = deserializeValue;
})(Polymer);
(function(scope) {
// imports
var extend = scope.extend;
// module
var api = {};
api.declaration = {};
api.instance = {};
api.publish = function(apis, prototype) {
for (var n in apis) {
extend(prototype, apis[n]);
}
};
// exports
scope.api = api;
})(Polymer);
(function(scope) {
/**
* @class polymer-base
*/
var utils = {
/**
* Invokes a function asynchronously. The context of the callback
* function is bound to 'this' automatically. Returns a handle which may
* be passed to <a href="#cancelAsync">cancelAsync</a> to cancel the
* asynchronous call.
*
* @method async
* @param {Function|String} method
* @param {any|Array} args
* @param {number} timeout
*/
async: function(method, args, timeout) {
// when polyfilling Object.observe, ensure changes
// propagate before executing the async method
Polymer.flush();
// second argument to `apply` must be an array
args = (args && args.length) ? args : [args];
// function to invoke
var fn = function() {
(this[method] || method).apply(this, args);
}.bind(this);
// execute `fn` sooner or later
var handle = timeout ? setTimeout(fn, timeout) :
requestAnimationFrame(fn);
// NOTE: switch on inverting handle to determine which time is used.
return timeout ? handle : ~handle;
},
/**
* Cancels a pending callback that was scheduled via
* <a href="#async">async</a>.
*
* @method cancelAsync
* @param {handle} handle Handle of the `async` to cancel.
*/
cancelAsync: function(handle) {
if (handle < 0) {
cancelAnimationFrame(~handle);
} else {
clearTimeout(handle);
}
},
/**
* Fire an event.
*
* @method fire
* @returns {Object} event
* @param {string} type An event name.
* @param {any} detail
* @param {Node} onNode Target node.
* @param {Boolean} bubbles Set false to prevent bubbling, defaults to true
* @param {Boolean} cancelable Set false to prevent cancellation, defaults to true
*/
fire: function(type, detail, onNode, bubbles, cancelable) {
var node = onNode || this;
var detail = detail === null || detail === undefined ? {} : detail;
var event = new CustomEvent(type, {
bubbles: bubbles !== undefined ? bubbles : true,
cancelable: cancelable !== undefined ? cancelable : true,
detail: detail
});
node.dispatchEvent(event);
return event;
},
/**
* Fire an event asynchronously.
*
* @method asyncFire
* @param {string} type An event name.
* @param detail
* @param {Node} toNode Target node.
*/
asyncFire: function(/*inType, inDetail*/) {
this.async("fire", arguments);
},
/**
* Remove class from old, add class to anew, if they exist.
*
* @param classFollows
* @param anew A node.
* @param old A node
* @param className
*/
classFollows: function(anew, old, className) {
if (old) {
old.classList.remove(className);
}
if (anew) {
anew.classList.add(className);
}
},
/**
* Inject HTML which contains markup bound to this element into
* a target element (replacing target element content).
*
* @param String html to inject
* @param Element target element
*/
injectBoundHTML: function(html, element) {
var template = document.createElement('template');
template.innerHTML = html;
var fragment = this.instanceTemplate(template);
if (element) {
element.textContent = '';
element.appendChild(fragment);
}
return fragment;
}
};
// no-operation function for handy stubs
var nop = function() {};
// null-object for handy stubs
var nob = {};
// deprecated
utils.asyncMethod = utils.async;
// exports
scope.api.instance.utils = utils;
scope.nop = nop;
scope.nob = nob;
})(Polymer);
(function(scope) {
// imports
var log = window.WebComponents ? WebComponents.flags.log : {};
var EVENT_PREFIX = 'on-';
// instance events api
var events = {
// read-only
EVENT_PREFIX: EVENT_PREFIX,
// event listeners on host
addHostListeners: function() {
var events = this.eventDelegates;
log.events && (Object.keys(events).length > 0) && console.log('[%s] addHostListeners:', this.localName, events);
// NOTE: host events look like bindings but really are not;
// (1) we don't want the attribute to be set and (2) we want to support
// multiple event listeners ('host' and 'instance') and Node.bind
// by default supports 1 thing being bound.
for (var type in events) {
var methodName = events[type];
PolymerGestures.addEventListener(this, type, this.element.getEventHandler(this, this, methodName));
}
},
// call 'method' or function method on 'obj' with 'args', if the method exists
dispatchMethod: function(obj, method, args) {
if (obj) {
log.events && console.group('[%s] dispatch [%s]', obj.localName, method);
var fn = typeof method === 'function' ? method : obj[method];
if (fn) {
fn[args ? 'apply' : 'call'](obj, args);
}
log.events && console.groupEnd();
// NOTE: dirty check right after calling method to ensure
// changes apply quickly; in a very complicated app using high
// frequency events, this can be a perf concern; in this case,
// imperative handlers can be used to avoid flushing.
Polymer.flush();
}
}
};
// exports
scope.api.instance.events = events;
/**
* @class Polymer
*/
/**
* Add a gesture aware event handler to the given `node`. Can be used
* in place of `element.addEventListener` and ensures gestures will function
* as expected on mobile platforms. Please note that Polymer's declarative
* event handlers include this functionality by default.
*
* @method addEventListener
* @param {Node} node node on which to listen
* @param {String} eventType name of the event
* @param {Function} handlerFn event handler function
* @param {Boolean} capture set to true to invoke event capturing
* @type Function
*/
// alias PolymerGestures event listener logic
scope.addEventListener = function(node, eventType, handlerFn, capture) {
PolymerGestures.addEventListener(wrap(node), eventType, handlerFn, capture);
};
/**
* Remove a gesture aware event handler on the given `node`. To remove an
* event listener, the exact same arguments are required that were passed
* to `Polymer.addEventListener`.
*
* @method removeEventListener
* @param {Node} node node on which to listen
* @param {String} eventType name of the event
* @param {Function} handlerFn event handler function
* @param {Boolean} capture set to true to invoke event capturing
* @type Function
*/
scope.removeEventListener = function(node, eventType, handlerFn, capture) {
PolymerGestures.removeEventListener(wrap(node), eventType, handlerFn, capture);
};
})(Polymer);
(function(scope) {
// instance api for attributes
var attributes = {
// copy attributes defined in the element declaration to the instance
// e.g. <polymer-element name="x-foo" tabIndex="0"> tabIndex is copied
// to the element instance here.
copyInstanceAttributes: function () {
var a$ = this._instanceAttributes;
for (var k in a$) {
if (!this.hasAttribute(k)) {
this.setAttribute(k, a$[k]);
}
}
},
// for each attribute on this, deserialize value to property as needed
takeAttributes: function() {
// if we have no publish lookup table, we have no attributes to take
// TODO(sjmiles): ad hoc
if (this._publishLC) {
for (var i=0, a$=this.attributes, l=a$.length, a; (a=a$[i]) && i<l; i++) {
this.attributeToProperty(a.name, a.value);
}
}
},
// if attribute 'name' is mapped to a property, deserialize
// 'value' into that property
attributeToProperty: function(name, value) {
// try to match this attribute to a property (attributes are
// all lower-case, so this is case-insensitive search)
var name = this.propertyForAttribute(name);
if (name) {
// filter out 'mustached' values, these are to be
// replaced with bound-data and are not yet values
// themselves
if (value && value.search(scope.bindPattern) >= 0) {
return;
}
// get original value
var currentValue = this[name];
// deserialize Boolean or Number values from attribute
var value = this.deserializeValue(value, currentValue);
// only act if the value has changed
if (value !== currentValue) {
// install new value (has side-effects)
this[name] = value;
}
}
},
// return the published property matching name, or undefined
propertyForAttribute: function(name) {
var match = this._publishLC && this._publishLC[name];
return match;
},
// convert representation of `stringValue` based on type of `currentValue`
deserializeValue: function(stringValue, currentValue) {
return scope.deserializeValue(stringValue, currentValue);
},
// convert to a string value based on the type of `inferredType`
serializeValue: function(value, inferredType) {
if (inferredType === 'boolean') {
return value ? '' : undefined;
} else if (inferredType !== 'object' && inferredType !== 'function'
&& value !== undefined) {
return value;
}
},
// serializes `name` property value and updates the corresponding attribute
// note that reflection is opt-in.
reflectPropertyToAttribute: function(name) {
var inferredType = typeof this[name];
// try to intelligently serialize property value
var serializedValue = this.serializeValue(this[name], inferredType);
// boolean properties must reflect as boolean attributes
if (serializedValue !== undefined) {
this.setAttribute(name, serializedValue);
// TODO(sorvell): we should remove attr for all properties
// that have undefined serialization; however, we will need to
// refine the attr reflection system to achieve this; pica, for example,
// relies on having inferredType object properties not removed as
// attrs.
} else if (inferredType === 'boolean') {
this.removeAttribute(name);
}
}
};
// exports
scope.api.instance.attributes = attributes;
})(Polymer);
(function(scope) {
/**
* @class polymer-base
*/
// imports
var log = window.WebComponents ? WebComponents.flags.log : {};
// magic words
var OBSERVE_SUFFIX = 'Changed';
// element api
var empty = [];
var updateRecord = {
object: undefined,
type: 'update',
name: undefined,
oldValue: undefined
};
var numberIsNaN = Number.isNaN || function(value) {
return typeof value === 'number' && isNaN(value);
};
function areSameValue(left, right) {
if (left === right)
return left !== 0 || 1 / left === 1 / right;
if (numberIsNaN(left) && numberIsNaN(right))
return true;
return left !== left && right !== right;
}
// capture A's value if B's value is null or undefined,
// otherwise use B's value
function resolveBindingValue(oldValue, value) {
if (value === undefined && oldValue === null) {
return value;
}
return (value === null || value === undefined) ? oldValue : value;
}
var properties = {
// creates a CompoundObserver to observe property changes
// NOTE, this is only done there are any properties in the `observe` object
createPropertyObserver: function() {
var n$ = this._observeNames;
if (n$ && n$.length) {
var o = this._propertyObserver = new CompoundObserver(true);
this.registerObserver(o);
// TODO(sorvell): may not be kosher to access the value here (this[n]);
// previously we looked at the descriptor on the prototype
// this doesn't work for inheritance and not for accessors without
// a value property
for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) {
o.addPath(this, n);
this.observeArrayValue(n, this[n], null);
}
}
},
// start observing property changes
openPropertyObserver: function() {
if (this._propertyObserver) {
this._propertyObserver.open(this.notifyPropertyChanges, this);
}
},
// handler for property changes; routes changes to observing methods
// note: array valued properties are observed for array splices
notifyPropertyChanges: function(newValues, oldValues, paths) {
var name, method, called = {};
for (var i in oldValues) {
// note: paths is of form [object, path, object, path]
name = paths[2 * i + 1];
method = this.observe[name];
if (method) {
var ov = oldValues[i], nv = newValues[i];
// observes the value if it is an array
this.observeArrayValue(name, nv, ov);
if (!called[method]) {
// only invoke change method if one of ov or nv is not (undefined | null)
if ((ov !== undefined && ov !== null) || (nv !== undefined && nv !== null)) {
called[method] = true;
// TODO(sorvell): call method with the set of values it's expecting;
// e.g. 'foo bar': 'invalidate' expects the new and old values for
// foo and bar. Currently we give only one of these and then
// deliver all the arguments.
this.invokeMethod(method, [ov, nv, arguments]);
}
}
}
}
},
// call method iff it exists.
invokeMethod: function(method, args) {
var fn = this[method] || method;
if (typeof fn === 'function') {
fn.apply(this, args);
}
},
/**
* Force any pending property changes to synchronously deliver to
* handlers specified in the `observe` object.
* Note, normally changes are processed at microtask time.
*
* @method deliverChanges
*/
deliverChanges: function() {
if (this._propertyObserver) {
this._propertyObserver.deliver();
}
},
observeArrayValue: function(name, value, old) {
// we only care if there are registered side-effects
var callbackName = this.observe[name];
if (callbackName) {
// if we are observing the previous value, stop
if (Array.isArray(old)) {
log.observe && console.log('[%s] observeArrayValue: unregister observer [%s]', this.localName, name);
this.closeNamedObserver(name + '__array');
}
// if the new value is an array, being observing it
if (Array.isArray(value)) {
log.observe && console.log('[%s] observeArrayValue: register observer [%s]', this.localName, name, value);
var observer = new ArrayObserver(value);
observer.open(function(splices) {
this.invokeMethod(callbackName, [splices]);
}, this);
this.registerNamedObserver(name + '__array', observer);
}
}
},
emitPropertyChangeRecord: function(name, value, oldValue) {
var object = this;
if (areSameValue(value, oldValue)) {
return;
}
// invoke property change side effects
this._propertyChanged(name, value, oldValue);
// emit change record
if (!Observer.hasObjectObserve) {
return;
}
var notifier = this._objectNotifier;
if (!notifier) {
notifier = this._objectNotifier = Object.getNotifier(this);
}
updateRecord.object = this;
updateRecord.name = name;
updateRecord.oldValue = oldValue;
notifier.notify(updateRecord);
},
_propertyChanged: function(name, value, oldValue) {
if (this.reflect[name]) {
this.reflectPropertyToAttribute(name);
}
},
// creates a property binding (called via bind) to a published property.
bindProperty: function(property, observable, oneTime) {
if (oneTime) {
this[property] = observable;
return;
}
var computed = this.element.prototype.computed;
// Binding an "out-only" value to a computed property. Note that
// since this observer isn't opened, it doesn't need to be closed on
// cleanup.
if (computed && computed[property]) {
var privateComputedBoundValue = property + 'ComputedBoundObservable_';
this[privateComputedBoundValue] = observable;
return;
}
return this.bindToAccessor(property, observable, resolveBindingValue);
},
// NOTE property `name` must be published. This makes it an accessor.
bindToAccessor: function(name, observable, resolveFn) {
var privateName = name + '_';
var privateObservable = name + 'Observable_';
// Present for properties which are computed and published and have a
// bound value.
var privateComputedBoundValue = name + 'ComputedBoundObservable_';
this[privateObservable] = observable;
var oldValue = this[privateName];
// observable callback
var self = this;
function updateValue(value, oldValue) {
self[privateName] = value;
var setObserveable = self[privateComputedBoundValue];
if (setObserveable && typeof setObserveable.setValue == 'function') {
setObserveable.setValue(value);
}
self.emitPropertyChangeRecord(name, value, oldValue);
}
// resolve initial value
var value = observable.open(updateValue);
if (resolveFn && !areSameValue(oldValue, value)) {
var resolvedValue = resolveFn(oldValue, value);
if (!areSameValue(value, resolvedValue)) {
value = resolvedValue;
if (observable.setValue) {
observable.setValue(value);
}
}
}
updateValue(value, oldValue);
// register and return observable
var observer = {
close: function() {
observable.close();
self[privateObservable] = undefined;
self[privateComputedBoundValue] = undefined;
}
};
this.registerObserver(observer);
return observer;
},
createComputedProperties: function() {
if (!this._computedNames) {
return;
}
for (var i = 0; i < this._computedNames.length; i++) {
var name = this._computedNames[i];
var expressionText = this.computed[name];
try {
var expression = PolymerExpressions.getExpression(expressionText);
var observable = expression.getBinding(this, this.element.syntax);
this.bindToAccessor(name, observable);
} catch (ex) {
console.error('Failed to create computed property', ex);
}
}
},
// property bookkeeping
registerObserver: function(observer) {
if (!this._observers) {
this._observers = [observer];
return;
}
this._observers.push(observer);
},
closeObservers: function() {
if (!this._observers) {
return;
}
// observer array items are arrays of observers.
var observers = this._observers;
for (var i = 0; i < observers.length; i++) {
var observer = observers[i];
if (observer && typeof observer.close == 'function') {
observer.close();
}
}
this._observers = [];
},
// bookkeeping observers for memory management
registerNamedObserver: function(name, observer) {
var o$ = this._namedObservers || (this._namedObservers = {});
o$[name] = observer;
},
closeNamedObserver: function(name) {
var o$ = this._namedObservers;
if (o$ && o$[name]) {
o$[name].close();
o$[name] = null;
return true;
}
},
closeNamedObservers: function() {
if (this._namedObservers) {
for (var i in this._namedObservers) {
this.closeNamedObserver(i);
}
this._namedObservers = {};
}
}
};
// logging
var LOG_OBSERVE = '[%s] watching [%s]';
var LOG_OBSERVED = '[%s#%s] watch: [%s] now [%s] was [%s]';
var LOG_CHANGED = '[%s#%s] propertyChanged: [%s] now [%s] was [%s]';
// exports
scope.api.instance.properties = properties;
})(Polymer);
(function(scope) {
/**
* @class polymer-base
*/
// imports
var log = window.WebComponents ? WebComponents.flags.log : {};
// element api supporting mdv
var mdv = {
/**
* Creates dom cloned from the given template, instantiating bindings
* with this element as the template model and `PolymerExpressions` as the
* binding delegate.
*
* @method instanceTemplate
* @param {Template} template source template from which to create dom.
*/
instanceTemplate: function(template) {
// ensure template is decorated (lets' things like <tr template ...> work)
HTMLTemplateElement.decorate(template);
// ensure a default bindingDelegate
var syntax = this.syntax || (!template.bindingDelegate &&
this.element.syntax);
var dom = template.createInstance(this, syntax);
var observers = dom.bindings_;
for (var i = 0; i < observers.length; i++) {
this.registerObserver(observers[i]);
}
return dom;
},
// Called by TemplateBinding/NodeBind to setup a binding to the given
// property. It's overridden here to support property bindings
// in addition to attribute bindings that are supported by default.
bind: function(name, observable, oneTime) {
var property = this.propertyForAttribute(name);
if (!property) {
// TODO(sjmiles): this mixin method must use the special form
// of `super` installed by `mixinMethod` in declaration/prototype.js
return this.mixinSuper(arguments);
} else {
// use n-way Polymer binding
var observer = this.bindProperty(property, observable, oneTime);
// NOTE: reflecting binding information is typically required only for
// tooling. It has a performance cost so it's opt-in in Node.bind.
if (Platform.enableBindingsReflection && observer) {
observer.path = observable.path_;
this._recordBinding(property, observer);
}
if (this.reflect[property]) {
this.reflectPropertyToAttribute(property);
}
return observer;
}
},
_recordBinding: function(name, observer) {
this.bindings_ = this.bindings_ || {};
this.bindings_[name] = observer;
},
// Called by TemplateBinding when all bindings on an element have been
// executed. This signals that all element inputs have been gathered
// and it's safe to ready the element, create shadow-root and start
// data-observation.
bindFinished: function() {
this.makeElementReady();
},
// called at detached time to signal that an element's bindings should be
// cleaned up. This is done asynchronously so that users have the chance
// to call `cancelUnbindAll` to prevent unbinding.
asyncUnbindAll: function() {
if (!this._unbound) {
log.unbind && console.log('[%s] asyncUnbindAll', this.localName);
this._unbindAllJob = this.job(this._unbindAllJob, this.unbindAll, 0);
}
},
/**
* This method should rarely be used and only if
* <a href="#cancelUnbindAll">`cancelUnbindAll`</a> has been called to
* prevent element unbinding. In this case, the element's bindings will
* not be automatically cleaned up and it cannot be garbage collected
* by the system. If memory pressure is a concern or a
* large amount of elements need to be managed in this way, `unbindAll`
* can be called to deactivate the element's bindings and allow its
* memory to be reclaimed.
*
* @method unbindAll
*/
unbindAll: function() {
if (!this._unbound) {
this.closeObservers();
this.closeNamedObservers();
this._unbound = true;
}
},
/**
* Call in `detached` to prevent the element from unbinding when it is
* detached from the dom. The element is unbound as a cleanup step that
* allows its memory to be reclaimed.
* If `cancelUnbindAll` is used, consider calling
* <a href="#unbindAll">`unbindAll`</a> when the element is no longer
* needed. This will allow its memory to be reclaimed.
*
* @method cancelUnbindAll
*/
cancelUnbindAll: function() {
if (this._unbound) {
log.unbind && console.warn('[%s] already unbound, cannot cancel unbindAll', this.localName);
return;
}
log.unbind && console.log('[%s] cancelUnbindAll', this.localName);
if (this._unbindAllJob) {
this._unbindAllJob = this._unbindAllJob.stop();
}
}
};
function unbindNodeTree(node) {
forNodeTree(node, _nodeUnbindAll);
}
function _nodeUnbindAll(node) {
node.unbindAll();
}
function forNodeTree(node, callback) {
if (node) {
callback(node);
for (var child = node.firstChild; child; child = child.nextSibling) {
forNodeTree(child, callback);
}
}
}
var mustachePattern = /\{\{([^{}]*)}}/;
// exports
scope.bindPattern = mustachePattern;
scope.api.instance.mdv = mdv;
})(Polymer);
(function(scope) {
/**
* Common prototype for all Polymer Elements.
*
* @class polymer-base
* @homepage polymer.github.io
*/
var base = {
/**
* Tags this object as the canonical Base prototype.
*
* @property PolymerBase
* @type boolean
* @default true
*/
PolymerBase: true,
/**
* Debounce signals.
*
* Call `job` to defer a named signal, and all subsequent matching signals,
* until a wait time has elapsed with no new signal.
*
* debouncedClickAction: function(e) {
* // processClick only when it's been 100ms since the last click
* this.job('click', function() {
* this.processClick;
* }, 100);
* }
*
* @method job
* @param String {String} job A string identifier for the job to debounce.
* @param Function {Function} callback A function that is called (with `this` context) when the wait time elapses.
* @param Number {Number} wait Time in milliseconds (ms) after the last signal that must elapse before invoking `callback`
* @type Handle
*/
job: function(job, callback, wait) {
if (typeof job === 'string') {
var n = '___' + job;
this[n] = Polymer.job.call(this, this[n], callback, wait);
} else {
// TODO(sjmiles): suggest we deprecate this call signature
return Polymer.job.call(this, job, callback, wait);
}
},
/**
* Invoke a superclass method.
*
* Use `super()` to invoke the most recently overridden call to the
* currently executing function.
*
* To pass arguments through, use the literal `arguments` as the parameter
* to `super()`.
*
* nextPageAction: function(e) {
* // invoke the superclass version of `nextPageAction`
* this.super(arguments);
* }
*
* To pass custom arguments, arrange them in an array.
*
* appendSerialNo: function(value, serial) {
* // prefix the superclass serial number with our lot # before
* // invoking the superlcass
* return this.super([value, this.lotNo + serial])
* }
*
* @method super
* @type Any
* @param {args) An array of arguments to use when calling the superclass method, or null.
*/
super: Polymer.super,
/**
* Lifecycle method called when the element is instantiated.
*
* Override `created` to perform custom create-time tasks. No need to call
* super-class `created` unless you are extending another Polymer element.
* Created is called before the element creates `shadowRoot` or prepares
* data-observation.
*
* @method created
* @type void
*/
created: function() {
},
/**
* Lifecycle method called when the element has populated it's `shadowRoot`,
* prepared data-observation, and made itself ready for API interaction.
*
* @method ready
* @type void
*/
ready: function() {
},
/**
* Low-level lifecycle method called as part of standard Custom Elements
* operation. Polymer implements this method to provide basic default
* functionality. For custom create-time tasks, implement `created`
* instead, which is called immediately after `createdCallback`.
*
* @method createdCallback
*/
createdCallback: function() {
if (this.templateInstance && this.templateInstance.model) {
console.warn('Attributes on ' + this.localName + ' were data bound ' +
'prior to Polymer upgrading the element. This may result in ' +
'incorrect binding types.');
}
this.created();
this.prepareElement();
if (!this.ownerDocument.isStagingDocument) {
this.makeElementReady();
}
},
// system entry point, do not override
prepareElement: function() {
if (this._elementPrepared) {
console.warn('Element already prepared', this.localName);
return;
}
this._elementPrepared = true;
// storage for shadowRoots info
this.shadowRoots = {};
// install property observers
this.createPropertyObserver();
this.openPropertyObserver();
// install boilerplate attributes
this.copyInstanceAttributes();
// process input attributes
this.takeAttributes();
// add event listeners
this.addHostListeners();
},
// system entry point, do not override
makeElementReady: function() {
if (this._readied) {
return;
}
this._readied = true;
this.createComputedProperties();
this.parseDeclarations(this.__proto__);
// NOTE: Support use of the `unresolved` attribute to help polyfill
// custom elements' `:unresolved` feature.
this.removeAttribute('unresolved');
// user entry point
this.ready();
},
/**
* Low-level lifecycle method called as part of standard Custom Elements
* operation. Polymer implements this method to provide basic default
* functionality. For custom tasks in your element, implement `attributeChanged`
* instead, which is called immediately after `attributeChangedCallback`.
*
* @method attributeChangedCallback
*/
attributeChangedCallback: function(name, oldValue) {
// TODO(sjmiles): adhoc filter
if (name !== 'class' && name !== 'style') {
this.attributeToProperty(name, this.getAttribute(name));
}
if (this.attributeChanged) {
this.attributeChanged.apply(this, arguments);
}
},
/**
* Low-level lifecycle method called as part of standard Custom Elements
* operation. Polymer implements this method to provide basic default
* functionality. For custom create-time tasks, implement `attached`
* instead, which is called immediately after `attachedCallback`.
*
* @method attachedCallback
*/
attachedCallback: function() {
// when the element is attached, prevent it from unbinding.
this.cancelUnbindAll();
// invoke user action
if (this.attached) {
this.attached();
}
if (!this.hasBeenAttached) {
this.hasBeenAttached = true;
if (this.domReady) {
this.async('domReady');
}
}
},
/**
* Implement to access custom elements in dom descendants, ancestors,
* or siblings. Because custom elements upgrade in document order,
* elements accessed in `ready` or `attached` may not be upgraded. When
* `domReady` is called, all registered custom elements are guaranteed
* to have been upgraded.
*
* @method domReady
*/
/**
* Low-level lifecycle method called as part of standard Custom Elements
* operation. Polymer implements this method to provide basic default
* functionality. For custom create-time tasks, implement `detached`
* instead, which is called immediately after `detachedCallback`.
*
* @method detachedCallback
*/
detachedCallback: function() {
if (!this.preventDispose) {
this.asyncUnbindAll();
}
// invoke user action
if (this.detached) {
this.detached();
}
// TODO(sorvell): bc
if (this.leftView) {
this.leftView();
}
},
/**
* Walks the prototype-chain of this element and allows specific
* classes a chance to process static declarations.
*
* In particular, each polymer-element has it's own `template`.
* `parseDeclarations` is used to accumulate all element `template`s
* from an inheritance chain.
*
* `parseDeclaration` static methods implemented in the chain are called
* recursively, oldest first, with the `<polymer-element>` associated
* with the current prototype passed as an argument.
*
* An element may override this method to customize shadow-root generation.
*
* @method parseDeclarations
*/
parseDeclarations: function(p) {
if (p && p.element) {
this.parseDeclarations(p.__proto__);
p.parseDeclaration.call(this, p.element);
}
},
/**
* Perform init-time actions based on static information in the
* `<polymer-element>` instance argument.
*
* For example, the standard implementation locates the template associated
* with the given `<polymer-element>` and stamps it into a shadow-root to
* implement shadow inheritance.
*
* An element may override this method for custom behavior.
*
* @method parseDeclaration
*/
parseDeclaration: function(elementElement) {
var template = this.fetchTemplate(elementElement);
if (template) {
var root = this.shadowFromTemplate(template);
this.shadowRoots[elementElement.name] = root;
}
},
/**
* Given a `<polymer-element>`, find an associated template (if any) to be
* used for shadow-root generation.
*
* An element may override this method for custom behavior.
*
* @method fetchTemplate
*/
fetchTemplate: function(elementElement) {
return elementElement.querySelector('template');
},
/**
* Create a shadow-root in this host and stamp `template` as it's
* content.
*
* An element may override this method for custom behavior.
*
* @method shadowFromTemplate
*/
shadowFromTemplate: function(template) {
if (template) {
// make a shadow root
var root = this.createShadowRoot();
// stamp template
// which includes parsing and applying MDV bindings before being
// inserted (to avoid {{}} in attribute values)
// e.g. to prevent <img src="images/{{icon}}"> from generating a 404.
var dom = this.instanceTemplate(template);
// append to shadow dom
root.appendChild(dom);
// perform post-construction initialization tasks on shadow root
this.shadowRootReady(root, template);
// return the created shadow root
return root;
}
},
// utility function that stamps a <template> into light-dom
lightFromTemplate: function(template, refNode) {
if (template) {
// TODO(sorvell): mark this element as an eventController so that
// event listeners on bound nodes inside it will be called on it.
// Note, the expectation here is that events on all descendants
// should be handled by this element.
this.eventController = this;
// stamp template
// which includes parsing and applying MDV bindings before being
// inserted (to avoid {{}} in attribute values)
// e.g. to prevent <img src="images/{{icon}}"> from generating a 404.
var dom = this.instanceTemplate(template);
// append to shadow dom
if (refNode) {
this.insertBefore(dom, refNode);
} else {
this.appendChild(dom);
}
// perform post-construction initialization tasks on ahem, light root
this.shadowRootReady(this);
// return the created shadow root
return dom;
}
},
shadowRootReady: function(root) {
// locate nodes with id and store references to them in this.$ hash
this.marshalNodeReferences(root);
},
// locate nodes with id and store references to them in this.$ hash
marshalNodeReferences: function(root) {
// establish $ instance variable
var $ = this.$ = this.$ || {};
// populate $ from nodes with ID from the LOCAL tree
if (root) {
var n$ = root.querySelectorAll("[id]");
for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) {
$[n.id] = n;
};
}
},
/**
* Register a one-time callback when a child-list or sub-tree mutation
* occurs on node.
*
* For persistent callbacks, call onMutation from your listener.
*
* @method onMutation
* @param Node {Node} node Node to watch for mutations.
* @param Function {Function} listener Function to call on mutation. The function is invoked as `listener.call(this, observer, mutations);` where `observer` is the MutationObserver that triggered the notification, and `mutations` is the native mutation list.
*/
onMutation: function(node, listener) {
var observer = new MutationObserver(function(mutations) {
listener.call(this, observer, mutations);
observer.disconnect();
}.bind(this));
observer.observe(node, {childList: true, subtree: true});
}
};
/**
* @class Polymer
*/
/**
* Returns true if the object includes <a href="#polymer-base">polymer-base</a> in it's prototype chain.
*
* @method isBase
* @param Object {Object} object Object to test.
* @type Boolean
*/
function isBase(object) {
return object.hasOwnProperty('PolymerBase')
}
// name a base constructor for dev tools
/**
* The Polymer base-class constructor.
*
* @property Base
* @type Function
*/
function PolymerBase() {};
PolymerBase.prototype = base;
base.constructor = PolymerBase;
// exports
scope.Base = PolymerBase;
scope.isBase = isBase;
scope.api.instance.base = base;
})(Polymer);
(function(scope) {
// imports
var log = window.WebComponents ? WebComponents.flags.log : {};
var hasShadowDOMPolyfill = window.ShadowDOMPolyfill;
// magic words
var STYLE_SCOPE_ATTRIBUTE = 'element';
var STYLE_CONTROLLER_SCOPE = 'controller';
var styles = {
STYLE_SCOPE_ATTRIBUTE: STYLE_SCOPE_ATTRIBUTE,
/**
* Installs external stylesheets and <style> elements with the attribute
* polymer-scope='controller' into the scope of element. This is intended
* to be a called during custom element construction.
*/
installControllerStyles: function() {
// apply controller styles, but only if they are not yet applied
var scope = this.findStyleScope();
if (scope && !this.scopeHasNamedStyle(scope, this.localName)) {
// allow inherited controller styles
var proto = getPrototypeOf(this), cssText = '';
while (proto && proto.element) {
cssText += proto.element.cssTextForScope(STYLE_CONTROLLER_SCOPE);
proto = getPrototypeOf(proto);
}
if (cssText) {
this.installScopeCssText(cssText, scope);
}
}
},
installScopeStyle: function(style, name, scope) {
var scope = scope || this.findStyleScope(), name = name || '';
if (scope && !this.scopeHasNamedStyle(scope, this.localName + name)) {
var cssText = '';
if (style instanceof Array) {
for (var i=0, l=style.length, s; (i<l) && (s=style[i]); i++) {
cssText += s.textContent + '\n\n';
}
} else {
cssText = style.textContent;
}
this.installScopeCssText(cssText, scope, name);
}
},
installScopeCssText: function(cssText, scope, name) {
scope = scope || this.findStyleScope();
name = name || '';
if (!scope) {
return;
}
if (hasShadowDOMPolyfill) {
cssText = shimCssText(cssText, scope.host);
}
var style = this.element.cssTextToScopeStyle(cssText,
STYLE_CONTROLLER_SCOPE);
Polymer.applyStyleToScope(style, scope);
// cache that this style has been applied
this.styleCacheForScope(scope)[this.localName + name] = true;
},
findStyleScope: function(node) {
// find the shadow root that contains this element
var n = node || this;
while (n.parentNode) {
n = n.parentNode;
}
return n;
},
scopeHasNamedStyle: function(scope, name) {
var cache = this.styleCacheForScope(scope);
return cache[name];
},
styleCacheForScope: function(scope) {
if (hasShadowDOMPolyfill) {
var scopeName = scope.host ? scope.host.localName : scope.localName;
return polyfillScopeStyleCache[scopeName] || (polyfillScopeStyleCache[scopeName] = {});
} else {
return scope._scopeStyles = (scope._scopeStyles || {});
}
}
};
var polyfillScopeStyleCache = {};
// NOTE: use raw prototype traversal so that we ensure correct traversal
// on platforms where the protoype chain is simulated via __proto__ (IE10)
function getPrototypeOf(prototype) {
return prototype.__proto__;
}
function shimCssText(cssText, host) {
var name = '', is = false;
if (host) {
name = host.localName;
is = host.hasAttribute('is');
}
var selector = WebComponents.ShadowCSS.makeScopeSelector(name, is);
return WebComponents.ShadowCSS.shimCssText(cssText, selector);
}
// exports
scope.api.instance.styles = styles;
})(Polymer);
(function(scope) {
// imports
var extend = scope.extend;
var api = scope.api;
// imperative implementation: Polymer()
// specify an 'own' prototype for tag `name`
function element(name, prototype) {
if (typeof name !== 'string') {
var script = prototype || document._currentScript;
prototype = name;
name = script && script.parentNode && script.parentNode.getAttribute ?
script.parentNode.getAttribute('name') : '';
if (!name) {
throw 'Element name could not be inferred.';
}
}
if (getRegisteredPrototype(name)) {
throw 'Already registered (Polymer) prototype for element ' + name;
}
// cache the prototype
registerPrototype(name, prototype);
// notify the registrar waiting for 'name', if any
notifyPrototype(name);
}
// async prototype source
function waitingForPrototype(name, client) {
waitPrototype[name] = client;
}
var waitPrototype = {};
function notifyPrototype(name) {
if (waitPrototype[name]) {
waitPrototype[name].registerWhenReady();
delete waitPrototype[name];
}
}
// utility and bookkeeping
// maps tag names to prototypes, as registered with
// Polymer. Prototypes associated with a tag name
// using document.registerElement are available from
// HTMLElement.getPrototypeForTag().
// If an element was fully registered by Polymer, then
// Polymer.getRegisteredPrototype(name) ===
// HTMLElement.getPrototypeForTag(name)
var prototypesByName = {};
function registerPrototype(name, prototype) {
return prototypesByName[name] = prototype || {};
}
function getRegisteredPrototype(name) {
return prototypesByName[name];
}
function instanceOfType(element, type) {
if (typeof type !== 'string') {
return false;
}
var proto = HTMLElement.getPrototypeForTag(type);
var ctor = proto && proto.constructor;
if (!ctor) {
return false;
}
if (CustomElements.instanceof) {
return CustomElements.instanceof(element, ctor);
}
return element instanceof ctor;
}
// exports
scope.getRegisteredPrototype = getRegisteredPrototype;
scope.waitingForPrototype = waitingForPrototype;
scope.instanceOfType = instanceOfType;
// namespace shenanigans so we can expose our scope on the registration
// function
// make window.Polymer reference `element()`
window.Polymer = element;
// TODO(sjmiles): find a way to do this that is less terrible
// copy window.Polymer properties onto `element()`
extend(Polymer, scope);
// Under the HTMLImports polyfill, scripts in the main document
// do not block on imports; we want to allow calls to Polymer in the main
// document. WebComponents collects those calls until we can process them, which
// we do here.
if (WebComponents.consumeDeclarations) {
WebComponents.consumeDeclarations(function(declarations) {
if (declarations) {
for (var i=0, l=declarations.length, d; (i<l) && (d=declarations[i]); i++) {
element.apply(null, d);
}
}
});
}
})(Polymer);
(function(scope) {
/**
* @class polymer-base
*/
/**
* Resolve a url path to be relative to a `base` url. If unspecified, `base`
* defaults to the element's ownerDocument url. Can be used to resolve
* paths from element's in templates loaded in HTMLImports to be relative
* to the document containing the element. Polymer automatically does this for
* url attributes in element templates; however, if a url, for
* example, contains a binding, then `resolvePath` can be used to ensure it is
* relative to the element document. For example, in an element's template,
*
* <a href="{{resolvePath(path)}}">Resolved</a>
*
* @method resolvePath
* @param {String} url Url path to resolve.
* @param {String} base Optional base url against which to resolve, defaults
* to the element's ownerDocument url.
* returns {String} resolved url.
*/
var path = {
resolveElementPaths: function(node) {
Polymer.urlResolver.resolveDom(node);
},
addResolvePathApi: function() {
// let assetpath attribute modify the resolve path
var assetPath = this.getAttribute('assetpath') || '';
var root = new URL(assetPath, this.ownerDocument.baseURI);
this.prototype.resolvePath = function(urlPath, base) {
var u = new URL(urlPath, base || root);
return u.href;
};
}
};
// exports
scope.api.declaration.path = path;
})(Polymer);
(function(scope) {
// imports
var log = window.WebComponents ? WebComponents.flags.log : {};
var api = scope.api.instance.styles;
var STYLE_SCOPE_ATTRIBUTE = api.STYLE_SCOPE_ATTRIBUTE;
var hasShadowDOMPolyfill = window.ShadowDOMPolyfill;
// magic words
var STYLE_SELECTOR = 'style';
var STYLE_LOADABLE_MATCH = '@import';
var SHEET_SELECTOR = 'link[rel=stylesheet]';
var STYLE_GLOBAL_SCOPE = 'global';
var SCOPE_ATTR = 'polymer-scope';
var styles = {
// returns true if resources are loading
loadStyles: function(callback) {
var template = this.fetchTemplate();
var content = template && this.templateContent();
if (content) {
this.convertSheetsToStyles(content);
var styles = this.findLoadableStyles(content);
if (styles.length) {
var templateUrl = template.ownerDocument.baseURI;
return Polymer.styleResolver.loadStyles(styles, templateUrl, callback);
}
}
if (callback) {
callback();
}
},
convertSheetsToStyles: function(root) {
var s$ = root.querySelectorAll(SHEET_SELECTOR);
for (var i=0, l=s$.length, s, c; (i<l) && (s=s$[i]); i++) {
c = createStyleElement(importRuleForSheet(s, this.ownerDocument.baseURI),
this.ownerDocument);
this.copySheetAttributes(c, s);
s.parentNode.replaceChild(c, s);
}
},
copySheetAttributes: function(style, link) {
for (var i=0, a$=link.attributes, l=a$.length, a; (a=a$[i]) && i<l; i++) {
if (a.name !== 'rel' && a.name !== 'href') {
style.setAttribute(a.name, a.value);
}
}
},
findLoadableStyles: function(root) {
var loadables = [];
if (root) {
var s$ = root.querySelectorAll(STYLE_SELECTOR);
for (var i=0, l=s$.length, s; (i<l) && (s=s$[i]); i++) {
if (s.textContent.match(STYLE_LOADABLE_MATCH)) {
loadables.push(s);
}
}
}
return loadables;
},
/**
* Install external stylesheets loaded in <polymer-element> elements into the
* element's template.
* @param elementElement The <element> element to style.
*/
installSheets: function() {
this.cacheSheets();
this.cacheStyles();
this.installLocalSheets();
this.installGlobalStyles();
},
/**
* Remove all sheets from element and store for later use.
*/
cacheSheets: function() {
this.sheets = this.findNodes(SHEET_SELECTOR);
this.sheets.forEach(function(s) {
if (s.parentNode) {
s.parentNode.removeChild(s);
}
});
},
cacheStyles: function() {
this.styles = this.findNodes(STYLE_SELECTOR + '[' + SCOPE_ATTR + ']');
this.styles.forEach(function(s) {
if (s.parentNode) {
s.parentNode.removeChild(s);
}
});
},
/**
* Takes external stylesheets loaded in an <element> element and moves
* their content into a <style> element inside the <element>'s template.
* The sheet is then removed from the <element>. This is done only so
* that if the element is loaded in the main document, the sheet does
* not become active.
* Note, ignores sheets with the attribute 'polymer-scope'.
* @param elementElement The <element> element to style.
*/
installLocalSheets: function () {
var sheets = this.sheets.filter(function(s) {
return !s.hasAttribute(SCOPE_ATTR);
});
var content = this.templateContent();
if (content) {
var cssText = '';
sheets.forEach(function(sheet) {
cssText += cssTextFromSheet(sheet) + '\n';
});
if (cssText) {
var style = createStyleElement(cssText, this.ownerDocument);
content.insertBefore(style, content.firstChild);
}
}
},
findNodes: function(selector, matcher) {
var nodes = this.querySelectorAll(selector).array();
var content = this.templateContent();
if (content) {
var templateNodes = content.querySelectorAll(selector).array();
nodes = nodes.concat(templateNodes);
}
return matcher ? nodes.filter(matcher) : nodes;
},
/**
* Promotes external stylesheets and <style> elements with the attribute
* polymer-scope='global' into global scope.
* This is particularly useful for defining @keyframe rules which
* currently do not function in scoped or shadow style elements.
* (See wkb.ug/72462)
* @param elementElement The <element> element to style.
*/
// TODO(sorvell): remove when wkb.ug/72462 is addressed.
installGlobalStyles: function() {
var style = this.styleForScope(STYLE_GLOBAL_SCOPE);
applyStyleToScope(style, document.head);
},
cssTextForScope: function(scopeDescriptor) {
var cssText = '';
// handle stylesheets
var selector = '[' + SCOPE_ATTR + '=' + scopeDescriptor + ']';
var matcher = function(s) {
return matchesSelector(s, selector);
};
var sheets = this.sheets.filter(matcher);
sheets.forEach(function(sheet) {
cssText += cssTextFromSheet(sheet) + '\n\n';
});
// handle cached style elements
var styles = this.styles.filter(matcher);
styles.forEach(function(style) {
cssText += style.textContent + '\n\n';
});
return cssText;
},
styleForScope: function(scopeDescriptor) {
var cssText = this.cssTextForScope(scopeDescriptor);
return this.cssTextToScopeStyle(cssText, scopeDescriptor);
},
cssTextToScopeStyle: function(cssText, scopeDescriptor) {
if (cssText) {
var style = createStyleElement(cssText);
style.setAttribute(STYLE_SCOPE_ATTRIBUTE, this.getAttribute('name') +
'-' + scopeDescriptor);
return style;
}
}
};
function importRuleForSheet(sheet, baseUrl) {
var href = new URL(sheet.getAttribute('href'), baseUrl).href;
return '@import \'' + href + '\';';
}
function applyStyleToScope(style, scope) {
if (style) {
if (scope === document) {
scope = document.head;
}
if (hasShadowDOMPolyfill) {
scope = document.head;
}
// TODO(sorvell): necessary for IE
// see https://connect.microsoft.com/IE/feedback/details/790212/
// cloning-a-style-element-and-adding-to-document-produces
// -unexpected-result#details
// var clone = style.cloneNode(true);
var clone = createStyleElement(style.textContent);
var attr = style.getAttribute(STYLE_SCOPE_ATTRIBUTE);
if (attr) {
clone.setAttribute(STYLE_SCOPE_ATTRIBUTE, attr);
}
// TODO(sorvell): probably too brittle; try to figure out
// where to put the element.
var refNode = scope.firstElementChild;
if (scope === document.head) {
var selector = 'style[' + STYLE_SCOPE_ATTRIBUTE + ']';
var s$ = document.head.querySelectorAll(selector);
if (s$.length) {
refNode = s$[s$.length-1].nextElementSibling;
}
}
scope.insertBefore(clone, refNode);
}
}
function createStyleElement(cssText, scope) {
scope = scope || document;
scope = scope.createElement ? scope : scope.ownerDocument;
var style = scope.createElement('style');
style.textContent = cssText;
return style;
}
function cssTextFromSheet(sheet) {
return (sheet && sheet.__resource) || '';
}
function matchesSelector(node, inSelector) {
if (matches) {
return matches.call(node, inSelector);
}
}
var p = HTMLElement.prototype;
var matches = p.matches || p.matchesSelector || p.webkitMatchesSelector
|| p.mozMatchesSelector;
// exports
scope.api.declaration.styles = styles;
scope.applyStyleToScope = applyStyleToScope;
})(Polymer);
(function(scope) {
// imports
var log = window.WebComponents ? WebComponents.flags.log : {};
var api = scope.api.instance.events;
var EVENT_PREFIX = api.EVENT_PREFIX;
var mixedCaseEventTypes = {};
[
'webkitAnimationStart',
'webkitAnimationEnd',
'webkitTransitionEnd',
'DOMFocusOut',
'DOMFocusIn',
'DOMMouseScroll'
].forEach(function(e) {
mixedCaseEventTypes[e.toLowerCase()] = e;
});
// polymer-element declarative api: events feature
var events = {
parseHostEvents: function() {
// our delegates map
var delegates = this.prototype.eventDelegates;
// extract data from attributes into delegates
this.addAttributeDelegates(delegates);
},
addAttributeDelegates: function(delegates) {
// for each attribute
for (var i=0, a; a=this.attributes[i]; i++) {
// does it have magic marker identifying it as an event delegate?
if (this.hasEventPrefix(a.name)) {
// if so, add the info to delegates
delegates[this.removeEventPrefix(a.name)] = a.value.replace('{{', '')
.replace('}}', '').trim();
}
}
},
// starts with 'on-'
hasEventPrefix: function (n) {
return n && (n[0] === 'o') && (n[1] === 'n') && (n[2] === '-');
},
removeEventPrefix: function(n) {
return n.slice(prefixLength);
},
findController: function(node) {
while (node.parentNode) {
if (node.eventController) {
return node.eventController;
}
node = node.parentNode;
}
return node.host;
},
getEventHandler: function(controller, target, method) {
var events = this;
return function(e) {
if (!controller || !controller.PolymerBase) {
controller = events.findController(target);
}
var args = [e, e.detail, e.currentTarget];
controller.dispatchMethod(controller, method, args);
};
},
prepareEventBinding: function(pathString, name, node) {
if (!this.hasEventPrefix(name))
return;
var eventType = this.removeEventPrefix(name);
eventType = mixedCaseEventTypes[eventType] || eventType;
var events = this;
return function(model, node, oneTime) {
var handler = events.getEventHandler(undefined, node, pathString);
PolymerGestures.addEventListener(node, eventType, handler);
if (oneTime)
return;
// TODO(rafaelw): This is really pointless work. Aside from the cost
// of these allocations, NodeBind is going to setAttribute back to its
// current value. Fixing this would mean changing the TemplateBinding
// binding delegate API.
function bindingValue() {
return '{{ ' + pathString + ' }}';
}
return {
open: bindingValue,
discardChanges: bindingValue,
close: function() {
PolymerGestures.removeEventListener(node, eventType, handler);
}
};
};
}
};
var prefixLength = EVENT_PREFIX.length;
// exports
scope.api.declaration.events = events;
})(Polymer);
(function(scope) {
// element api
var observationBlacklist = ['attribute'];
var properties = {
inferObservers: function(prototype) {
// called before prototype.observe is chained to inherited object
var observe = prototype.observe, property;
for (var n in prototype) {
if (n.slice(-7) === 'Changed') {
property = n.slice(0, -7);
if (this.canObserveProperty(property)) {
if (!observe) {
observe = (prototype.observe = {});
}
observe[property] = observe[property] || n;
}
}
}
},
canObserveProperty: function(property) {
return (observationBlacklist.indexOf(property) < 0);
},
explodeObservers: function(prototype) {
// called before prototype.observe is chained to inherited object
var o = prototype.observe;
if (o) {
var exploded = {};
for (var n in o) {
var names = n.split(' ');
for (var i=0, ni; ni=names[i]; i++) {
exploded[ni] = o[n];
}
}
prototype.observe = exploded;
}
},
optimizePropertyMaps: function(prototype) {
if (prototype.observe) {
// construct name list
var a = prototype._observeNames = [];
for (var n in prototype.observe) {
var names = n.split(' ');
for (var i=0, ni; ni=names[i]; i++) {
a.push(ni);
}
}
}
if (prototype.publish) {
// construct name list
var a = prototype._publishNames = [];
for (var n in prototype.publish) {
a.push(n);
}
}
if (prototype.computed) {
// construct name list
var a = prototype._computedNames = [];
for (var n in prototype.computed) {
a.push(n);
}
}
},
publishProperties: function(prototype, base) {
// if we have any properties to publish
var publish = prototype.publish;
if (publish) {
// transcribe `publish` entries onto own prototype
this.requireProperties(publish, prototype, base);
// warn and remove accessor names that are broken on some browsers
this.filterInvalidAccessorNames(publish);
// construct map of lower-cased property names
prototype._publishLC = this.lowerCaseMap(publish);
}
var computed = prototype.computed;
if (computed) {
// warn and remove accessor names that are broken on some browsers
this.filterInvalidAccessorNames(computed);
}
},
// Publishing/computing a property where the name might conflict with a
// browser property is not currently supported to help users of Polymer
// avoid browser bugs:
//
// https://code.google.com/p/chromium/issues/detail?id=43394
// https://bugs.webkit.org/show_bug.cgi?id=49739
//
// We can lift this restriction when those bugs are fixed.
filterInvalidAccessorNames: function(propertyNames) {
for (var name in propertyNames) {
// Check if the name is in our blacklist.
if (this.propertyNameBlacklist[name]) {
console.warn('Cannot define property "' + name + '" for element "' +
this.name + '" because it has the same name as an HTMLElement ' +
'property, and not all browsers support overriding that. ' +
'Consider giving it a different name.');
// Remove the invalid accessor from the list.
delete propertyNames[name];
}
}
},
//
// `name: value` entries in the `publish` object may need to generate
// matching properties on the prototype.
//
// Values that are objects may have a `reflect` property, which
// signals that the value describes property control metadata.
// In metadata objects, the prototype default value (if any)
// is encoded in the `value` property.
//
// publish: {
// foo: 5,
// bar: {value: true, reflect: true},
// zot: {}
// }
//
// `reflect` metadata property controls whether changes to the property
// are reflected back to the attribute (default false).
//
// A value is stored on the prototype unless it's === `undefined`,
// in which case the base chain is checked for a value.
// If the basal value is also undefined, `null` is stored on the prototype.
//
// The reflection data is stored on another prototype object, `reflect`
// which also can be specified directly.
//
// reflect: {
// foo: true
// }
//
requireProperties: function(propertyInfos, prototype, base) {
// per-prototype storage for reflected properties
prototype.reflect = prototype.reflect || {};
// ensure a prototype value for each property
// and update the property's reflect to attribute status
for (var n in propertyInfos) {
var value = propertyInfos[n];
// value has metadata if it has a `reflect` property
if (value && value.reflect !== undefined) {
prototype.reflect[n] = Boolean(value.reflect);
value = value.value;
}
// only set a value if one is specified
if (value !== undefined) {
prototype[n] = value;
}
}
},
lowerCaseMap: function(properties) {
var map = {};
for (var n in properties) {
map[n.toLowerCase()] = n;
}
return map;
},
createPropertyAccessor: function(name, ignoreWrites) {
var proto = this.prototype;
var privateName = name + '_';
var privateObservable = name + 'Observable_';
proto[privateName] = proto[name];
Object.defineProperty(proto, name, {
get: function() {
var observable = this[privateObservable];
if (observable)
observable.deliver();
return this[privateName];
},
set: function(value) {
if (ignoreWrites) {
return this[privateName];
}
var observable = this[privateObservable];
if (observable) {
observable.setValue(value);
return;
}
var oldValue = this[privateName];
this[privateName] = value;
this.emitPropertyChangeRecord(name, value, oldValue);
return value;
},
configurable: true
});
},
createPropertyAccessors: function(prototype) {
var n$ = prototype._computedNames;
if (n$ && n$.length) {
for (var i=0, l=n$.length, n, fn; (i<l) && (n=n$[i]); i++) {
this.createPropertyAccessor(n, true);
}
}
var n$ = prototype._publishNames;
if (n$ && n$.length) {
for (var i=0, l=n$.length, n, fn; (i<l) && (n=n$[i]); i++) {
// If the property is computed and published, the accessor is created
// above.
if (!prototype.computed || !prototype.computed[n]) {
this.createPropertyAccessor(n);
}
}
}
},
// This list contains some property names that people commonly want to use,
// but won't work because of Chrome/Safari bugs. It isn't an exhaustive
// list. In particular it doesn't contain any property names found on
// subtypes of HTMLElement (e.g. name, value). Rather it attempts to catch
// some common cases.
propertyNameBlacklist: {
children: 1,
'class': 1,
id: 1,
hidden: 1,
style: 1,
title: 1,
}
};
// exports
scope.api.declaration.properties = properties;
})(Polymer);
(function(scope) {
// magic words
var ATTRIBUTES_ATTRIBUTE = 'attributes';
var ATTRIBUTES_REGEX = /\s|,/;
// attributes api
var attributes = {
inheritAttributesObjects: function(prototype) {
// chain our lower-cased publish map to the inherited version
this.inheritObject(prototype, 'publishLC');
// chain our instance attributes map to the inherited version
this.inheritObject(prototype, '_instanceAttributes');
},
publishAttributes: function(prototype, base) {
// merge names from 'attributes' attribute into the 'publish' object
var attributes = this.getAttribute(ATTRIBUTES_ATTRIBUTE);
if (attributes) {
// create a `publish` object if needed.
// the `publish` object is only relevant to this prototype, the
// publishing logic in `declaration/properties.js` is responsible for
// managing property values on the prototype chain.
// TODO(sjmiles): the `publish` object is later chained to it's
// ancestor object, presumably this is only for
// reflection or other non-library uses.
var publish = prototype.publish || (prototype.publish = {});
// names='a b c' or names='a,b,c'
var names = attributes.split(ATTRIBUTES_REGEX);
// record each name for publishing
for (var i=0, l=names.length, n; i<l; i++) {
// remove excess ws
n = names[i].trim();
// looks weird, but causes n to exist on `publish` if it does not;
// a more careful test would need expensive `in` operator
if (n && publish[n] === undefined) {
publish[n] = undefined;
}
}
}
},
// record clonable attributes from <element>
accumulateInstanceAttributes: function() {
// inherit instance attributes
var clonable = this.prototype._instanceAttributes;
// merge attributes from element
var a$ = this.attributes;
for (var i=0, l=a$.length, a; (i<l) && (a=a$[i]); i++) {
if (this.isInstanceAttribute(a.name)) {
clonable[a.name] = a.value;
}
}
},
isInstanceAttribute: function(name) {
return !this.blackList[name] && name.slice(0,3) !== 'on-';
},
// do not clone these attributes onto instances
blackList: {
name: 1,
'extends': 1,
constructor: 1,
noscript: 1,
assetpath: 1,
'cache-csstext': 1
}
};
// add ATTRIBUTES_ATTRIBUTE to the blacklist
attributes.blackList[ATTRIBUTES_ATTRIBUTE] = 1;
// exports
scope.api.declaration.attributes = attributes;
})(Polymer);
(function(scope) {
// imports
var events = scope.api.declaration.events;
var syntax = new PolymerExpressions();
var prepareBinding = syntax.prepareBinding;
// Polymer takes a first crack at the binding to see if it's a declarative
// event handler.
syntax.prepareBinding = function(pathString, name, node) {
return events.prepareEventBinding(pathString, name, node) ||
prepareBinding.call(syntax, pathString, name, node);
};
// declaration api supporting mdv
var mdv = {
syntax: syntax,
fetchTemplate: function() {
return this.querySelector('template');
},
templateContent: function() {
var template = this.fetchTemplate();
return template && template.content;
},
installBindingDelegate: function(template) {
if (template) {
template.bindingDelegate = this.syntax;
}
}
};
// exports
scope.api.declaration.mdv = mdv;
})(Polymer);
(function(scope) {
// imports
var api = scope.api;
var isBase = scope.isBase;
var extend = scope.extend;
var hasShadowDOMPolyfill = window.ShadowDOMPolyfill;
// prototype api
var prototype = {
register: function(name, extendeeName) {
// build prototype combining extendee, Polymer base, and named api
this.buildPrototype(name, extendeeName);
// register our custom element with the platform
this.registerPrototype(name, extendeeName);
// reference constructor in a global named by 'constructor' attribute
this.publishConstructor();
},
buildPrototype: function(name, extendeeName) {
// get our custom prototype (before chaining)
var extension = scope.getRegisteredPrototype(name);
// get basal prototype
var base = this.generateBasePrototype(extendeeName);
// implement declarative features
this.desugarBeforeChaining(extension, base);
// join prototypes
this.prototype = this.chainPrototypes(extension, base);
// more declarative features
this.desugarAfterChaining(name, extendeeName);
},
desugarBeforeChaining: function(prototype, base) {
// back reference declaration element
// TODO(sjmiles): replace `element` with `elementElement` or `declaration`
prototype.element = this;
// transcribe `attributes` declarations onto own prototype's `publish`
this.publishAttributes(prototype, base);
// `publish` properties to the prototype and to attribute watch
this.publishProperties(prototype, base);
// infer observers for `observe` list based on method names
this.inferObservers(prototype);
// desugar compound observer syntax, e.g. 'a b c'
this.explodeObservers(prototype);
},
chainPrototypes: function(prototype, base) {
// chain various meta-data objects to inherited versions
this.inheritMetaData(prototype, base);
// chain custom api to inherited
var chained = this.chainObject(prototype, base);
// x-platform fixup
ensurePrototypeTraversal(chained);
return chained;
},
inheritMetaData: function(prototype, base) {
// chain observe object to inherited
this.inheritObject('observe', prototype, base);
// chain publish object to inherited
this.inheritObject('publish', prototype, base);
// chain reflect object to inherited
this.inheritObject('reflect', prototype, base);
// chain our lower-cased publish map to the inherited version
this.inheritObject('_publishLC', prototype, base);
// chain our instance attributes map to the inherited version
this.inheritObject('_instanceAttributes', prototype, base);
// chain our event delegates map to the inherited version
this.inheritObject('eventDelegates', prototype, base);
},
// implement various declarative features
desugarAfterChaining: function(name, extendee) {
// build side-chained lists to optimize iterations
this.optimizePropertyMaps(this.prototype);
this.createPropertyAccessors(this.prototype);
// install mdv delegate on template
this.installBindingDelegate(this.fetchTemplate());
// install external stylesheets as if they are inline
this.installSheets();
// adjust any paths in dom from imports
this.resolveElementPaths(this);
// compile list of attributes to copy to instances
this.accumulateInstanceAttributes();
// parse on-* delegates declared on `this` element
this.parseHostEvents();
//
// install a helper method this.resolvePath to aid in
// setting resource urls. e.g.
// this.$.image.src = this.resolvePath('images/foo.png')
this.addResolvePathApi();
// under ShadowDOMPolyfill, transforms to approximate missing CSS features
if (hasShadowDOMPolyfill) {
WebComponents.ShadowCSS.shimStyling(this.templateContent(), name,
extendee);
}
// allow custom element access to the declarative context
if (this.prototype.registerCallback) {
this.prototype.registerCallback(this);
}
},
// if a named constructor is requested in element, map a reference
// to the constructor to the given symbol
publishConstructor: function() {
var symbol = this.getAttribute('constructor');
if (symbol) {
window[symbol] = this.ctor;
}
},
// build prototype combining extendee, Polymer base, and named api
generateBasePrototype: function(extnds) {
var prototype = this.findBasePrototype(extnds);
if (!prototype) {
// create a prototype based on tag-name extension
var prototype = HTMLElement.getPrototypeForTag(extnds);
// insert base api in inheritance chain (if needed)
prototype = this.ensureBaseApi(prototype);
// memoize this base
memoizedBases[extnds] = prototype;
}
return prototype;
},
findBasePrototype: function(name) {
return memoizedBases[name];
},
// install Polymer instance api into prototype chain, as needed
ensureBaseApi: function(prototype) {
if (prototype.PolymerBase) {
return prototype;
}
var extended = Object.create(prototype);
// we need a unique copy of base api for each base prototype
// therefore we 'extend' here instead of simply chaining
api.publish(api.instance, extended);
// TODO(sjmiles): sharing methods across prototype chains is
// not supported by 'super' implementation which optimizes
// by memoizing prototype relationships.
// Probably we should have a version of 'extend' that is
// share-aware: it could study the text of each function,
// look for usage of 'super', and wrap those functions in
// closures.
// As of now, there is only one problematic method, so
// we just patch it manually.
// To avoid re-entrancy problems, the special super method
// installed is called `mixinSuper` and the mixin method
// must use this method instead of the default `super`.
this.mixinMethod(extended, prototype, api.instance.mdv, 'bind');
// return buffed-up prototype
return extended;
},
mixinMethod: function(extended, prototype, api, name) {
var $super = function(args) {
return prototype[name].apply(this, args);
};
extended[name] = function() {
this.mixinSuper = $super;
return api[name].apply(this, arguments);
}
},
// ensure prototype[name] inherits from a prototype.prototype[name]
inheritObject: function(name, prototype, base) {
// require an object
var source = prototype[name] || {};
// chain inherited properties onto a new object
prototype[name] = this.chainObject(source, base[name]);
},
// register 'prototype' to custom element 'name', store constructor
registerPrototype: function(name, extendee) {
var info = {
prototype: this.prototype
}
// native element must be specified in extends
var typeExtension = this.findTypeExtension(extendee);
if (typeExtension) {
info.extends = typeExtension;
}
// register the prototype with HTMLElement for name lookup
HTMLElement.register(name, this.prototype);
// register the custom type
this.ctor = document.registerElement(name, info);
},
findTypeExtension: function(name) {
if (name && name.indexOf('-') < 0) {
return name;
} else {
var p = this.findBasePrototype(name);
if (p.element) {
return this.findTypeExtension(p.element.extends);
}
}
}
};
// memoize base prototypes
var memoizedBases = {};
// implementation of 'chainObject' depends on support for __proto__
if (Object.__proto__) {
prototype.chainObject = function(object, inherited) {
if (object && inherited && object !== inherited) {
object.__proto__ = inherited;
}
return object;
}
} else {
prototype.chainObject = function(object, inherited) {
if (object && inherited && object !== inherited) {
var chained = Object.create(inherited);
object = extend(chained, object);
}
return object;
}
}
// On platforms that do not support __proto__ (versions of IE), the prototype
// chain of a custom element is simulated via installation of __proto__.
// Although custom elements manages this, we install it here so it's
// available during desugaring.
function ensurePrototypeTraversal(prototype) {
if (!Object.__proto__) {
var ancestor = Object.getPrototypeOf(prototype);
prototype.__proto__ = ancestor;
if (isBase(ancestor)) {
ancestor.__proto__ = Object.getPrototypeOf(ancestor);
}
}
}
// exports
api.declaration.prototype = prototype;
})(Polymer);
(function(scope) {
/*
Elements are added to a registration queue so that they register in
the proper order at the appropriate time. We do this for a few reasons:
* to enable elements to load resources (like stylesheets)
asynchronously. We need to do this until the platform provides an efficient
alternative. One issue is that remote @import stylesheets are
re-fetched whenever stamped into a shadowRoot.
* to ensure elements loaded 'at the same time' (e.g. via some set of
imports) are registered as a batch. This allows elements to be enured from
upgrade ordering as long as they query the dom tree 1 task after
upgrade (aka domReady). This is a performance tradeoff. On the one hand,
elements that could register while imports are loading are prevented from
doing so. On the other, grouping upgrades into a single task means less
incremental work (for example style recalcs), Also, we can ensure the
document is in a known state at the single quantum of time when
elements upgrade.
*/
var queue = {
// tell the queue to wait for an element to be ready
wait: function(element) {
if (!element.__queue) {
element.__queue = {};
elements.push(element);
}
},
// enqueue an element to the next spot in the queue.
enqueue: function(element, check, go) {
var shouldAdd = element.__queue && !element.__queue.check;
if (shouldAdd) {
queueForElement(element).push(element);
element.__queue.check = check;
element.__queue.go = go;
}
return (this.indexOf(element) !== 0);
},
indexOf: function(element) {
var i = queueForElement(element).indexOf(element);
if (i >= 0 && document.contains(element)) {
i += (HTMLImports.useNative || HTMLImports.ready) ?
importQueue.length : 1e9;
}
return i;
},
// tell the queue an element is ready to be registered
go: function(element) {
var readied = this.remove(element);
if (readied) {
element.__queue.flushable = true;
this.addToFlushQueue(readied);
this.check();
}
},
remove: function(element) {
var i = this.indexOf(element);
if (i !== 0) {
//console.warn('queue order wrong', i);
return;
}
return queueForElement(element).shift();
},
check: function() {
// next
var element = this.nextElement();
if (element) {
element.__queue.check.call(element);
}
if (this.canReady()) {
this.ready();
return true;
}
},
nextElement: function() {
return nextQueued();
},
canReady: function() {
return !this.waitToReady && this.isEmpty();
},
isEmpty: function() {
for (var i=0, l=elements.length, e; (i<l) &&
(e=elements[i]); i++) {
if (e.__queue && !e.__queue.flushable) {
return;
}
}
return true;
},
addToFlushQueue: function(element) {
flushQueue.push(element);
},
flush: function() {
// prevent re-entrance
if (this.flushing) {
return;
}
this.flushing = true;
var element;
while (flushQueue.length) {
element = flushQueue.shift();
element.__queue.go.call(element);
element.__queue = null;
}
this.flushing = false;
},
ready: function() {
// TODO(sorvell): As an optimization, turn off CE polyfill upgrading
// while registering. This way we avoid having to upgrade each document
// piecemeal per registration and can instead register all elements
// and upgrade once in a batch. Without this optimization, upgrade time
// degrades significantly when SD polyfill is used. This is mainly because
// querying the document tree for elements is slow under the SD polyfill.
var polyfillWasReady = CustomElements.ready;
CustomElements.ready = false;
this.flush();
if (!CustomElements.useNative) {
CustomElements.upgradeDocumentTree(document);
}
CustomElements.ready = polyfillWasReady;
Polymer.flush();
requestAnimationFrame(this.flushReadyCallbacks);
},
addReadyCallback: function(callback) {
if (callback) {
readyCallbacks.push(callback);
}
},
flushReadyCallbacks: function() {
if (readyCallbacks) {
var fn;
while (readyCallbacks.length) {
fn = readyCallbacks.shift();
fn();
}
}
},
/**
Returns a list of elements that have had polymer-elements created but
are not yet ready to register. The list is an array of element definitions.
*/
waitingFor: function() {
var e$ = [];
for (var i=0, l=elements.length, e; (i<l) &&
(e=elements[i]); i++) {
if (e.__queue && !e.__queue.flushable) {
e$.push(e);
}
}
return e$;
},
waitToReady: true
};
var elements = [];
var flushQueue = [];
var importQueue = [];
var mainQueue = [];
var readyCallbacks = [];
function queueForElement(element) {
return document.contains(element) ? mainQueue : importQueue;
}
function nextQueued() {
return importQueue.length ? importQueue[0] : mainQueue[0];
}
function whenReady(callback) {
queue.waitToReady = true;
Polymer.endOfMicrotask(function() {
HTMLImports.whenReady(function() {
queue.addReadyCallback(callback);
queue.waitToReady = false;
queue.check();
});
});
}
/**
Forces polymer to register any pending elements. Can be used to abort
waiting for elements that are partially defined.
@param timeout {Integer} Optional timeout in milliseconds
*/
function forceReady(timeout) {
if (timeout === undefined) {
queue.ready();
return;
}
var handle = setTimeout(function() {
queue.ready();
}, timeout);
Polymer.whenReady(function() {
clearTimeout(handle);
});
}
// exports
scope.elements = elements;
scope.waitingFor = queue.waitingFor.bind(queue);
scope.forceReady = forceReady;
scope.queue = queue;
scope.whenReady = scope.whenPolymerReady = whenReady;
})(Polymer);
(function(scope) {
// imports
var extend = scope.extend;
var api = scope.api;
var queue = scope.queue;
var whenReady = scope.whenReady;
var getRegisteredPrototype = scope.getRegisteredPrototype;
var waitingForPrototype = scope.waitingForPrototype;
// declarative implementation: <polymer-element>
var prototype = extend(Object.create(HTMLElement.prototype), {
createdCallback: function() {
if (this.getAttribute('name')) {
this.init();
}
},
init: function() {
// fetch declared values
this.name = this.getAttribute('name');
this.extends = this.getAttribute('extends');
queue.wait(this);
// initiate any async resource fetches
this.loadResources();
// register when all constraints are met
this.registerWhenReady();
},
// TODO(sorvell): we currently queue in the order the prototypes are
// registered, but we should queue in the order that polymer-elements
// are registered. We are currently blocked from doing this based on
// crbug.com/395686.
registerWhenReady: function() {
if (this.registered
|| this.waitingForPrototype(this.name)
|| this.waitingForQueue()
|| this.waitingForResources()) {
return;
}
queue.go(this);
},
_register: function() {
//console.log('registering', this.name);
// warn if extending from a custom element not registered via Polymer
if (isCustomTag(this.extends) && !isRegistered(this.extends)) {
console.warn('%s is attempting to extend %s, an unregistered element ' +
'or one that was not registered with Polymer.', this.name,
this.extends);
}
this.register(this.name, this.extends);
this.registered = true;
},
waitingForPrototype: function(name) {
if (!getRegisteredPrototype(name)) {
// then wait for a prototype
waitingForPrototype(name, this);
// emulate script if user is not supplying one
this.handleNoScript(name);
// prototype not ready yet
return true;
}
},
handleNoScript: function(name) {
// if explicitly marked as 'noscript'
if (this.hasAttribute('noscript') && !this.noscript) {
this.noscript = true;
// imperative element registration
Polymer(name);
}
},
waitingForResources: function() {
return this._needsResources;
},
// NOTE: Elements must be queued in proper order for inheritance/composition
// dependency resolution. Previously this was enforced for inheritance,
// and by rule for composition. It's now entirely by rule.
waitingForQueue: function() {
return queue.enqueue(this, this.registerWhenReady, this._register);
},
loadResources: function() {
this._needsResources = true;
this.loadStyles(function() {
this._needsResources = false;
this.registerWhenReady();
}.bind(this));
}
});
// semi-pluggable APIs
// TODO(sjmiles): should be fully pluggable (aka decoupled, currently
// the various plugins are allowed to depend on each other directly)
api.publish(api.declaration, prototype);
// utility and bookkeeping
function isRegistered(name) {
return Boolean(HTMLElement.getPrototypeForTag(name));
}
function isCustomTag(name) {
return (name && name.indexOf('-') >= 0);
}
// boot tasks
whenReady(function() {
document.body.removeAttribute('unresolved');
document.dispatchEvent(
new CustomEvent('polymer-ready', {bubbles: true})
);
});
// register polymer-element with document
document.registerElement('polymer-element', {prototype: prototype});
})(Polymer);
(function(scope) {
/**
* @class Polymer
*/
var whenReady = scope.whenReady;
/**
* Loads the set of HTMLImports contained in `node`. Notifies when all
* the imports have loaded by calling the `callback` function argument.
* This method can be used to lazily load imports. For example, given a
* template:
*
* <template>
* <link rel="import" href="my-import1.html">
* <link rel="import" href="my-import2.html">
* </template>
*
* Polymer.importElements(template.content, function() {
* console.log('imports lazily loaded');
* });
*
* @method importElements
* @param {Node} node Node containing the HTMLImports to load.
* @param {Function} callback Callback called when all imports have loaded.
*/
function importElements(node, callback) {
if (node) {
document.head.appendChild(node);
whenReady(callback);
} else if (callback) {
callback();
}
}
/**
* Loads an HTMLImport for each url specified in the `urls` array.
* Notifies when all the imports have loaded by calling the `callback`
* function argument. This method can be used to lazily load imports.
* For example,
*
* Polymer.import(['my-import1.html', 'my-import2.html'], function() {
* console.log('imports lazily loaded');
* });
*
* @method import
* @param {Array} urls Array of urls to load as HTMLImports.
* @param {Function} callback Callback called when all imports have loaded.
*/
function _import(urls, callback) {
if (urls && urls.length) {
var frag = document.createDocumentFragment();
for (var i=0, l=urls.length, url, link; (i<l) && (url=urls[i]); i++) {
link = document.createElement('link');
link.rel = 'import';
link.href = url;
frag.appendChild(link);
}
importElements(frag, callback);
} else if (callback) {
callback();
}
}
// exports
scope.import = _import;
scope.importElements = importElements;
})(Polymer);
/**
* The `auto-binding` element extends the template element. It provides a quick
* and easy way to do data binding without the need to setup a model.
* The `auto-binding` element itself serves as the model and controller for the
* elements it contains. Both data and event handlers can be bound.
*
* The `auto-binding` element acts just like a template that is bound to
* a model. It stamps its content in the dom adjacent to itself. When the
* content is stamped, the `template-bound` event is fired.
*
* Example:
*
* <template is="auto-binding">
* <div>Say something: <input value="{{value}}"></div>
* <div>You said: {{value}}</div>
* <button on-tap="{{buttonTap}}">Tap me!</button>
* </template>
* <script>
* var template = document.querySelector('template');
* template.value = 'something';
* template.buttonTap = function() {
* console.log('tap!');
* };
* </script>
*
* @module Polymer
* @status stable
*/
(function() {
var element = document.createElement('polymer-element');
element.setAttribute('name', 'auto-binding');
element.setAttribute('extends', 'template');
element.init();
Polymer('auto-binding', {
createdCallback: function() {
this.syntax = this.bindingDelegate = this.makeSyntax();
// delay stamping until polymer-ready so that auto-binding is not
// required to load last.
Polymer.whenPolymerReady(function() {
this.model = this;
this.setAttribute('bind', '');
// we don't bother with an explicit signal here, we could ust a MO
// if necessary
this.async(function() {
// note: this will marshall *all* the elements in the parentNode
// rather than just stamped ones. We'd need to use createInstance
// to fix this or something else fancier.
this.marshalNodeReferences(this.parentNode);
// template stamping is asynchronous so stamping isn't complete
// by polymer-ready; fire an event so users can use stamped elements
this.fire('template-bound');
});
}.bind(this));
},
makeSyntax: function() {
var events = Object.create(Polymer.api.declaration.events);
var self = this;
events.findController = function() { return self.model; };
var syntax = new PolymerExpressions();
var prepareBinding = syntax.prepareBinding;
syntax.prepareBinding = function(pathString, name, node) {
return events.prepareEventBinding(pathString, name, node) ||
prepareBinding.call(syntax, pathString, name, node);
};
return syntax;
}
});
})();
|
src/Parser/HolyPaladin/Modules/PaladinCore/FillerLightOfTheMartyrs.js | mwwscott0/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import SpellLink from 'common/SpellLink';
import ItemLink from 'common/ItemLink';
import Module from 'Parser/Core/Module';
import AbilityTracker from './PaladinAbilityTracker';
import MaraadsDyingBreath from '../Items/MaraadsDyingBreath';
class FillerLightOfTheMartyrs extends Module {
static dependencies = {
abilityTracker: AbilityTracker,
maraadsDyingBreath: MaraadsDyingBreath,
};
suggestions(when) {
const getAbility = spellId => this.abilityTracker.getAbility(spellId);
const lightOfTheMartyrs = getAbility(SPELLS.LIGHT_OF_THE_MARTYR.id).casts || 0;
let fillerLotms = lightOfTheMartyrs;
if (this.maraadsDyingBreath.active) {
const lightOfTheDawns = getAbility(SPELLS.LIGHT_OF_DAWN_CAST.id).casts || 0;
fillerLotms -= lightOfTheDawns;
}
const fillerLotmsPerMinute = fillerLotms / (this.owner.fightDuration / 1000) * 60;
when(fillerLotmsPerMinute).isGreaterThan(1.5)
.addSuggestion((suggest, actual, recommended) => {
let suggestionText;
let actualText;
if (this.maraadsDyingBreath.active) {
suggestionText = <span>With <ItemLink id={ITEMS.MARAADS_DYING_BREATH.id} /> you should only cast <b>one</b> <SpellLink id={SPELLS.LIGHT_OF_THE_MARTYR.id} /> per <SpellLink id={SPELLS.LIGHT_OF_DAWN_CAST.id} />. Without the buff <SpellLink id={SPELLS.LIGHT_OF_THE_MARTYR.id} /> is a very inefficient spell to cast. Try to only cast Light of the Martyr when it will save someone's life or when moving and all other instant cast spells are on cooldown.</span>;
actualText = `${fillerLotmsPerMinute.toFixed(2)} Casts Per Minute - ${fillerLotms} casts total (unbuffed only)`;
} else {
suggestionText = <span>You cast many <SpellLink id={SPELLS.LIGHT_OF_THE_MARTYR.id} />s. Light of the Martyr is an inefficient spell to cast, try to only cast Light of the Martyr when it will save someone's life or when moving and all other instant cast spells are on cooldown.</span>;
actualText = `${fillerLotmsPerMinute.toFixed(2)} Casts Per Minute - ${fillerLotms} casts total`;
}
return suggest(suggestionText)
.icon(SPELLS.LIGHT_OF_THE_MARTYR.icon)
.actual(actualText)
.recommended(`<${recommended} Casts Per Minute is recommended`)
.regular(recommended + 0.5).major(recommended + 1.5);
});
}
}
export default FillerLightOfTheMartyrs;
|
test/dialog-spec.js | alitaheri/material-ui | import React from 'react';
import Dialog from 'dialog';
import {spy} from 'sinon';
import TestUtils from 'react-addons-test-utils';
describe('Dialog', () => {
it('appends a dialog to the document body', () => {
let testClass = 'test-dialog-class';
TestUtils.renderIntoDocument(
<Dialog
open={true}
contentClassName={testClass} />
);
let dialogEl = document.getElementsByClassName(testClass)[0];
expect(dialogEl).to.be.ok;
});
it('registers events on dialog actions', () => {
let clickSpy = spy();
let testClass = 'dialog-action';
TestUtils.renderIntoDocument(
<Dialog
open={true}
actions={[
<button
key="a"
onClick={clickSpy}
className={testClass}>
test
</button>,
]} />
);
let actionEl = document.getElementsByClassName(testClass)[0];
expect(actionEl).to.be.ok;
TestUtils.Simulate.click(actionEl);
expect(clickSpy.called).to.be.ok;
});
});
|
src/svg-icons/action/assignment-returned.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAssignmentReturned = (props) => (
<SvgIcon {...props}>
<path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm0 15l-5-5h3V9h4v4h3l-5 5z"/>
</SvgIcon>
);
ActionAssignmentReturned = pure(ActionAssignmentReturned);
ActionAssignmentReturned.displayName = 'ActionAssignmentReturned';
ActionAssignmentReturned.muiName = 'SvgIcon';
export default ActionAssignmentReturned;
|
src/routes.js | tahmid-tanzim/work-abroad-client | import React from 'react';
import {Route} from 'react-router';
/* React Component */
import App from './components/App';
import {VotingContainer} from './components/Voting';
import {ResultsContainer} from './components/Results';
import {Home} from './components/Home';
import {Members} from './components/Members';
const routes = <Route component={App}>
<Route path="/results" component={ResultsContainer} />
<Route path="/voting" component={VotingContainer} />
<Route path="/home" component={Home} />
<Route path="/members" component={Members} />
<Route path="*" component={Home} />
</Route>;
export default routes; |
public/js/cat_source/es6/components/header/manage/FilterProjects.js | Ostico/MateCat | import React from 'react'
import IconDown from '../../icons/IconDown'
import FilterProjectsStatus from './FilterProjectsStatus'
import SearchInput from './SearchInput'
class FilterProjects extends React.Component {
constructor(props) {
super(props)
this.ALL_MEMBERS = '-1'
this.NOT_ASSIGNED = '0'
this.teamChanged = false
this.dropDownUsersInitialized = false
this.state = {
currentStatus: 'active',
}
this.selectedUser = ManageConstants.ALL_MEMBERS_FILTER
}
componentDidUpdate() {
let self = this
if (this.props.selectedTeam) {
if (this.teamChanged) {
if (
!this.dropDownUsersInitialized &&
this.props.selectedTeam.get('members').size > 1
) {
if (this.selectedUser === ManageConstants.ALL_MEMBERS_FILTER) {
$(this.dropdownUsers).dropdown('set selected', '-1')
} else {
$(this.dropdownUsers).dropdown('set selected', this.selectedUser)
}
$(this.dropdownUsers).dropdown({
fullTextSearch: 'exact',
onChange: function (value) {
self.changeUser(value)
},
})
this.dropDownUsersInitialized = true
}
this.teamChanged = false
}
}
}
getSnapshotBeforeUpdate(propsBefore) {
if (_.isUndefined(this.props.selectedTeam)) return null
if (
_.isUndefined(propsBefore.selectedTeam) ||
this.props.selectedTeam.get('id') !==
propsBefore.selectedTeam.get('id') ||
this.props.selectedTeam.get('members') !==
propsBefore.selectedTeam.get('members')
) {
this.teamChanged = true
this.dropDownUsersInitialized = false
if (
!_.isUndefined(propsBefore.selectedTeam) &&
this.props.selectedTeam.get('id') !== propsBefore.selectedTeam.get('id')
) {
this.selectedUser = ManageConstants.ALL_MEMBERS_FILTER
}
if (
this.props.selectedTeam &&
this.props.selectedTeam.get('type') !== 'personal' &&
this.props.selectedTeam.get('members').size === 1
) {
this.dropDownUsersInitialized = true
}
}
return null
}
changeUser(value) {
let self = this
let selectedUser
if (value === this.ALL_MEMBERS) {
selectedUser = ManageConstants.ALL_MEMBERS_FILTER
} else if (value === this.NOT_ASSIGNED && value !== this.selectedUser) {
selectedUser = ManageConstants.NOT_ASSIGNED_FILTER
} else {
selectedUser = this.props.selectedTeam
.get('members')
.find(function (member) {
if (parseInt(member.get('user').get('uid')) === parseInt(value)) {
return true
}
})
}
if (selectedUser !== this.selectedUser) {
this.selectedUser = selectedUser
ManageActions.filterProjects(
self.selectedUser,
self.currentText,
self.state.currentStatus,
)
}
}
onChangeSearchInput(value) {
this.currentText = value
let self = this
ManageActions.filterProjects(
self.selectedUser,
self.currentText,
self.state.currentStatus,
)
}
filterByStatus(status) {
this.setState({currentStatus: status})
ManageActions.filterProjects(
this.selectedUser,
this.currentText,
this.state.currentStatus,
)
}
getUserFilter() {
let result = ''
if (
this.props.selectedTeam &&
this.props.selectedTeam.get('type') === 'general' &&
this.props.selectedTeam.get('members') &&
this.props.selectedTeam.get('members').size > 1
) {
let members = this.props.selectedTeam.get('members').map((member) => {
let classDisable = member.get('projects') === 0 ? 'disabled' : ''
let userIcon = (
<a className="ui circular label">
{APP.getUserShortName(member.get('user').toJS())}
</a>
)
if (member.get('user_metadata')) {
userIcon = (
<img
className="ui avatar image ui-user-dropdown-image"
src={member.get('user_metadata').get('gplus_picture') + '?sz=80'}
/>
)
}
return (
<div
className={'item ' + classDisable}
data-value={member.get('user').get('uid')}
key={'user' + member.get('user').get('uid')}
>
{userIcon}
<div className="user-projects">
<div className="user-name-filter">
{member.get('user').get('first_name') +
' ' +
member.get('user').get('last_name')}
</div>
<div className="box-number-project">{member.get('projects')}</div>
</div>
</div>
)
})
let item = (
<div className="item" data-value="-1" key={'user' + -1}>
<a className="ui all label">ALL</a>
<div className="user-projects">
<div className="user-name-filter">All Members</div>
<div className="box-number-project"></div>
</div>
</div>
)
members = members.unshift(item)
item = (
<div className="item" data-value="0" key={'user' + 0}>
<a className="ui all label">NA</a>
<div className="user-projects">
<div className="user-name-filter">Not assigned</div>
<div className="box-number-project"></div>
</div>
</div>
)
members = members.unshift(item)
result = (
<div
className="ui top left pointing dropdown users-filter"
title="Filter project by members"
ref={(dropdown) => (this.dropdownUsers = dropdown)}
>
<div className="text">
<div className="ui all label">ALL</div>
All Members
</div>
<div className="icon">
<IconDown width={16} height={16} color={'#788190'} />
</div>
<div className="menu">{members}</div>
</div>
)
/*result = <div className="users-filter" title="Filter project by members">
<div className="assigned-list">
<p>Projects of: </p>
</div>
<div className="list-team">
<div className="ui dropdown top right pointing users-projects"
ref={(dropdownUsers) => this.dropdownUsers = dropdownUsers}>
<div className="text">
<div className="ui all label">ALL</div>
All Members
</div>
<i className="dropdown icon"/>
<div className="menu">
<div className="ui icon search input">
<i className="icon-search icon"/>
<input type="text" name="UserName" placeholder="Search by name." />
</div>
<div className="scrolling menu">
{members}
</div>
</div>
</div>
</div>
</div>;*/
}
return result
}
getCurrentStatusLabel() {
switch (this.state.currentStatus) {
case 'active':
return <div className="active">Active:</div>
case 'archived':
return <div className="archived">Archived:</div>
case 'cancelled':
return <div className="cancelled">Cancelled:</div>
}
}
shouldComponentUpdate(nextProps) {
return (
_.isUndefined(this.props.selectedTeam) ||
(!_.isUndefined(nextProps.selectedTeam) &&
!nextProps.selectedTeam.equals(this.props.selectedTeam))
)
}
render() {
let membersFilter = this.getUserFilter()
return (
<section className="row sub-head">
<div className="ui grid">
<div className="twelve wide column">
<div className="ui right labeled fluid input search-state-filters">
<SearchInput onChange={this.onChangeSearchInput.bind(this)} />
<FilterProjectsStatus
filterFunction={this.filterByStatus.bind(this)}
/>
</div>
</div>
{/*<div className="cta-create-team" onClick={this.openCreateTeams.bind(this)}>
<a class="cta-create-team-text">Create New Team <i className="icon-settings icon"></i></a>
</div>*/}
<div className="four wide column pad-right-0">{membersFilter}</div>
</div>
</section>
)
}
}
export default FilterProjects
|
src/parser/hunter/survival/modules/talents/Bloodseeker.js | sMteX/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
import { BLOODSEEKER_ATTACK_SPEED_GAIN } from 'parser/hunter/survival/constants';
import { formatPercentage } from 'common/format';
import ItemDamageDone from 'interface/others/ItemDamageDone';
/**
* Kill Command causes the target to bleed for X damage over 8 sec.
* You and your pet gain 10% attack speed for every bleeding enemy within 12 yds.
*
* Example log: https://www.warcraftlogs.com/reports/WBkTFfP6G4VcxjLz#fight=1&type=auras&source=8&ability=260249
*/
const MS_BUFFER = 100;
class Bloodseeker extends Analyzer {
averageStacks = 0;
kcCastTimestamp = null;
damage = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.BLOODSEEKER_TALENT.id);
}
on_byPlayerPet_damage(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.KILL_COMMAND_DAMAGE_SV.id) {
return;
}
if (event.timestamp > (this.kcCastTimestamp + MS_BUFFER)) {
this.damage += event.amount + (event.absorbed || 0);
}
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.KILL_COMMAND_CAST_SV.id) {
return;
}
this.kcCastTimestamp = event.timestamp;
}
get uptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.BLOODSEEKER_BUFF.id) / this.owner.fightDuration;
}
get averageAttackSpeedGain() {
this.averageStacks = this.selectedCombatant.getStackWeightedBuffUptime(SPELLS.BLOODSEEKER_BUFF.id) / this.owner.fightDuration;
return this.averageStacks * BLOODSEEKER_ATTACK_SPEED_GAIN;
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.BLOODSEEKER_TALENT.id}
value={<>
<ItemDamageDone amount={this.damage} /> <br />
{formatPercentage(this.averageAttackSpeedGain)}% atk speed gain
</>}
tooltip={`You had ${formatPercentage(this.uptime)}% uptime on the buff, with an average of ${(this.averageStacks).toFixed(2)} stacks.`}
/>
);
}
}
export default Bloodseeker;
|
app/components/ConversationList.js | DrPandemic/TwiolioRN | // @flow
import React, { Component } from 'react';
import {
Dimensions,
FlatList,
View,
StyleSheet
} from 'react-native';
import { List, ListItem } from 'react-native-elements';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import ActionButton from 'react-native-action-button';
import { ActionCreators } from '../actions';
import { Message } from '../types';
import { getConversations, filterByUs } from '../types/ConversationStore';
import { getNameForMessage } from '../types/Contact';
import { Colors } from '../constants';
import type { StateT } from '../reducers';
import type { T as AccountT } from '../reducers/account';
import type { T as MessagesT } from '../reducers/messages';
import type { T as ContactT } from '../reducers/contacts';
const { width } = Dimensions.get('window');
const styles = StyleSheet.create({
container: {
width,
flexDirection: 'column',
backgroundColor: Colors.background,
},
list: {
marginTop: 0,
borderBottomWidth: 0,
},
item: {
paddingTop: 10,
paddingBottom: 10,
borderBottomWidth: 0,
},
flatList: {
marginBottom: 30,
},
actionButton: {
position: 'absolute',
bottom: 0,
right: 0,
},
actionButtonIcon: {
fontSize: 20,
height: 22,
color: Colors.primary.text,
},
});
type PropsT = {
account: AccountT,
messages: MessagesT,
contacts: ContactT,
push: (any) => void,
};
export class PConversationList extends Component {
props: PropsT;
constructor(props: PropsT): void {
super(props);
this.onSelectConversation = this.onSelectConversation.bind(this);
this.onButtonPress = this.onButtonPress.bind(this);
}
onSelectConversation(message: Message): void {
this.props.push({
pathname: '/conversation',
state: {
conversationId: message.conversationId,
to: message.conversationUsers.other,
from: message.conversationUsers.us,
},
});
}
renderRow([message]: Array<Message>) {
return (
<ListItem
key={message.conversationId}
title={getNameForMessage(this.props.contacts.contacts, message)}
onPress={() => this.onSelectConversation(message)}
containerStyle={styles.item}
underlayColor={'#dedede'}
/>
);
}
onButtonPress() {
this.props.push({
pathname: '/newConversation',
});
}
render() {
const messages = getConversations(filterByUs(
this.props.messages.messages,
this.props.account.selectedNumber
));
return (
<View style={styles.container}>
<List style={styles.list}>
<FlatList
data={messages}
renderItem={({ item }) => this.renderRow(item)}
keyExtractor={([message]) => message.sid}
style={styles.flatList}
/>
</List>
<ActionButton
style={styles.actionButton}
buttonColor={Colors.primary.normal}
onPress={() => this.onButtonPress()}
/>
</View>
);
}
}
function mapStateToProps(state: StateT) {
return {
account: state.account,
messages: state.messages,
contacts: state.contacts,
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(ActionCreators, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(PConversationList);
|
src/components/DeviceList/DeviceList.js | yanivefraim/mobile-device-manager | 'use strict';
import React from 'react';
import DeviceItem from '../DeviceItem';
export default class DeviceList extends React.Component {
render() {
var devicesHTML = this.props.devices.map( function( deviceItem ){
return (
<DeviceItem device = {deviceItem} />
);
});
return (
<div>
<ul>
{ devicesHTML }
</ul>
</div>
);
}
}
|
app/js/components/sidebar_content.js | carlos09/portal-react-rocket | import React from 'react';
import MaterialTitlePanel from './material_title_panel';
import { Grid, Row, Col, Form } from 'react-bootstrap';
import {Link} from 'react-router';
const styles = {
sidebar: {
width: 256,
height: '100%',
},
sidebarLink: {
display: 'block',
padding: '16px 0px',
color: '#757575',
textDecoration: 'none',
},
divider: {
margin: '8px 0',
height: 1,
backgroundColor: '#757575',
},
content: {
padding: '16px',
height: '100%',
backgroundColor: 'white',
},
};
const SidebarContent = (props) => {
const style = props.style ? {...styles.sidebar, ...props.style} : styles.sidebar;
const links = [];
for (let ind = 0; ind < 10; ind++) {
links.push(
<a key={ind} href="#" style={styles.sidebarLink}>Mock menu item {ind}</a>);
}
return (
<MaterialTitlePanel style={style}>
<div id="sidebar">
<div className="text-center profile-welcome">
<Link to="/"><div className="avatar"></div></Link>
</div>
<div className="">
<ul id="nav-list">
<li><Link to="/"><i className="zmdi zmdi-view-dashboard"></i> Dashboard</Link></li>
<li><Link to="/affiliates"><i className="zmdi zmdi-account-box"></i> Affiliates</Link></li>
<li><Link to="/stations"><i className="zmdi zmdi-portable-wifi"></i> Stations</Link></li>
<li><Link to="/users"><i className="zmdi zmdi-accounts"></i> Users</Link></li>
<li><Link to="/login"><i className="material-icons md-24">keyboard_tab</i> Login</Link></li>
</ul>
</div>
</div>
</MaterialTitlePanel>
);
};
export default SidebarContent;
|
src/List/ListItem.spec.js | rhaedes/material-ui | /* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import ListItem from './ListItem';
import getMuiTheme from '../styles/getMuiTheme';
describe('<ListItem />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
it('should render an EnhancedButton', () => {
const wrapper = shallowWithContext(
<ListItem />
);
const enhancedButton = wrapper.find('EnhancedButton');
assert.ok(enhancedButton.length);
});
it('should display a list-item with text if primaryText is specified', () => {
const testText = 'Primary Text';
const wrapper = shallowWithContext(
<ListItem
primaryText={testText}
/>
);
const enhancedButton = wrapper.find('EnhancedButton');
assert.strictEqual(enhancedButton.children().text(), testText);
});
it('should display a list-item elment with a class if specified', () => {
const testClass = 'test-class';
const wrapper = shallowWithContext(
<ListItem
className={testClass}
/>
);
const enhancedButton = wrapper.find('EnhancedButton');
assert.strictEqual(enhancedButton.prop('className'), testClass);
});
it('should display a disabled list-item if specified.', () => {
const wrapper = shallowWithContext(
<ListItem
disabled={true}
/>
);
assert.notOk(wrapper.find('EnhancedButton').length, 'should not have an EnhancedButton');
});
it('should display a disabled list-item with a class if specified.', () => {
const testClass = 'test-class';
const wrapper = shallowWithContext(
<ListItem
className={testClass}
disabled={true}
/>
);
assert.notOk(wrapper.find('EnhancedButton').length, 'should not have an EnhancedButton');
assert.strictEqual(wrapper.find(`.${testClass}`).length, 1, 'should have a div with the test class');
});
it('should display a checkbox in the list-item if specified.', () => {
const testClass = 'test-class';
const wrapper = shallowWithContext(
<ListItem
leftCheckbox={<div className="test-checkbox" />}
className={testClass}
/>
);
assert.ok(wrapper.find('.test-checkbox').length);
assert.strictEqual(wrapper.find(`.${testClass}`).length, 1, 'should have a div with the test class');
});
});
|
app/components/NavBar/index.js | Rohitbels/KolheshwariIndustries | /**
*
* NavBar
*
*/
import React from 'react';
import {Nav,Navbar,NavItem,NavDropdown,MenuItem} from 'react-bootstrap'
import {Link } from 'react-router';
import {LinkContainer} from 'react-router-bootstrap';
class NavBar extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<Navbar inverse collapseOnSelect style={{marginBottom: '0px'}}>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">Kolheshwari Industries</Link>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<LinkContainer to="/">
<NavItem eventKey={1} >Home</NavItem>
</LinkContainer>
<LinkContainer to="/product">
<NavItem eventKey={2} >Products</NavItem>
</LinkContainer>
<LinkContainer to="/contact">
<NavItem eventKey={3} >Contact Us</NavItem>
</LinkContainer>
<LinkContainer to="/about">
<NavItem eventKey={4} >About Us</NavItem>
</LinkContainer>
</Nav>
<Nav pullRight>
<NavItem eventKey={1} href="#">Helpline : 9552040509</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}
export default NavBar;
|
ajax/libs/jquery.fancytree/2.22.3/jquery.fancytree-all.js | wout/cdnjs | /*!
* jquery.fancytree.js
* Tree view control with support for lazy loading and much more.
* https://github.com/mar10/fancytree/
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
/** Core Fancytree module.
*/
// Start of local namespace
;(function($, window, document, undefined) {
"use strict";
// prevent duplicate loading
if ( $.ui && $.ui.fancytree ) {
$.ui.fancytree.warn("Fancytree: ignored duplicate include");
return;
}
/* *****************************************************************************
* Private functions and variables
*/
var i, attr,
FT = null, // initialized below
TEST_IMG = new RegExp(/\.|\//), // strings are considered image urls if they contain '.' or '/'
REX_HTML = /[&<>"'\/]/g,
REX_TOOLTIP = /[<>"'\/]/g,
RECURSIVE_REQUEST_ERROR = "$recursive_request",
ENTITY_MAP = {"&": "&", "<": "<", ">": ">", "\"": """, "'": "'", "/": "/"},
IGNORE_KEYCODES = { 16: true, 17: true, 18: true },
SPECIAL_KEYCODES = {
8: "backspace", 9: "tab", 10: "return", 13: "return",
// 16: null, 17: null, 18: null, // ignore shift, ctrl, alt
19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup",
34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up",
39: "right", 40: "down", 45: "insert", 46: "del", 59: ";", 61: "=",
96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6",
103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".",
111: "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5",
117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11",
123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=",
188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
221: "]", 222: "'"},
MOUSE_BUTTONS = { 0: "", 1: "left", 2: "middle", 3: "right" },
// Boolean attributes that can be set with equivalent class names in the LI tags
CLASS_ATTRS = "active expanded focus folder hideCheckbox lazy selected unselectable".split(" "),
CLASS_ATTR_MAP = {},
// Top-level Fancytree node attributes, that can be set by dict
NODE_ATTRS = "expanded extraClasses folder hideCheckbox icon key lazy refKey selected statusNodeType title tooltip unselectable".split(" "),
NODE_ATTR_MAP = {},
// Mapping of lowercase -> real name (because HTML5 data-... attribute only supports lowercase)
NODE_ATTR_LOWERCASE_MAP = {},
// Attribute names that should NOT be added to node.data
NONE_NODE_DATA_MAP = {"active": true, "children": true, "data": true, "focus": true};
for(i=0; i<CLASS_ATTRS.length; i++){ CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true; }
for(i=0; i<NODE_ATTRS.length; i++) {
attr = NODE_ATTRS[i];
NODE_ATTR_MAP[attr] = true;
if( attr !== attr.toLowerCase() ) {
NODE_ATTR_LOWERCASE_MAP[attr.toLowerCase()] = attr;
}
}
function _assert(cond, msg){
// TODO: see qunit.js extractStacktrace()
if(!cond){
msg = msg ? ": " + msg : "";
// consoleApply("assert", [!!cond, msg]);
$.error("Fancytree assertion failed" + msg);
}
}
_assert($.ui, "Fancytree requires jQuery UI (http://jqueryui.com)");
function consoleApply(method, args){
var i, s,
fn = window.console ? window.console[method] : null;
if(fn){
try{
fn.apply(window.console, args);
} catch(e) {
// IE 8?
s = "";
for( i=0; i<args.length; i++ ) {
s += args[i];
}
fn(s);
}
}
}
/*Return true if x is a FancytreeNode.*/
function _isNode(x){
return !!(x.tree && x.statusNodeType !== undefined);
}
/** Return true if dotted version string is equal or higher than requested version.
*
* See http://jsfiddle.net/mar10/FjSAN/
*/
function isVersionAtLeast(dottedVersion, major, minor, patch){
var i, v, t,
verParts = $.map($.trim(dottedVersion).split("."), function(e){ return parseInt(e, 10); }),
testParts = $.map(Array.prototype.slice.call(arguments, 1), function(e){ return parseInt(e, 10); });
for( i = 0; i < testParts.length; i++ ){
v = verParts[i] || 0;
t = testParts[i] || 0;
if( v !== t ){
return ( v > t );
}
}
return true;
}
/** Return a wrapper that calls sub.methodName() and exposes
* this : tree
* this._local : tree.ext.EXTNAME
* this._super : base.methodName.call()
* this._superApply : base.methodName.apply()
*/
function _makeVirtualFunction(methodName, tree, base, extension, extName){
// $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName);
// if(rexTestSuper && !rexTestSuper.test(func)){
// // extension.methodName() doesn't call _super(), so no wrapper required
// return func;
// }
// Use an immediate function as closure
var proxy = (function(){
var prevFunc = tree[methodName], // org. tree method or prev. proxy
baseFunc = extension[methodName], //
_local = tree.ext[extName],
_super = function(){
return prevFunc.apply(tree, arguments);
},
_superApply = function(args){
return prevFunc.apply(tree, args);
};
// Return the wrapper function
return function(){
var prevLocal = tree._local,
prevSuper = tree._super,
prevSuperApply = tree._superApply;
try{
tree._local = _local;
tree._super = _super;
tree._superApply = _superApply;
return baseFunc.apply(tree, arguments);
}finally{
tree._local = prevLocal;
tree._super = prevSuper;
tree._superApply = prevSuperApply;
}
};
})(); // end of Immediate Function
return proxy;
}
/**
* Subclass `base` by creating proxy functions
*/
function _subclassObject(tree, base, extension, extName){
// $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName);
for(var attrName in extension){
if(typeof extension[attrName] === "function"){
if(typeof tree[attrName] === "function"){
// override existing method
tree[attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName);
}else if(attrName.charAt(0) === "_"){
// Create private methods in tree.ext.EXTENSION namespace
tree.ext[extName][attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName);
}else{
$.error("Could not override tree." + attrName + ". Use prefix '_' to create tree." + extName + "._" + attrName);
}
}else{
// Create member variables in tree.ext.EXTENSION namespace
if(attrName !== "options"){
tree.ext[extName][attrName] = extension[attrName];
}
}
}
}
function _getResolvedPromise(context, argArray){
if(context === undefined){
return $.Deferred(function(){this.resolve();}).promise();
}else{
return $.Deferred(function(){this.resolveWith(context, argArray);}).promise();
}
}
function _getRejectedPromise(context, argArray){
if(context === undefined){
return $.Deferred(function(){this.reject();}).promise();
}else{
return $.Deferred(function(){this.rejectWith(context, argArray);}).promise();
}
}
function _makeResolveFunc(deferred, context){
return function(){
deferred.resolveWith(context);
};
}
function _getElementDataAsDict($el){
// Evaluate 'data-NAME' attributes with special treatment for 'data-json'.
var d = $.extend({}, $el.data()),
json = d.json;
delete d.fancytree; // added to container by widget factory (old jQuery UI)
delete d.uiFancytree; // added to container by widget factory
if( json ) {
delete d.json;
// <li data-json='...'> is already returned as object (http://api.jquery.com/data/#data-html5)
d = $.extend(d, json);
}
return d;
}
function _escapeHtml(s){
return ("" + s).replace(REX_HTML, function(s) {
return ENTITY_MAP[s];
});
}
function _escapeTooltip(s){
return ("" + s).replace(REX_TOOLTIP, function(s) {
return ENTITY_MAP[s];
});
}
// TODO: use currying
function _makeNodeTitleMatcher(s){
s = s.toLowerCase();
return function(node){
return node.title.toLowerCase().indexOf(s) >= 0;
};
}
function _makeNodeTitleStartMatcher(s){
var reMatch = new RegExp("^" + s, "i");
return function(node){
return reMatch.test(node.title);
};
}
/* *****************************************************************************
* FancytreeNode
*/
/**
* Creates a new FancytreeNode
*
* @class FancytreeNode
* @classdesc A FancytreeNode represents the hierarchical data model and operations.
*
* @param {FancytreeNode} parent
* @param {NodeData} obj
*
* @property {Fancytree} tree The tree instance
* @property {FancytreeNode} parent The parent node
* @property {string} key Node id (must be unique inside the tree)
* @property {string} title Display name (may contain HTML)
* @property {object} data Contains all extra data that was passed on node creation
* @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br>
* For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array
* to define a node that has no children.
* @property {boolean} expanded Use isExpanded(), setExpanded() to access this property.
* @property {string} extraClasses Additional CSS classes, added to the node's `<span>`.<br>
* Note: use `node.add/remove/toggleClass()` to modify.
* @property {boolean} folder Folder nodes have different default icons and click behavior.<br>
* Note: Also non-folders may have children.
* @property {string} statusNodeType null for standard nodes. Otherwise type of special system node: 'error', 'loading', 'nodata', or 'paging'.
* @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion.
* @property {boolean} selected Use isSelected(), setSelected() to access this property.
* @property {string} tooltip Alternative description used as hover popup
*/
function FancytreeNode(parent, obj){
var i, l, name, cl;
this.parent = parent;
this.tree = parent.tree;
this.ul = null;
this.li = null; // <li id='key' ftnode=this> tag
this.statusNodeType = null; // if this is a temp. node to display the status of its parent
this._isLoading = false; // if this node itself is loading
this._error = null; // {message: '...'} if a load error occurred
this.data = {};
// TODO: merge this code with node.toDict()
// copy attributes from obj object
for(i=0, l=NODE_ATTRS.length; i<l; i++){
name = NODE_ATTRS[i];
this[name] = obj[name];
}
// node.data += obj.data
if(obj.data){
$.extend(this.data, obj.data);
}
// copy all other attributes to this.data.NAME
for(name in obj){
if(!NODE_ATTR_MAP[name] && !$.isFunction(obj[name]) && !NONE_NODE_DATA_MAP[name]){
// node.data.NAME = obj.NAME
this.data[name] = obj[name];
}
}
// Fix missing key
if( this.key == null ){ // test for null OR undefined
if( this.tree.options.defaultKey ) {
this.key = this.tree.options.defaultKey(this);
_assert(this.key, "defaultKey() must return a unique key");
} else {
this.key = "_" + (FT._nextNodeKey++);
}
} else {
this.key = "" + this.key; // Convert to string (#217)
}
// Fix tree.activeNode
// TODO: not elegant: we use obj.active as marker to set tree.activeNode
// when loading from a dictionary.
if(obj.active){
_assert(this.tree.activeNode === null, "only one active node allowed");
this.tree.activeNode = this;
}
if( obj.selected ){ // #186
this.tree.lastSelectedNode = this;
}
// TODO: handle obj.focus = true
// Create child nodes
cl = obj.children;
if( cl ){
if( cl.length ){
this._setChildren(cl);
} else {
// if an empty array was passed for a lazy node, keep it, in order to mark it 'loaded'
this.children = this.lazy ? [] : null;
}
} else {
this.children = null;
}
// Add to key/ref map (except for root node)
// if( parent ) {
this.tree._callHook("treeRegisterNode", this.tree, true, this);
// }
}
FancytreeNode.prototype = /** @lends FancytreeNode# */{
/* Return the direct child FancytreeNode with a given key, index. */
_findDirectChild: function(ptr){
var i, l,
cl = this.children;
if(cl){
if(typeof ptr === "string"){
for(i=0, l=cl.length; i<l; i++){
if(cl[i].key === ptr){
return cl[i];
}
}
}else if(typeof ptr === "number"){
return this.children[ptr];
}else if(ptr.parent === this){
return ptr;
}
}
return null;
},
// TODO: activate()
// TODO: activateSilently()
/* Internal helper called in recursive addChildren sequence.*/
_setChildren: function(children){
_assert(children && (!this.children || this.children.length === 0), "only init supported");
this.children = [];
for(var i=0, l=children.length; i<l; i++){
this.children.push(new FancytreeNode(this, children[i]));
}
},
/**
* Append (or insert) a list of child nodes.
*
* @param {NodeData[]} children array of child node definitions (also single child accepted)
* @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such).
* If omitted, the new children are appended.
* @returns {FancytreeNode} first child added
*
* @see FancytreeNode#applyPatch
*/
addChildren: function(children, insertBefore){
var i, l, pos,
origFirstChild = this.getFirstChild(),
origLastChild = this.getLastChild(),
firstNode = null,
nodeList = [];
if($.isPlainObject(children) ){
children = [children];
}
if(!this.children){
this.children = [];
}
for(i=0, l=children.length; i<l; i++){
nodeList.push(new FancytreeNode(this, children[i]));
}
firstNode = nodeList[0];
if(insertBefore == null){
this.children = this.children.concat(nodeList);
}else{
insertBefore = this._findDirectChild(insertBefore);
pos = $.inArray(insertBefore, this.children);
_assert(pos >= 0, "insertBefore must be an existing child");
// insert nodeList after children[pos]
this.children.splice.apply(this.children, [pos, 0].concat(nodeList));
}
if ( origFirstChild && !insertBefore ) {
// #708: Fast path -- don't render every child of root, just the new ones!
// #723, #729: but only if it's appended to an existing child list
for(i=0, l=nodeList.length; i<l; i++) {
nodeList[i].render(); // New nodes were never rendered before
}
// Adjust classes where status may have changed
// Has a first child
if (origFirstChild !== this.getFirstChild()) {
// Different first child -- recompute classes
origFirstChild.renderStatus();
}
if (origLastChild !== this.getLastChild()) {
// Different last child -- recompute classes
origLastChild.renderStatus();
}
} else if( !this.parent || this.parent.ul || this.tr ){
// render if the parent was rendered (or this is a root node)
this.render();
}
if( this.tree.options.selectMode === 3 ){
this.fixSelection3FromEndNodes();
}
this.triggerModifyChild("add", nodeList.length === 1 ? nodeList[0] : null);
return firstNode;
},
/**
* Add class to node's span tag and to .extraClasses.
*
* @param {string} className class name
*
* @since 2.17
*/
addClass: function(className){
return this.toggleClass(className, true);
},
/**
* Append or prepend a node, or append a child node.
*
* This a convenience function that calls addChildren()
*
* @param {NodeData} node node definition
* @param {string} [mode=child] 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child')
* @returns {FancytreeNode} new node
*/
addNode: function(node, mode){
if(mode === undefined || mode === "over"){
mode = "child";
}
switch(mode){
case "after":
return this.getParent().addChildren(node, this.getNextSibling());
case "before":
return this.getParent().addChildren(node, this);
case "firstChild":
// Insert before the first child if any
var insertBefore = (this.children ? this.children[0] : null);
return this.addChildren(node, insertBefore);
case "child":
case "over":
return this.addChildren(node);
}
_assert(false, "Invalid mode: " + mode);
},
/**Add child status nodes that indicate 'More...', etc.
*
* This also maintains the node's `partload` property.
* @param {boolean|object} node optional node definition. Pass `false` to remove all paging nodes.
* @param {string} [mode='child'] 'child'|firstChild'
* @since 2.15
*/
addPagingNode: function(node, mode){
var i, n;
mode = mode || "child";
if( node === false ) {
for(i=this.children.length-1; i >= 0; i--) {
n = this.children[i];
if( n.statusNodeType === "paging" ) {
this.removeChild(n);
}
}
this.partload = false;
return;
}
node = $.extend({
title: this.tree.options.strings.moreData,
statusNodeType: "paging",
icon: false
}, node);
this.partload = true;
return this.addNode(node, mode);
},
/**
* Append new node after this.
*
* This a convenience function that calls addNode(node, 'after')
*
* @param {NodeData} node node definition
* @returns {FancytreeNode} new node
*/
appendSibling: function(node){
return this.addNode(node, "after");
},
/**
* Modify existing child nodes.
*
* @param {NodePatch} patch
* @returns {$.Promise}
* @see FancytreeNode#addChildren
*/
applyPatch: function(patch) {
// patch [key, null] means 'remove'
if(patch === null){
this.remove();
return _getResolvedPromise(this);
}
// TODO: make sure that root node is not collapsed or modified
// copy (most) attributes to node.ATTR or node.data.ATTR
var name, promise, v,
IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global
for(name in patch){
v = patch[name];
if( !IGNORE_MAP[name] && !$.isFunction(v)){
if(NODE_ATTR_MAP[name]){
this[name] = v;
}else{
this.data[name] = v;
}
}
}
// Remove and/or create children
if(patch.hasOwnProperty("children")){
this.removeChildren();
if(patch.children){ // only if not null and not empty list
// TODO: addChildren instead?
this._setChildren(patch.children);
}
// TODO: how can we APPEND or INSERT child nodes?
}
if(this.isVisible()){
this.renderTitle();
this.renderStatus();
}
// Expand collapse (final step, since this may be async)
if(patch.hasOwnProperty("expanded")){
promise = this.setExpanded(patch.expanded);
}else{
promise = _getResolvedPromise(this);
}
return promise;
},
/** Collapse all sibling nodes.
* @returns {$.Promise}
*/
collapseSiblings: function() {
return this.tree._callHook("nodeCollapseSiblings", this);
},
/** Copy this node as sibling or child of `node`.
*
* @param {FancytreeNode} node source node
* @param {string} [mode=child] 'before' | 'after' | 'child'
* @param {Function} [map] callback function(NodeData) that could modify the new node
* @returns {FancytreeNode} new
*/
copyTo: function(node, mode, map) {
return node.addNode(this.toDict(true, map), mode);
},
/** Count direct and indirect children.
*
* @param {boolean} [deep=true] pass 'false' to only count direct children
* @returns {int} number of child nodes
*/
countChildren: function(deep) {
var cl = this.children, i, l, n;
if( !cl ){
return 0;
}
n = cl.length;
if(deep !== false){
for(i=0, l=n; i<l; i++){
n += cl[i].countChildren();
}
}
return n;
},
// TODO: deactivate()
/** Write to browser console if debugLevel >= 2 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
debug: function(msg){
if( this.tree.options.debugLevel >= 2 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("log", arguments);
}
},
/** Deprecated.
* @deprecated since 2014-02-16. Use resetLazy() instead.
*/
discard: function(){
this.warn("FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead.");
return this.resetLazy();
},
/** Remove DOM elements for all descendents. May be called on .collapse event
* to keep the DOM small.
* @param {boolean} [includeSelf=false]
*/
discardMarkup: function(includeSelf){
var fn = includeSelf ? "nodeRemoveMarkup" : "nodeRemoveChildMarkup";
this.tree._callHook(fn, this);
},
/**Find all nodes that match condition (excluding self).
*
* @param {string | function(node)} match title string to search for, or a
* callback function that returns `true` if a node is matched.
* @returns {FancytreeNode[]} array of nodes (may be empty)
*/
findAll: function(match) {
match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
var res = [];
this.visit(function(n){
if(match(n)){
res.push(n);
}
});
return res;
},
/**Find first node that matches condition (excluding self).
*
* @param {string | function(node)} match title string to search for, or a
* callback function that returns `true` if a node is matched.
* @returns {FancytreeNode} matching node or null
* @see FancytreeNode#findAll
*/
findFirst: function(match) {
match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
var res = null;
this.visit(function(n){
if(match(n)){
res = n;
return false;
}
});
return res;
},
/* Apply selection state (internal use only) */
_changeSelectStatusAttrs: function (state) {
var changed = false;
switch(state){
case false:
changed = ( this.selected || this.partsel );
this.selected = false;
this.partsel = false;
break;
case true:
changed = ( !this.selected || !this.partsel );
this.selected = true;
this.partsel = true;
break;
case undefined:
changed = ( this.selected || !this.partsel );
this.selected = false;
this.partsel = true;
break;
default:
_assert(false, "invalid state: " + state);
}
// this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed);
if( changed ){
this.renderStatus();
}
return changed;
},
/**
* Fix selection status, after this node was (de)selected in multi-hier mode.
* This includes (de)selecting all children.
*/
fixSelection3AfterClick: function() {
var flag = this.isSelected();
// this.debug("fixSelection3AfterClick()");
this.visit(function(node){
node._changeSelectStatusAttrs(flag);
});
this.fixSelection3FromEndNodes();
},
/**
* Fix selection status for multi-hier mode.
* Only end-nodes are considered to update the descendants branch and parents.
* Should be called after this node has loaded new children or after
* children have been modified using the API.
*/
fixSelection3FromEndNodes: function() {
// this.debug("fixSelection3FromEndNodes()");
_assert(this.tree.options.selectMode === 3, "expected selectMode 3");
// Visit all end nodes and adjust their parent's `selected` and `partsel`
// attributes. Return selection state true, false, or undefined.
function _walk(node){
var i, l, child, s, state, allSelected,someSelected,
children = node.children;
if( children && children.length ){
// check all children recursively
allSelected = true;
someSelected = false;
for( i=0, l=children.length; i<l; i++ ){
child = children[i];
// the selection state of a node is not relevant; we need the end-nodes
s = _walk(child);
if( s !== false ) {
someSelected = true;
}
if( s !== true ) {
allSelected = false;
}
}
state = allSelected ? true : (someSelected ? undefined : false);
}else{
// This is an end-node: simply report the status
// state = ( node.unselectable ) ? undefined : !!node.selected;
state = !!node.selected;
}
node._changeSelectStatusAttrs(state);
return state;
}
_walk(this);
// Update parent's state
this.visitParents(function(node){
var i, l, child, state,
children = node.children,
allSelected = true,
someSelected = false;
for( i=0, l=children.length; i<l; i++ ){
child = children[i];
// When fixing the parents, we trust the sibling status (i.e.
// we don't recurse)
if( child.selected || child.partsel ) {
someSelected = true;
}
if( !child.unselectable && !child.selected ) {
allSelected = false;
}
}
state = allSelected ? true : (someSelected ? undefined : false);
node._changeSelectStatusAttrs(state);
});
},
// TODO: focus()
/**
* Update node data. If dict contains 'children', then also replace
* the hole sub tree.
* @param {NodeData} dict
*
* @see FancytreeNode#addChildren
* @see FancytreeNode#applyPatch
*/
fromDict: function(dict) {
// copy all other attributes to this.data.xxx
for(var name in dict){
if(NODE_ATTR_MAP[name]){
// node.NAME = dict.NAME
this[name] = dict[name];
}else if(name === "data"){
// node.data += dict.data
$.extend(this.data, dict.data);
}else if(!$.isFunction(dict[name]) && !NONE_NODE_DATA_MAP[name]){
// node.data.NAME = dict.NAME
this.data[name] = dict[name];
}
}
if(dict.children){
// recursively set children and render
this.removeChildren();
this.addChildren(dict.children);
}
this.renderTitle();
/*
var children = dict.children;
if(children === undefined){
this.data = $.extend(this.data, dict);
this.render();
return;
}
dict = $.extend({}, dict);
dict.children = undefined;
this.data = $.extend(this.data, dict);
this.removeChildren();
this.addChild(children);
*/
},
/** Return the list of child nodes (undefined for unexpanded lazy nodes).
* @returns {FancytreeNode[] | undefined}
*/
getChildren: function() {
if(this.hasChildren() === undefined){ // TODO: only required for lazy nodes?
return undefined; // Lazy node: unloaded, currently loading, or load error
}
return this.children;
},
/** Return the first child node or null.
* @returns {FancytreeNode | null}
*/
getFirstChild: function() {
return this.children ? this.children[0] : null;
},
/** Return the 0-based child index.
* @returns {int}
*/
getIndex: function() {
// return this.parent.children.indexOf(this);
return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7
},
/** Return the hierarchical child index (1-based, e.g. '3.2.4').
* @param {string} [separator="."]
* @param {int} [digits=1]
* @returns {string}
*/
getIndexHier: function(separator, digits) {
separator = separator || ".";
var s,
res = [];
$.each(this.getParentList(false, true), function(i, o){
s = "" + (o.getIndex() + 1);
if( digits ){
// prepend leading zeroes
s = ("0000000" + s).substr(-digits);
}
res.push(s);
});
return res.join(separator);
},
/** Return the parent keys separated by options.keyPathSeparator, e.g. "id_1/id_17/id_32".
* @param {boolean} [excludeSelf=false]
* @returns {string}
*/
getKeyPath: function(excludeSelf) {
var path = [],
sep = this.tree.options.keyPathSeparator;
this.visitParents(function(n){
if(n.parent){
path.unshift(n.key);
}
}, !excludeSelf);
return sep + path.join(sep);
},
/** Return the last child of this node or null.
* @returns {FancytreeNode | null}
*/
getLastChild: function() {
return this.children ? this.children[this.children.length - 1] : null;
},
/** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... .
* @returns {int}
*/
getLevel: function() {
var level = 0,
dtn = this.parent;
while( dtn ) {
level++;
dtn = dtn.parent;
}
return level;
},
/** Return the successor node (under the same parent) or null.
* @returns {FancytreeNode | null}
*/
getNextSibling: function() {
// TODO: use indexOf, if available: (not in IE6)
if( this.parent ){
var i, l,
ac = this.parent.children;
for(i=0, l=ac.length-1; i<l; i++){ // up to length-2, so next(last) = null
if( ac[i] === this ){
return ac[i+1];
}
}
}
return null;
},
/** Return the parent node (null for the system root node).
* @returns {FancytreeNode | null}
*/
getParent: function() {
// TODO: return null for top-level nodes?
return this.parent;
},
/** Return an array of all parent nodes (top-down).
* @param {boolean} [includeRoot=false] Include the invisible system root node.
* @param {boolean} [includeSelf=false] Include the node itself.
* @returns {FancytreeNode[]}
*/
getParentList: function(includeRoot, includeSelf) {
var l = [],
dtn = includeSelf ? this : this.parent;
while( dtn ) {
if( includeRoot || dtn.parent ){
l.unshift(dtn);
}
dtn = dtn.parent;
}
return l;
},
/** Return the predecessor node (under the same parent) or null.
* @returns {FancytreeNode | null}
*/
getPrevSibling: function() {
if( this.parent ){
var i, l,
ac = this.parent.children;
for(i=1, l=ac.length; i<l; i++){ // start with 1, so prev(first) = null
if( ac[i] === this ){
return ac[i-1];
}
}
}
return null;
},
/**
* Return an array of selected descendant nodes.
* @param {boolean} [stopOnParents=false] only return the topmost selected
* node (useful with selectMode 3)
* @returns {FancytreeNode[]}
*/
getSelectedNodes: function(stopOnParents) {
var nodeList = [];
this.visit(function(node){
if( node.selected ) {
nodeList.push(node);
if( stopOnParents === true ){
return "skip"; // stop processing this branch
}
}
});
return nodeList;
},
/** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded).
* @returns {boolean | undefined}
*/
hasChildren: function() {
if(this.lazy){
if(this.children == null ){
// null or undefined: Not yet loaded
return undefined;
}else if(this.children.length === 0){
// Loaded, but response was empty
return false;
}else if(this.children.length === 1 && this.children[0].isStatusNode() ){
// Currently loading or load error
return undefined;
}
return true;
}
return !!( this.children && this.children.length );
},
/** Return true if node has keyboard focus.
* @returns {boolean}
*/
hasFocus: function() {
return (this.tree.hasFocus() && this.tree.focusNode === this);
},
/** Write to browser console if debugLevel >= 1 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
info: function(msg){
if( this.tree.options.debugLevel >= 1 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("info", arguments);
}
},
/** Return true if node is active (see also FancytreeNode#isSelected).
* @returns {boolean}
*/
isActive: function() {
return (this.tree.activeNode === this);
},
/** Return true if node is a direct child of otherNode.
* @param {FancytreeNode} otherNode
* @returns {boolean}
*/
isChildOf: function(otherNode) {
return (this.parent && this.parent === otherNode);
},
/** Return true, if node is a direct or indirect sub node of otherNode.
* @param {FancytreeNode} otherNode
* @returns {boolean}
*/
isDescendantOf: function(otherNode) {
if(!otherNode || otherNode.tree !== this.tree){
return false;
}
var p = this.parent;
while( p ) {
if( p === otherNode ){
return true;
}
p = p.parent;
}
return false;
},
/** Return true if node is expanded.
* @returns {boolean}
*/
isExpanded: function() {
return !!this.expanded;
},
/** Return true if node is the first node of its parent's children.
* @returns {boolean}
*/
isFirstSibling: function() {
var p = this.parent;
return !p || p.children[0] === this;
},
/** Return true if node is a folder, i.e. has the node.folder attribute set.
* @returns {boolean}
*/
isFolder: function() {
return !!this.folder;
},
/** Return true if node is the last node of its parent's children.
* @returns {boolean}
*/
isLastSibling: function() {
var p = this.parent;
return !p || p.children[p.children.length-1] === this;
},
/** Return true if node is lazy (even if data was already loaded)
* @returns {boolean}
*/
isLazy: function() {
return !!this.lazy;
},
/** Return true if node is lazy and loaded. For non-lazy nodes always return true.
* @returns {boolean}
*/
isLoaded: function() {
return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node
},
/** Return true if children are currently beeing loaded, i.e. a Ajax request is pending.
* @returns {boolean}
*/
isLoading: function() {
return !!this._isLoading;
},
/*
* @deprecated since v2.4.0: Use isRootNode() instead
*/
isRoot: function() {
return this.isRootNode();
},
/** (experimental) Return true if this is partially loaded.
* @returns {boolean}
* @since 2.15
*/
isPartload: function() {
return !!this.partload;
},
/** Return true if this is the (invisible) system root node.
* @returns {boolean}
* @since 2.4
*/
isRootNode: function() {
return (this.tree.rootNode === this);
},
/** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive).
* @returns {boolean}
*/
isSelected: function() {
return !!this.selected;
},
/** Return true if this node is a temporarily generated system node like
* 'loading', 'paging', or 'error' (node.statusNodeType contains the type).
* @returns {boolean}
*/
isStatusNode: function() {
return !!this.statusNodeType;
},
/** Return true if this node is a status node of type 'paging'.
* @returns {boolean}
* @since 2.15
*/
isPagingNode: function() {
return this.statusNodeType === "paging";
},
/** Return true if this a top level node, i.e. a direct child of the (invisible) system root node.
* @returns {boolean}
* @since 2.4
*/
isTopLevel: function() {
return (this.tree.rootNode === this.parent);
},
/** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false.
* @returns {boolean}
*/
isUndefined: function() {
return this.hasChildren() === undefined; // also checks if the only child is a status node
},
/** Return true if all parent nodes are expanded. Note: this does not check
* whether the node is scrolled into the visible part of the screen.
* @returns {boolean}
*/
isVisible: function() {
var i, l,
parents = this.getParentList(false, false);
for(i=0, l=parents.length; i<l; i++){
if( ! parents[i].expanded ){ return false; }
}
return true;
},
/** Deprecated.
* @deprecated since 2014-02-16: use load() instead.
*/
lazyLoad: function(discard) {
this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead.");
return this.load(discard);
},
/**
* Load all children of a lazy node if neccessary. The <i>expanded</i> state is maintained.
* @param {boolean} [forceReload=false] Pass true to discard any existing nodes before. Otherwise this method does nothing if the node was already loaded.
* @returns {$.Promise}
*/
load: function(forceReload) {
var res, source,
that = this,
wasExpanded = this.isExpanded();
_assert( this.isLazy(), "load() requires a lazy node" );
// _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" );
if( !forceReload && !this.isUndefined() ) {
return _getResolvedPromise(this);
}
if( this.isLoaded() ){
this.resetLazy(); // also collapses
}
// This method is also called by setExpanded() and loadKeyPath(), so we
// have to avoid recursion.
source = this.tree._triggerNodeEvent("lazyLoad", this);
if( source === false ) { // #69
return _getResolvedPromise(this);
}
_assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
res = this.tree._callHook("nodeLoadChildren", this, source);
if( wasExpanded ) {
this.expanded = true;
res.always(function(){
that.render();
});
} else {
res.always(function(){
that.renderStatus(); // fix expander icon to 'loaded'
});
}
return res;
},
/** Expand all parents and optionally scroll into visible area as neccessary.
* Promise is resolved, when lazy loading and animations are done.
* @param {object} [opts] passed to `setExpanded()`.
* Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true}
* @returns {$.Promise}
*/
makeVisible: function(opts) {
var i,
that = this,
deferreds = [],
dfd = new $.Deferred(),
parents = this.getParentList(false, false),
len = parents.length,
effects = !(opts && opts.noAnimation === true),
scroll = !(opts && opts.scrollIntoView === false);
// Expand bottom-up, so only the top node is animated
for(i = len - 1; i >= 0; i--){
// that.debug("pushexpand" + parents[i]);
deferreds.push(parents[i].setExpanded(true, opts));
}
$.when.apply($, deferreds).done(function(){
// All expands have finished
// that.debug("expand DONE", scroll);
if( scroll ){
that.scrollIntoView(effects).done(function(){
// that.debug("scroll DONE");
dfd.resolve();
});
} else {
dfd.resolve();
}
});
return dfd.promise();
},
/** Move this node to targetNode.
* @param {FancytreeNode} targetNode
* @param {string} mode <pre>
* 'child': append this node as last child of targetNode.
* This is the default. To be compatble with the D'n'd
* hitMode, we also accept 'over'.
* 'firstChild': add this node as first child of targetNode.
* 'before': add this node as sibling before targetNode.
* 'after': add this node as sibling after targetNode.</pre>
* @param {function} [map] optional callback(FancytreeNode) to allow modifcations
*/
moveTo: function(targetNode, mode, map) {
if(mode === undefined || mode === "over"){
mode = "child";
} else if ( mode === "firstChild" ) {
if( targetNode.children && targetNode.children.length ) {
mode = "before";
targetNode = targetNode.children[0];
} else {
mode = "child";
}
}
var pos,
prevParent = this.parent,
targetParent = (mode === "child") ? targetNode : targetNode.parent;
if(this === targetNode){
return;
}else if( !this.parent ){
$.error("Cannot move system root");
}else if( targetParent.isDescendantOf(this) ){
$.error("Cannot move a node to its own descendant");
}
if( targetParent !== prevParent ) {
prevParent.triggerModifyChild("remove", this);
}
// Unlink this node from current parent
if( this.parent.children.length === 1 ) {
if( this.parent === targetParent ){
return; // #258
}
this.parent.children = this.parent.lazy ? [] : null;
this.parent.expanded = false;
} else {
pos = $.inArray(this, this.parent.children);
_assert(pos >= 0, "invalid source parent");
this.parent.children.splice(pos, 1);
}
// Remove from source DOM parent
// if(this.parent.ul){
// this.parent.ul.removeChild(this.li);
// }
// Insert this node to target parent's child list
this.parent = targetParent;
if( targetParent.hasChildren() ) {
switch(mode) {
case "child":
// Append to existing target children
targetParent.children.push(this);
break;
case "before":
// Insert this node before target node
pos = $.inArray(targetNode, targetParent.children);
_assert(pos >= 0, "invalid target parent");
targetParent.children.splice(pos, 0, this);
break;
case "after":
// Insert this node after target node
pos = $.inArray(targetNode, targetParent.children);
_assert(pos >= 0, "invalid target parent");
targetParent.children.splice(pos+1, 0, this);
break;
default:
$.error("Invalid mode " + mode);
}
} else {
targetParent.children = [ this ];
}
// Parent has no <ul> tag yet:
// if( !targetParent.ul ) {
// // This is the parent's first child: create UL tag
// // (Hidden, because it will be
// targetParent.ul = document.createElement("ul");
// targetParent.ul.style.display = "none";
// targetParent.li.appendChild(targetParent.ul);
// }
// // Issue 319: Add to target DOM parent (only if node was already rendered(expanded))
// if(this.li){
// targetParent.ul.appendChild(this.li);
// }^
// Let caller modify the nodes
if( map ){
targetNode.visit(map, true);
}
if( targetParent === prevParent ) {
targetParent.triggerModifyChild("move", this);
} else {
// prevParent.triggerModifyChild("remove", this);
targetParent.triggerModifyChild("add", this);
}
// Handle cross-tree moves
if( this.tree !== targetNode.tree ) {
// Fix node.tree for all source nodes
// _assert(false, "Cross-tree move is not yet implemented.");
this.warn("Cross-tree moveTo is experimantal!");
this.visit(function(n){
// TODO: fix selection state and activation, ...
n.tree = targetNode.tree;
}, true);
}
// A collaposed node won't re-render children, so we have to remove it manually
// if( !targetParent.expanded ){
// prevParent.ul.removeChild(this.li);
// }
// Update HTML markup
if( !prevParent.isDescendantOf(targetParent)) {
prevParent.render();
}
if( !targetParent.isDescendantOf(prevParent) && targetParent !== prevParent) {
targetParent.render();
}
// TODO: fix selection state
// TODO: fix active state
/*
var tree = this.tree;
var opts = tree.options;
var pers = tree.persistence;
// Always expand, if it's below minExpandLevel
// tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel());
if ( opts.minExpandLevel >= ftnode.getLevel() ) {
// tree.logDebug ("Force expand for %o", ftnode);
this.bExpanded = true;
}
// In multi-hier mode, update the parents selection state
// DT issue #82: only if not initializing, because the children may not exist yet
// if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing )
// ftnode._fixSelectionState();
// In multi-hier mode, update the parents selection state
if( ftnode.bSelected && opts.selectMode==3 ) {
var p = this;
while( p ) {
if( !p.hasSubSel )
p._setSubSel(true);
p = p.parent;
}
}
// render this node and the new child
if ( tree.bEnableUpdate )
this.render();
return ftnode;
*/
},
/** Set focus relative to this node and optionally activate.
*
* @param {number} where The keyCode that would normally trigger this move,
* e.g. `$.ui.keyCode.LEFT` would collapse the node if it
* is expanded or move to the parent oterwise.
* @param {boolean} [activate=true]
* @returns {$.Promise}
*/
navigate: function(where, activate) {
var i, parents, res,
handled = true,
KC = $.ui.keyCode,
sib = null;
// Navigate to node
function _goto(n){
if( n ){
// setFocus/setActive will scroll later (if autoScroll is specified)
try { n.makeVisible({scrollIntoView: false}); } catch(e) {} // #272
// Node may still be hidden by a filter
if( ! $(n.span).is(":visible") ) {
n.debug("Navigate: skipping hidden node");
n.navigate(where, activate);
return;
}
return activate === false ? n.setFocus() : n.setActive();
}
}
switch( where ) {
case KC.BACKSPACE:
if( this.parent && this.parent.parent ) {
res = _goto(this.parent);
}
break;
case KC.HOME:
this.tree.visit(function(n){ // goto first visible node
if( $(n.span).is(":visible") ) {
res = _goto(n);
return false;
}
});
break;
case KC.END:
this.tree.visit(function(n){ // goto last visible node
if( $(n.span).is(":visible") ) {
res = n;
}
});
if( res ) {
res = _goto(res);
}
break;
case KC.LEFT:
if( this.expanded ) {
this.setExpanded(false);
res = _goto(this);
} else if( this.parent && this.parent.parent ) {
res = _goto(this.parent);
}
break;
case KC.RIGHT:
if( !this.expanded && (this.children || this.lazy) ) {
this.setExpanded();
res = _goto(this);
} else if( this.children && this.children.length ) {
res = _goto(this.children[0]);
}
break;
case KC.UP:
sib = this.getPrevSibling();
// #359: skip hidden sibling nodes, preventing a _goto() recursion
while( sib && !$(sib.span).is(":visible") ) {
sib = sib.getPrevSibling();
}
while( sib && sib.expanded && sib.children && sib.children.length ) {
sib = sib.children[sib.children.length - 1];
}
if( !sib && this.parent && this.parent.parent ){
sib = this.parent;
}
res = _goto(sib);
break;
case KC.DOWN:
if( this.expanded && this.children && this.children.length ) {
sib = this.children[0];
} else {
parents = this.getParentList(false, true);
for(i=parents.length-1; i>=0; i--) {
sib = parents[i].getNextSibling();
// #359: skip hidden sibling nodes, preventing a _goto() recursion
while( sib && !$(sib.span).is(":visible") ) {
sib = sib.getNextSibling();
}
if( sib ){ break; }
}
}
res = _goto(sib);
break;
default:
handled = false;
}
return res || _getResolvedPromise();
},
/**
* Remove this node (not allowed for system root).
*/
remove: function() {
return this.parent.removeChild(this);
},
/**
* Remove childNode from list of direct children.
* @param {FancytreeNode} childNode
*/
removeChild: function(childNode) {
return this.tree._callHook("nodeRemoveChild", this, childNode);
},
/**
* Remove all child nodes and descendents. This converts the node into a leaf.<br>
* If this was a lazy node, it is still considered 'loaded'; call node.resetLazy()
* in order to trigger lazyLoad on next expand.
*/
removeChildren: function() {
return this.tree._callHook("nodeRemoveChildren", this);
},
/**
* Remove class from node's span tag and .extraClasses.
*
* @param {string} className class name
*
* @since 2.17
*/
removeClass: function(className){
return this.toggleClass(className, false);
},
/**
* This method renders and updates all HTML markup that is required
* to display this node in its current state.<br>
* Note:
* <ul>
* <li>It should only be neccessary to call this method after the node object
* was modified by direct access to its properties, because the common
* API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...)
* already handle this.
* <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus}
* are implied. If changes are more local, calling only renderTitle() or
* renderStatus() may be sufficient and faster.
* </ul>
*
* @param {boolean} [force=false] re-render, even if html markup was already created
* @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
*/
render: function(force, deep) {
return this.tree._callHook("nodeRender", this, force, deep);
},
/** Create HTML markup for the node's outer <span> (expander, checkbox, icon, and title).
* Implies {@link FancytreeNode#renderStatus}.
* @see Fancytree_Hooks#nodeRenderTitle
*/
renderTitle: function() {
return this.tree._callHook("nodeRenderTitle", this);
},
/** Update element's CSS classes according to node state.
* @see Fancytree_Hooks#nodeRenderStatus
*/
renderStatus: function() {
return this.tree._callHook("nodeRenderStatus", this);
},
/**
* (experimental) Replace this node with `source`.
* (Currently only available for paging nodes.)
* @param {NodeData[]} source List of child node definitions
* @since 2.15
*/
replaceWith: function(source) {
var res,
parent = this.parent,
pos = $.inArray(this, parent.children),
that = this;
_assert( this.isPagingNode(), "replaceWith() currently requires a paging status node" );
res = this.tree._callHook("nodeLoadChildren", this, source);
res.done(function(data){
// New nodes are currently children of `this`.
var children = that.children;
// Prepend newly loaded child nodes to `this`
// Move new children after self
for( i=0; i<children.length; i++ ) {
children[i].parent = parent;
}
parent.children.splice.apply(parent.children, [pos + 1, 0].concat(children));
// Remove self
that.children = null;
that.remove();
// Redraw new nodes
parent.render();
// TODO: set node.partload = false if this was tha last paging node?
// parent.addPagingNode(false);
}).fail(function(){
that.setExpanded();
});
return res;
// $.error("Not implemented: replaceWith()");
},
/**
* Remove all children, collapse, and set the lazy-flag, so that the lazyLoad
* event is triggered on next expand.
*/
resetLazy: function() {
this.removeChildren();
this.expanded = false;
this.lazy = true;
this.children = undefined;
this.renderStatus();
},
/** Schedule activity for delayed execution (cancel any pending request).
* scheduleAction('cancel') will only cancel a pending request (if any).
* @param {string} mode
* @param {number} ms
*/
scheduleAction: function(mode, ms) {
if( this.tree.timer ) {
clearTimeout(this.tree.timer);
// this.tree.debug("clearTimeout(%o)", this.tree.timer);
}
this.tree.timer = null;
var self = this; // required for closures
switch (mode) {
case "cancel":
// Simply made sure that timer was cleared
break;
case "expand":
this.tree.timer = setTimeout(function(){
self.tree.debug("setTimeout: trigger expand");
self.setExpanded(true);
}, ms);
break;
case "activate":
this.tree.timer = setTimeout(function(){
self.tree.debug("setTimeout: trigger activate");
self.setActive(true);
}, ms);
break;
default:
$.error("Invalid mode " + mode);
}
// this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer);
},
/**
*
* @param {boolean | PlainObject} [effects=false] animation options.
* @param {object} [options=null] {topNode: null, effects: ..., parent: ...} this node will remain visible in
* any case, even if `this` is outside the scroll pane.
* @returns {$.Promise}
*/
scrollIntoView: function(effects, options) {
if( options !== undefined && _isNode(options) ) {
this.warn("scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead.");
options = {topNode: options};
}
// this.$scrollParent = (this.options.scrollParent === "auto") ? $ul.scrollParent() : $(this.options.scrollParent);
// this.$scrollParent = this.$scrollParent.length ? this.$scrollParent || this.$container;
var topNodeY, nodeY, horzScrollbarHeight, containerOffsetTop,
opts = $.extend({
effects: (effects === true) ? {duration: 200, queue: false} : effects,
scrollOfs: this.tree.options.scrollOfs,
scrollParent: this.tree.options.scrollParent || this.tree.$container,
topNode: null
}, options),
dfd = new $.Deferred(),
that = this,
nodeHeight = $(this.span).height(),
$container = $(opts.scrollParent),
topOfs = opts.scrollOfs.top || 0,
bottomOfs = opts.scrollOfs.bottom || 0,
containerHeight = $container.height(),// - topOfs - bottomOfs,
scrollTop = $container.scrollTop(),
$animateTarget = $container,
isParentWindow = $container[0] === window,
topNode = opts.topNode || null,
newScrollTop = null;
// this.debug("scrollIntoView(), scrollTop=" + scrollTop, opts.scrollOfs);
// _assert($(this.span).is(":visible"), "scrollIntoView node is invisible"); // otherwise we cannot calc offsets
if( !$(this.span).is(":visible") ) {
// We cannot calc offsets for hidden elements
this.warn("scrollIntoView(): node is invisible.");
return _getResolvedPromise();
}
if( isParentWindow ) {
nodeY = $(this.span).offset().top;
topNodeY = (topNode && topNode.span) ? $(topNode.span).offset().top : 0;
$animateTarget = $("html,body");
} else {
_assert($container[0] !== document && $container[0] !== document.body,
"scrollParent should be a simple element or `window`, not document or body.");
containerOffsetTop = $container.offset().top,
nodeY = $(this.span).offset().top - containerOffsetTop + scrollTop; // relative to scroll parent
topNodeY = topNode ? $(topNode.span).offset().top - containerOffsetTop + scrollTop : 0;
horzScrollbarHeight = Math.max(0, ($container.innerHeight() - $container[0].clientHeight));
containerHeight -= horzScrollbarHeight;
}
// this.debug(" scrollIntoView(), nodeY=" + nodeY + ", containerHeight=" + containerHeight);
if( nodeY < (scrollTop + topOfs) ){
// Node is above visible container area
newScrollTop = nodeY - topOfs;
// this.debug(" scrollIntoView(), UPPER newScrollTop=" + newScrollTop);
}else if((nodeY + nodeHeight) > (scrollTop + containerHeight - bottomOfs)){
newScrollTop = nodeY + nodeHeight - containerHeight + bottomOfs;
// this.debug(" scrollIntoView(), LOWER newScrollTop=" + newScrollTop);
// If a topNode was passed, make sure that it is never scrolled
// outside the upper border
if(topNode){
_assert(topNode.isRootNode() || $(topNode.span).is(":visible"), "topNode must be visible");
if( topNodeY < newScrollTop ){
newScrollTop = topNodeY - topOfs;
// this.debug(" scrollIntoView(), TOP newScrollTop=" + newScrollTop);
}
}
}
if(newScrollTop !== null){
// this.debug(" scrollIntoView(), SET newScrollTop=" + newScrollTop);
if(opts.effects){
opts.effects.complete = function(){
dfd.resolveWith(that);
};
$animateTarget.stop(true).animate({
scrollTop: newScrollTop
}, opts.effects);
}else{
$animateTarget[0].scrollTop = newScrollTop;
dfd.resolveWith(this);
}
}else{
dfd.resolveWith(this);
}
return dfd.promise();
},
/**Activate this node.
* @param {boolean} [flag=true] pass false to deactivate
* @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false}
* @returns {$.Promise}
*/
setActive: function(flag, opts){
return this.tree._callHook("nodeSetActive", this, flag, opts);
},
/**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done.
* @param {boolean} [flag=true] pass false to collapse
* @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
* @returns {$.Promise}
*/
setExpanded: function(flag, opts){
return this.tree._callHook("nodeSetExpanded", this, flag, opts);
},
/**Set keyboard focus to this node.
* @param {boolean} [flag=true] pass false to blur
* @see Fancytree#setFocus
*/
setFocus: function(flag){
return this.tree._callHook("nodeSetFocus", this, flag);
},
/**Select this node, i.e. check the checkbox.
* @param {boolean} [flag=true] pass false to deselect
*/
setSelected: function(flag){
return this.tree._callHook("nodeSetSelected", this, flag);
},
/**Mark a lazy node as 'error', 'loading', 'nodata', or 'ok'.
* @param {string} status 'error'|'empty'|'ok'
* @param {string} [message]
* @param {string} [details]
*/
setStatus: function(status, message, details){
return this.tree._callHook("nodeSetStatus", this, status, message, details);
},
/**Rename this node.
* @param {string} title
*/
setTitle: function(title){
this.title = title;
this.renderTitle();
this.triggerModify("rename");
},
/**Sort child list by title.
* @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title).
* @param {boolean} [deep=false] pass true to sort all descendant nodes
*/
sortChildren: function(cmp, deep) {
var i,l,
cl = this.children;
if( !cl ){
return;
}
cmp = cmp || function(a, b) {
var x = a.title.toLowerCase(),
y = b.title.toLowerCase();
return x === y ? 0 : x > y ? 1 : -1;
};
cl.sort(cmp);
if( deep ){
for(i=0, l=cl.length; i<l; i++){
if( cl[i].children ){
cl[i].sortChildren(cmp, "$norender$");
}
}
}
if( deep !== "$norender$" ){
this.render();
}
this.triggerModifyChild("sort");
},
/** Convert node (or whole branch) into a plain object.
*
* The result is compatible with node.addChildren().
*
* @param {boolean} [recursive=false] include child nodes
* @param {function} [callback] callback(dict, node) is called for every node, in order to allow modifications
* @returns {NodeData}
*/
toDict: function(recursive, callback) {
var i, l, node,
dict = {},
self = this;
$.each(NODE_ATTRS, function(i, a){
if(self[a] || self[a] === false){
dict[a] = self[a];
}
});
if(!$.isEmptyObject(this.data)){
dict.data = $.extend({}, this.data);
if($.isEmptyObject(dict.data)){
delete dict.data;
}
}
if( callback ){
callback(dict, self);
}
if( recursive ) {
if(this.hasChildren()){
dict.children = [];
for(i=0, l=this.children.length; i<l; i++ ){
node = this.children[i];
if( !node.isStatusNode() ){
dict.children.push(node.toDict(true, callback));
}
}
}else{
// dict.children = null;
}
}
return dict;
},
/**
* Set, clear, or toggle class of node's span tag and .extraClasses.
*
* @param {string} className class name (separate multiple classes by space)
* @param {boolean} [flag] true/false to add/remove class. If omitted, class is toggled.
* @returns {boolean} true if a class was added
*
* @since 2.17
*/
toggleClass: function(value, flag){
var className, hasClass,
rnotwhite = ( /\S+/g ),
classNames = value.match( rnotwhite ) || [],
i = 0,
wasAdded = false,
statusElem = this[this.tree.statusClassPropName],
curClasses = (" " + (this.extraClasses || "") + " ");
// this.info("toggleClass('" + value + "', " + flag + ")", curClasses);
// Modify DOM element directly if it already exists
if( statusElem ) {
$(statusElem).toggleClass(value, flag);
}
// Modify node.extraClasses to make this change persistent
// Toggle if flag was not passed
while ( className = classNames[ i++ ] ) {
hasClass = curClasses.indexOf(" " + className + " ") >= 0;
flag = (flag === undefined) ? (!hasClass) : !!flag;
if ( flag ) {
if( !hasClass ) {
curClasses += className + " ";
wasAdded = true;
}
} else {
while ( curClasses.indexOf( " " + className + " " ) > -1 ) {
curClasses = curClasses.replace( " " + className + " ", " " );
}
}
}
this.extraClasses = $.trim(curClasses);
// this.info("-> toggleClass('" + value + "', " + flag + "): '" + this.extraClasses + "'");
return wasAdded;
},
/** Flip expanded status. */
toggleExpanded: function(){
return this.tree._callHook("nodeToggleExpanded", this);
},
/** Flip selection status. */
toggleSelected: function(){
return this.tree._callHook("nodeToggleSelected", this);
},
toString: function() {
return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>";
},
/**
* Trigger `modifyChild` event on a parent to signal that a child was modified.
* @param {string} operation Type of change: 'add', 'remove', 'rename', 'move', 'data', ...
* @param {FancytreeNode} [childNode]
* @param {object} [extra]
*/
triggerModifyChild: function(operation, childNode, extra){
var data,
modifyChild = this.tree.options.modifyChild;
if ( modifyChild ){
if( childNode && childNode.parent !== this ) {
$.error("childNode " + childNode + " is not a child of " + this);
}
data = {
node: this,
tree: this.tree,
operation: operation,
childNode: childNode || null
};
if( extra ) {
$.extend(data, extra);
}
modifyChild({type: "modifyChild"}, data);
}
},
/**
* Trigger `modifyChild` event on node.parent(!).
* @param {string} operation Type of change: 'add', 'remove', 'rename', 'move', 'data', ...
* @param {object} [extra]
*/
triggerModify: function(operation, extra){
this.parent.triggerModifyChild(operation, this, extra);
},
/** Call fn(node) for all child nodes.<br>
* Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br>
* Return false if iteration was stopped.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and
* its children only.
* @param {boolean} [includeSelf=false]
* @returns {boolean}
*/
visit: function(fn, includeSelf) {
var i, l,
res = true,
children = this.children;
if( includeSelf === true ) {
res = fn(this);
if( res === false || res === "skip" ){
return res;
}
}
if(children){
for(i=0, l=children.length; i<l; i++){
res = children[i].visit(fn, true);
if( res === false ){
break;
}
}
}
return res;
},
/** Call fn(node) for all child nodes and recursively load lazy children.<br>
* <b>Note:</b> If you need this method, you probably should consider to review
* your architecture! Recursivley loading nodes is a perfect way for lazy
* programmers to flood the server with requests ;-)
*
* @param {function} [fn] optional callback function.
* Return false to stop iteration, return "skip" to skip this node and
* its children only.
* @param {boolean} [includeSelf=false]
* @returns {$.Promise}
* @since 2.4
*/
visitAndLoad: function(fn, includeSelf, _recursion) {
var dfd, res, loaders,
node = this;
// node.debug("visitAndLoad");
if( fn && includeSelf === true ) {
res = fn(node);
if( res === false || res === "skip" ) {
return _recursion ? res : _getResolvedPromise();
}
}
if( !node.children && !node.lazy ) {
return _getResolvedPromise();
}
dfd = new $.Deferred();
loaders = [];
// node.debug("load()...");
node.load().done(function(){
// node.debug("load()... done.");
for(var i=0, l=node.children.length; i<l; i++){
res = node.children[i].visitAndLoad(fn, true, true);
if( res === false ) {
dfd.reject();
break;
} else if ( res !== "skip" ) {
loaders.push(res); // Add promise to the list
}
}
$.when.apply(this, loaders).then(function(){
dfd.resolve();
});
});
return dfd.promise();
},
/** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br>
* Stop iteration, if fn() returns false.<br>
* Return false if iteration was stopped.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and children only.
* @param {boolean} [includeSelf=false]
* @returns {boolean}
*/
visitParents: function(fn, includeSelf) {
// Visit parent nodes (bottom up)
if(includeSelf && fn(this) === false){
return false;
}
var p = this.parent;
while( p ) {
if(fn(p) === false){
return false;
}
p = p.parent;
}
return true;
},
/** Write warning to browser console (prepending node info)
*
* @param {*} msg string or object or array of such
*/
warn: function(msg){
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("warn", arguments);
}
};
/* *****************************************************************************
* Fancytree
*/
/**
* Construct a new tree object.
*
* @class Fancytree
* @classdesc The controller behind a fancytree.
* This class also contains 'hook methods': see {@link Fancytree_Hooks}.
*
* @param {Widget} widget
*
* @property {string} _id Automatically generated unique tree instance ID, e.g. "1".
* @property {string} _ns Automatically generated unique tree namespace, e.g. ".fancytree-1".
* @property {FancytreeNode} activeNode Currently active node or null.
* @property {string} ariaPropName Property name of FancytreeNode that contains the element which will receive the aria attributes.
* Typically "li", but "tr" for table extension.
* @property {jQueryObject} $container Outer <ul> element (or <table> element for ext-table).
* @property {jQueryObject} $div A jQuery object containing the element used to instantiate the tree widget (`widget.element`)
* @property {object} data Metadata, i.e. properties that may be passed to `source` in addition to a children array.
* @property {object} ext Hash of all active plugin instances.
* @property {FancytreeNode} focusNode Currently focused node or null.
* @property {FancytreeNode} lastSelectedNode Used to implement selectMode 1 (single select)
* @property {string} nodeContainerAttrName Property name of FancytreeNode that contains the outer element of single nodes.
* Typically "li", but "tr" for table extension.
* @property {FancytreeOptions} options Current options, i.e. default options + options passed to constructor.
* @property {FancytreeNode} rootNode Invisible system root node.
* @property {string} statusClassPropName Property name of FancytreeNode that contains the element which will receive the status classes.
* Typically "span", but "tr" for table extension.
* @property {object} widget Base widget instance.
*/
function Fancytree(widget) {
this.widget = widget;
this.$div = widget.element;
this.options = widget.options;
if( this.options ) {
if( $.isFunction(this.options.lazyload ) && !$.isFunction(this.options.lazyLoad) ) {
this.options.lazyLoad = function() {
FT.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead.");
return widget.options.lazyload.apply(this, arguments);
};
}
if( $.isFunction(this.options.loaderror) ) {
$.error("The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead.");
}
if( this.options.fx !== undefined ) {
FT.warn("The 'fx' option was replaced by 'toggleEffect' since 2014-11-30.");
}
if( this.options.removeNode !== undefined ) {
$.error("The 'removeNode' event was replaced by 'modifyChild' since 2.20 (2016-09-10).");
}
}
this.ext = {}; // Active extension instances
// allow to init tree.data.foo from <div data-foo=''>
this.data = _getElementDataAsDict(this.$div);
// TODO: use widget.uuid instead?
this._id = $.ui.fancytree._nextId++;
// TODO: use widget.eventNamespace instead?
this._ns = ".fancytree-" + this._id; // append for namespaced events
this.activeNode = null;
this.focusNode = null;
this._hasFocus = null;
this._enableUpdate = true;
// this._dirtyRoots = null;
this.lastSelectedNode = null;
this.systemFocusElement = null;
this.lastQuicksearchTerm = "";
this.lastQuicksearchTime = 0;
this.statusClassPropName = "span";
this.ariaPropName = "li";
this.nodeContainerAttrName = "li";
// Remove previous markup if any
this.$div.find(">ul.fancytree-container").remove();
// Create a node without parent.
var fakeParent = { tree: this },
$ul;
this.rootNode = new FancytreeNode(fakeParent, {
title: "root",
key: "root_" + this._id,
children: null,
expanded: true
});
this.rootNode.parent = null;
// Create root markup
$ul = $("<ul>", {
"class": "ui-fancytree fancytree-container fancytree-plain"
}).appendTo(this.$div);
this.$container = $ul;
this.rootNode.ul = $ul[0];
if(this.options.debugLevel == null){
this.options.debugLevel = FT.debugLevel;
}
// // Add container to the TAB chain
// // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant
// // #577: Allow to set tabindex to "0", "-1" and ""
// this.$container.attr("tabindex", this.options.tabindex);
// if( this.options.rtl ) {
// this.$container.attr("DIR", "RTL").addClass("fancytree-rtl");
// // }else{
// // this.$container.attr("DIR", null).removeClass("fancytree-rtl");
// }
// if(this.options.aria){
// this.$container.attr("role", "tree");
// if( this.options.selectMode !== 1 ) {
// this.$container.attr("aria-multiselectable", true);
// }
// }
}
Fancytree.prototype = /** @lends Fancytree# */{
/* Return a context object that can be re-used for _callHook().
* @param {Fancytree | FancytreeNode | EventData} obj
* @param {Event} originalEvent
* @param {Object} extra
* @returns {EventData}
*/
_makeHookContext: function(obj, originalEvent, extra) {
var ctx, tree;
if(obj.node !== undefined){
// obj is already a context object
if(originalEvent && obj.originalEvent !== originalEvent){
$.error("invalid args");
}
ctx = obj;
}else if(obj.tree){
// obj is a FancytreeNode
tree = obj.tree;
ctx = { node: obj, tree: tree, widget: tree.widget, options: tree.widget.options, originalEvent: originalEvent };
}else if(obj.widget){
// obj is a Fancytree
ctx = { node: null, tree: obj, widget: obj.widget, options: obj.widget.options, originalEvent: originalEvent };
}else{
$.error("invalid args");
}
if(extra){
$.extend(ctx, extra);
}
return ctx;
},
/* Trigger a hook function: funcName(ctx, [...]).
*
* @param {string} funcName
* @param {Fancytree|FancytreeNode|EventData} contextObject
* @param {any} [_extraArgs] optional additional arguments
* @returns {any}
*/
_callHook: function(funcName, contextObject, _extraArgs) {
var ctx = this._makeHookContext(contextObject),
fn = this[funcName],
args = Array.prototype.slice.call(arguments, 2);
if(!$.isFunction(fn)){
$.error("_callHook('" + funcName + "') is not a function");
}
args.unshift(ctx);
// this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args);
return fn.apply(this, args);
},
/* Check if current extensions dependencies are met and throw an error if not.
*
* This method may be called inside the `treeInit` hook for custom extensions.
*
* @param {string} extension name of the required extension
* @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present
* @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter)
* @param {string} [message] optional error message (defaults to a descriptve error message)
*/
_requireExtension: function(name, required, before, message) {
before = !!before;
var thisName = this._local.name,
extList = this.options.extensions,
isBefore = $.inArray(name, extList) < $.inArray(thisName, extList),
isMissing = required && this.ext[name] == null,
badOrder = !isMissing && before != null && (before !== isBefore);
_assert(thisName && thisName !== name, "invalid or same name");
if( isMissing || badOrder ){
if( !message ){
if( isMissing || required ){
message = "'" + thisName + "' extension requires '" + name + "'";
if( badOrder ){
message += " to be registered " + (before ? "before" : "after") + " itself";
}
}else{
message = "If used together, `" + name + "` must be registered " + (before ? "before" : "after") + " `" + thisName + "`";
}
}
$.error(message);
return false;
}
return true;
},
/** Activate node with a given key and fire focus and activate events.
*
* A prevously activated node will be deactivated.
* If activeVisible option is set, all parents will be expanded as necessary.
* Pass key = false, to deactivate the current node only.
* @param {string} key
* @returns {FancytreeNode} activated node (null, if not found)
*/
activateKey: function(key) {
var node = this.getNodeByKey(key);
if(node){
node.setActive();
}else if(this.activeNode){
this.activeNode.setActive(false);
}
return node;
},
/** (experimental) Add child status nodes that indicate 'More...', ....
* @param {boolean|object} node optional node definition. Pass `false` to remove all paging nodes.
* @param {string} [mode='append'] 'child'|firstChild'
* @since 2.15
*/
addPagingNode: function(node, mode){
return this.rootNode.addPagingNode(node, mode);
},
/** (experimental) Modify existing data model.
*
* @param {Array} patchList array of [key, NodePatch] arrays
* @returns {$.Promise} resolved, when all patches have been applied
* @see TreePatch
*/
applyPatch: function(patchList) {
var dfd, i, p2, key, patch, node,
patchCount = patchList.length,
deferredList = [];
for(i=0; i<patchCount; i++){
p2 = patchList[i];
_assert(p2.length === 2, "patchList must be an array of length-2-arrays");
key = p2[0];
patch = p2[1];
node = (key === null) ? this.rootNode : this.getNodeByKey(key);
if(node){
dfd = new $.Deferred();
deferredList.push(dfd);
node.applyPatch(patch).always(_makeResolveFunc(dfd, node));
}else{
this.warn("could not find node with key '" + key + "'");
}
}
// Return a promise that is resolved, when ALL patches were applied
return $.when.apply($, deferredList).promise();
},
/* TODO: implement in dnd extension
cancelDrag: function() {
var dd = $.ui.ddmanager.current;
if(dd){
dd.cancel();
}
},
*/
/** Remove all nodes.
* @since 2.14
*/
clear: function(source) {
this._callHook("treeClear", this);
},
/** Return the number of nodes.
* @returns {integer}
*/
count: function() {
return this.rootNode.countChildren();
},
/** Write to browser console if debugLevel >= 2 (prepending tree name)
*
* @param {*} msg string or object or array of such
*/
debug: function(msg){
if( this.options.debugLevel >= 2 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("log", arguments);
}
},
// TODO: disable()
// TODO: enable()
/** Temporarily suppress rendering to improve performance on bulk-updates.
*
* @param {boolean} flag
* @returns {boolean} previous status
* @since 2.19
*/
enableUpdate: function(flag) {
flag = ( flag !== false );
/*jshint -W018 */ // Confusing use of '!'
if ( !!this._enableUpdate === !!flag ) {
return flag;
}
/*jshint +W018 */
this._enableUpdate = flag;
if ( flag ) {
this.debug("enableUpdate(true): redraw ", this._dirtyRoots);
this.render();
} else {
// this._dirtyRoots = null;
this.debug("enableUpdate(false)...");
}
return !flag; // return previous value
},
/**Find all nodes that matches condition.
*
* @param {string | function(node)} match title string to search for, or a
* callback function that returns `true` if a node is matched.
* @returns {FancytreeNode[]} array of nodes (may be empty)
* @see FancytreeNode#findAll
* @since 2.12
*/
findAll: function(match) {
return this.rootNode.findAll(match);
},
/**Find first node that matches condition.
*
* @param {string | function(node)} match title string to search for, or a
* callback function that returns `true` if a node is matched.
* @returns {FancytreeNode} matching node or null
* @see FancytreeNode#findFirst
* @since 2.12
*/
findFirst: function(match) {
return this.rootNode.findFirst(match);
},
/** Find the next visible node that starts with `match`, starting at `startNode`
* and wrap-around at the end.
*
* @param {string|function} match
* @param {FancytreeNode} [startNode] defaults to first node
* @returns {FancytreeNode} matching node or null
*/
findNextNode: function(match, startNode, visibleOnly) {
var stopNode = null,
parentChildren = startNode.parent.children,
matchingNode = null,
walkVisible = function(parent, idx, fn) {
var i, grandParent,
parentChildren = parent.children,
siblingCount = parentChildren.length,
node = parentChildren[idx];
// visit node itself
if( node && fn(node) === false ) {
return false;
}
// visit descendants
if( node && node.children && node.expanded ) {
if( walkVisible(node, 0, fn) === false ) {
return false;
}
}
// visit subsequent siblings
for( i = idx + 1; i < siblingCount; i++ ) {
if( walkVisible(parent, i, fn) === false ) {
return false;
}
}
// visit parent's subsequent siblings
grandParent = parent.parent;
if( grandParent ) {
return walkVisible(grandParent, grandParent.children.indexOf(parent) + 1, fn);
} else {
// wrap-around: restart with first node
return walkVisible(parent, 0, fn);
}
};
match = (typeof match === "string") ? _makeNodeTitleStartMatcher(match) : match;
startNode = startNode || this.getFirstChild();
walkVisible(startNode.parent, parentChildren.indexOf(startNode), function(node){
// Stop iteration if we see the start node a second time
if( node === stopNode ) {
return false;
}
stopNode = stopNode || node;
// Ignore nodes hidden by a filter
if( ! $(node.span).is(":visible") ) {
node.debug("quicksearch: skipping hidden node");
return;
}
// Test if we found a match, but search for a second match if this
// was the currently active node
if( match(node) ) {
// node.debug("quicksearch match " + node.title, startNode);
matchingNode = node;
if( matchingNode !== startNode ) {
return false;
}
}
});
return matchingNode;
},
// TODO: fromDict
/**
* Generate INPUT elements that can be submitted with html forms.
*
* In selectMode 3 only the topmost selected nodes are considered, unless
* `opts.stopOnParents: false` is passed.
*
* @example
* // Generate input elements for active and selected nodes
* tree.generateFormElements();
* // Generate input elements selected nodes, using a custom `name` attribute
* tree.generateFormElements("cust_sel", false);
* // Generate input elements using a custom filter
* tree.generateFormElements(true, true, { filter: function(node) {
* return node.isSelected() && node.data.yes;
* }});
*
* @param {boolean | string} [selected=true] Pass false to disable, pass a string to override the field name (default: 'ft_ID[]')
* @param {boolean | string} [active=true] Pass false to disable, pass a string to override the field name (default: 'ft_ID_active')
* @param {object} [opts] default { filter: null, stopOnParents: true }
*/
generateFormElements: function(selected, active, opts) {
opts = opts || {};
var nodeList,
selectedName = (typeof selected === "string") ? selected : "ft_" + this._id + "[]",
activeName = (typeof active === "string") ? active : "ft_" + this._id + "_active",
id = "fancytree_result_" + this._id,
$result = $("#" + id),
stopOnParents = this.options.selectMode === 3 && opts.stopOnParents !== false;
if($result.length){
$result.empty();
}else{
$result = $("<div>", {
id: id
}).hide().insertAfter(this.$container);
}
if(active !== false && this.activeNode){
$result.append($("<input>", {
type: "radio",
name: activeName,
value: this.activeNode.key,
checked: true
}));
}
function _appender( node ) {
$result.append($("<input>", {
type: "checkbox",
name: selectedName,
value: node.key,
checked: true
}));
}
if ( opts.filter ) {
this.visit(function(node) {
var res = opts.filter(node);
if( res === "skip" ) { return res; }
if ( res !== false ) {
_appender(node);
}
});
} else if ( selected !== false ) {
nodeList = this.getSelectedNodes(stopOnParents);
$.each(nodeList, function(idx, node) {
_appender(node);
});
}
},
/**
* Return the currently active node or null.
* @returns {FancytreeNode}
*/
getActiveNode: function() {
return this.activeNode;
},
/** Return the first top level node if any (not the invisible root node).
* @returns {FancytreeNode | null}
*/
getFirstChild: function() {
return this.rootNode.getFirstChild();
},
/**
* Return node that has keyboard focus or null.
* @returns {FancytreeNode}
*/
getFocusNode: function() {
return this.focusNode;
},
/**
* Return node with a given key or null if not found.
* @param {string} key
* @param {FancytreeNode} [searchRoot] only search below this node
* @returns {FancytreeNode | null}
*/
getNodeByKey: function(key, searchRoot) {
// Search the DOM by element ID (assuming this is faster than traversing all nodes).
// $("#...") has problems, if the key contains '.', so we use getElementById()
var el, match;
if(!searchRoot){
el = document.getElementById(this.options.idPrefix + key);
if( el ){
return el.ftnode ? el.ftnode : null;
}
}
// Not found in the DOM, but still may be in an unrendered part of tree
// TODO: optimize with specialized loop
// TODO: consider keyMap?
searchRoot = searchRoot || this.rootNode;
match = null;
searchRoot.visit(function(node){
// window.console.log("getNodeByKey(" + key + "): ", node.key);
if(node.key === key) {
match = node;
return false;
}
}, true);
return match;
},
/** Return the invisible system root node.
* @returns {FancytreeNode}
*/
getRootNode: function() {
return this.rootNode;
},
/**
* Return an array of selected nodes.
* @param {boolean} [stopOnParents=false] only return the topmost selected
* node (useful with selectMode 3)
* @returns {FancytreeNode[]}
*/
getSelectedNodes: function(stopOnParents) {
return this.rootNode.getSelectedNodes(stopOnParents);
},
/** Return true if the tree control has keyboard focus
* @returns {boolean}
*/
hasFocus: function(){
return !!this._hasFocus;
},
/** Write to browser console if debugLevel >= 1 (prepending tree name)
* @param {*} msg string or object or array of such
*/
info: function(msg){
if( this.options.debugLevel >= 1 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("info", arguments);
}
},
/*
TODO: isInitializing: function() {
return ( this.phase=="init" || this.phase=="postInit" );
},
TODO: isReloading: function() {
return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound;
},
TODO: isUserEvent: function() {
return ( this.phase=="userEvent" );
},
*/
/**
* Make sure that a node with a given ID is loaded, by traversing - and
* loading - its parents. This method is ment for lazy hierarchies.
* A callback is executed for every node as we go.
* @example
* tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){
* if(status === "loaded") {
* console.log("loaded intermiediate node " + node);
* }else if(status === "ok") {
* node.activate();
* }
* });
*
* @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7')
* @param {function} callback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error')
* @returns {$.Promise}
*/
loadKeyPath: function(keyPathList, callback, _rootNode) {
var deferredList, dfd, i, path, key, loadMap, node, root, segList,
sep = this.options.keyPathSeparator,
self = this;
callback = callback || $.noop;
if(!$.isArray(keyPathList)){
keyPathList = [keyPathList];
}
// Pass 1: handle all path segments for nodes that are already loaded
// Collect distinct top-most lazy nodes in a map
loadMap = {};
for(i=0; i<keyPathList.length; i++){
root = _rootNode || this.rootNode;
path = keyPathList[i];
// strip leading slash
if(path.charAt(0) === sep){
path = path.substr(1);
}
// traverse and strip keys, until we hit a lazy, unloaded node
segList = path.split(sep);
while(segList.length){
key = segList.shift();
// node = _findDirectChild(root, key);
node = root._findDirectChild(key);
if(!node){
this.warn("loadKeyPath: key not found: " + key + " (parent: " + root + ")");
callback.call(this, key, "error");
break;
}else if(segList.length === 0){
callback.call(this, node, "ok");
break;
}else if(!node.lazy || (node.hasChildren() !== undefined )){
callback.call(this, node, "loaded");
root = node;
}else{
callback.call(this, node, "loaded");
// segList.unshift(key);
if(loadMap[key]){
loadMap[key].push(segList.join(sep));
}else{
loadMap[key] = [segList.join(sep)];
}
break;
}
}
}
// alert("loadKeyPath: loadMap=" + JSON.stringify(loadMap));
// Now load all lazy nodes and continue itearation for remaining paths
deferredList = [];
// Avoid jshint warning 'Don't make functions within a loop.':
function __lazyload(key, node, dfd){
callback.call(self, node, "loading");
node.load().done(function(){
self.loadKeyPath.call(self, loadMap[key], callback, node).always(_makeResolveFunc(dfd, self));
}).fail(function(errMsg){
self.warn("loadKeyPath: error loading: " + key + " (parent: " + root + ")");
callback.call(self, node, "error");
dfd.reject();
});
}
for(key in loadMap){
node = root._findDirectChild(key);
if (node == null) { // #576
node = self.getNodeByKey(key);
}
dfd = new $.Deferred();
deferredList.push(dfd);
__lazyload(key, node, dfd);
}
// Return a promise that is resolved, when ALL paths were loaded
return $.when.apply($, deferredList).promise();
},
/** Re-fire beforeActivate, activate, and (optional) focus events.
* Calling this method in the `init` event, will activate the node that
* was marked 'active' in the source data, and optionally set the keyboard
* focus.
* @param [setFocus=false]
*/
reactivate: function(setFocus) {
var res,
node = this.activeNode;
if( !node ) {
return _getResolvedPromise();
}
this.activeNode = null; // Force re-activating
res = node.setActive(true, {noFocus: true});
if( setFocus ){
node.setFocus();
}
return res;
},
/** Reload tree from source and return a promise.
* @param [source] optional new source (defaults to initial source data)
* @returns {$.Promise}
*/
reload: function(source) {
this._callHook("treeClear", this);
return this._callHook("treeLoad", this, source);
},
/**Render tree (i.e. create DOM elements for all top-level nodes).
* @param {boolean} [force=false] create DOM elemnts, even if parent is collapsed
* @param {boolean} [deep=false]
*/
render: function(force, deep) {
return this.rootNode.render(force, deep);
},
// TODO: selectKey: function(key, select)
// TODO: serializeArray: function(stopOnParents)
/**
* @param {boolean} [flag=true]
*/
setFocus: function(flag) {
return this._callHook("treeSetFocus", this, flag);
},
/**
* Return all nodes as nested list of {@link NodeData}.
*
* @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children)
* @param {function} [callback] callback(dict, node) is called for every node, in order to allow modifications
* @returns {Array | object}
* @see FancytreeNode#toDict
*/
toDict: function(includeRoot, callback){
var res = this.rootNode.toDict(true, callback);
return includeRoot ? res : res.children;
},
/* Implicitly called for string conversions.
* @returns {string}
*/
toString: function(){
return "<Fancytree(#" + this._id + ")>";
},
/* _trigger a widget event with additional node ctx.
* @see EventData
*/
_triggerNodeEvent: function(type, node, originalEvent, extra) {
// this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx);
var ctx = this._makeHookContext(node, originalEvent, extra),
res = this.widget._trigger(type, originalEvent, ctx);
if(res !== false && ctx.result !== undefined){
return ctx.result;
}
return res;
},
/* _trigger a widget event with additional tree data. */
_triggerTreeEvent: function(type, originalEvent, extra) {
// this.debug("_trigger(" + type + ")", ctx);
var ctx = this._makeHookContext(this, originalEvent, extra),
res = this.widget._trigger(type, originalEvent, ctx);
if(res !== false && ctx.result !== undefined){
return ctx.result;
}
return res;
},
/** Call fn(node) for all nodes.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and children only.
* @returns {boolean} false, if the iterator was stopped.
*/
visit: function(fn) {
return this.rootNode.visit(fn, false);
},
/** Write warning to browser console (prepending tree info)
*
* @param {*} msg string or object or array of such
*/
warn: function(msg){
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("warn", arguments);
}
};
/**
* These additional methods of the {@link Fancytree} class are 'hook functions'
* that can be used and overloaded by extensions.
* (See <a href="https://github.com/mar10/fancytree/wiki/TutorialExtensions">writing extensions</a>.)
* @mixin Fancytree_Hooks
*/
$.extend(Fancytree.prototype,
/** @lends Fancytree_Hooks# */
{
/** Default handling for mouse click events.
*
* @param {EventData} ctx
*/
nodeClick: function(ctx) {
var activate, expand,
// event = ctx.originalEvent,
targetType = ctx.targetType,
node = ctx.node;
// this.debug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which, ctx);
// TODO: use switch
// TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample)
if( targetType === "expander" ) {
if( node.isLoading() ) {
// #495: we probably got a click event while a lazy load is pending.
// The 'expanded' state is not yet set, so 'toggle' would expand
// and trigger lazyLoad again.
// It would be better to allow to collapse/expand the status node
// while loading (instead of ignoring), but that would require some
// more work.
node.debug("Got 2nd click while loading: ignored");
return;
}
// Clicking the expander icon always expands/collapses
this._callHook("nodeToggleExpanded", ctx);
} else if( targetType === "checkbox" ) {
// Clicking the checkbox always (de)selects
this._callHook("nodeToggleSelected", ctx);
if( ctx.options.focusOnSelect ) { // #358
this._callHook("nodeSetFocus", ctx, true);
}
} else {
// Honor `clickFolderMode` for
expand = false;
activate = true;
if( node.folder ) {
switch( ctx.options.clickFolderMode ) {
case 2: // expand only
expand = true;
activate = false;
break;
case 3: // expand and activate
activate = true;
expand = true; //!node.isExpanded();
break;
// else 1 or 4: just activate
}
}
if( activate ) {
this.nodeSetFocus(ctx);
this._callHook("nodeSetActive", ctx, true);
}
if( expand ) {
if(!activate){
// this._callHook("nodeSetFocus", ctx);
}
// this._callHook("nodeSetExpanded", ctx, true);
this._callHook("nodeToggleExpanded", ctx);
}
}
// Make sure that clicks stop, otherwise <a href='#'> jumps to the top
// if(event.target.localName === "a" && event.target.className === "fancytree-title"){
// event.preventDefault();
// }
// TODO: return promise?
},
/** Collapse all other children of same parent.
*
* @param {EventData} ctx
* @param {object} callOpts
*/
nodeCollapseSiblings: function(ctx, callOpts) {
// TODO: return promise?
var ac, i, l,
node = ctx.node;
if( node.parent ){
ac = node.parent.children;
for (i=0, l=ac.length; i<l; i++) {
if ( ac[i] !== node && ac[i].expanded ){
this._callHook("nodeSetExpanded", ac[i], false, callOpts);
}
}
}
},
/** Default handling for mouse douleclick events.
* @param {EventData} ctx
*/
nodeDblclick: function(ctx) {
// TODO: return promise?
if( ctx.targetType === "title" && ctx.options.clickFolderMode === 4) {
// this.nodeSetFocus(ctx);
// this._callHook("nodeSetActive", ctx, true);
this._callHook("nodeToggleExpanded", ctx);
}
// TODO: prevent text selection on dblclicks
if( ctx.targetType === "title" ) {
ctx.originalEvent.preventDefault();
}
},
/** Default handling for mouse keydown events.
*
* NOTE: this may be called with node == null if tree (but no node) has focus.
* @param {EventData} ctx
*/
nodeKeydown: function(ctx) {
// TODO: return promise?
var matchNode, stamp, res, focusNode,
event = ctx.originalEvent,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
which = event.which,
whichChar = String.fromCharCode(which),
clean = !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey),
$target = $(event.target),
handled = true,
activate = !(event.ctrlKey || !opts.autoActivate );
// (node || FT).debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which);
// FT.debug("eventToString", which, '"' + String.fromCharCode(which) + '"', '"' + FT.eventToString(event) + '"');
// Set focus to active (or first node) if no other node has the focus yet
if( !node ){
focusNode = (this.getActiveNode() || this.getFirstChild());
if (focusNode){
focusNode.setFocus();
node = ctx.node = this.focusNode;
node.debug("Keydown force focus on active node");
}
}
if( opts.quicksearch && clean && /\w/.test(whichChar) &&
!SPECIAL_KEYCODES[which] && // #659
!$target.is(":input:enabled") ) {
// Allow to search for longer streaks if typed in quickly
stamp = new Date().getTime();
if( stamp - tree.lastQuicksearchTime > 500 ) {
tree.lastQuicksearchTerm = "";
}
tree.lastQuicksearchTime = stamp;
tree.lastQuicksearchTerm += whichChar;
// tree.debug("quicksearch find", tree.lastQuicksearchTerm);
matchNode = tree.findNextNode(tree.lastQuicksearchTerm, tree.getActiveNode());
if( matchNode ) {
matchNode.setActive();
}
event.preventDefault();
return;
}
switch( FT.eventToString(event) ) {
case "+":
case "=": // 187: '+' @ Chrome, Safari
tree.nodeSetExpanded(ctx, true);
break;
case "-":
tree.nodeSetExpanded(ctx, false);
break;
case "space":
if( node.isPagingNode() ) {
tree._triggerNodeEvent("clickPaging", ctx, event);
} else if(opts.checkbox){
tree.nodeToggleSelected(ctx);
}else{
tree.nodeSetActive(ctx, true);
}
break;
case "return":
tree.nodeSetActive(ctx, true);
break;
case "home":
case "end":
case "backspace":
case "left":
case "right":
case "up":
case "down":
res = node.navigate(event.which, activate, true);
break;
default:
handled = false;
}
if(handled){
event.preventDefault();
}
},
// /** Default handling for mouse keypress events. */
// nodeKeypress: function(ctx) {
// var event = ctx.originalEvent;
// },
// /** Trigger lazyLoad event (async). */
// nodeLazyLoad: function(ctx) {
// var node = ctx.node;
// if(this._triggerNodeEvent())
// },
/** Load child nodes (async).
*
* @param {EventData} ctx
* @param {object[]|object|string|$.Promise|function} source
* @returns {$.Promise} The deferred will be resolved as soon as the (ajax)
* data was rendered.
*/
nodeLoadChildren: function(ctx, source) {
var ajax, delay, dfd,
tree = ctx.tree,
node = ctx.node,
requestId = new Date().getTime();
if($.isFunction(source)){
source = source.call(tree, {type: "source"}, ctx);
_assert(!$.isFunction(source), "source callback must not return another function");
}
if(source.url){
if( node._requestId ) {
node.warn("Recursive load request #" + requestId + " while #" + node._requestId + " is pending.");
// } else {
// node.debug("Send load request #" + requestId);
}
// `source` is an Ajax options object
ajax = $.extend({}, ctx.options.ajax, source);
node._requestId = requestId;
if(ajax.debugDelay){
// simulate a slow server
delay = ajax.debugDelay;
if($.isArray(delay)){ // random delay range [min..max]
delay = delay[0] + Math.random() * (delay[1] - delay[0]);
}
node.warn("nodeLoadChildren waiting debugDelay " + Math.round(delay) + " ms ...");
ajax.debugDelay = false;
dfd = $.Deferred(function (dfd) {
setTimeout(function () {
$.ajax(ajax)
.done(function () { dfd.resolveWith(this, arguments); })
.fail(function () { dfd.rejectWith(this, arguments); });
}, delay);
});
}else{
dfd = $.ajax(ajax);
}
// Defer the deferred: we want to be able to reject, even if ajax
// resolved ok.
source = new $.Deferred();
dfd.done(function (data, textStatus, jqXHR) {
var errorObj, res;
if((this.dataType === "json" || this.dataType === "jsonp") && typeof data === "string"){
$.error("Ajax request returned a string (did you get the JSON dataType wrong?).");
}
if( node._requestId && node._requestId > requestId ) {
// The expected request time stamp is later than `requestId`
// (which was kept as as closure variable to this handler function)
// node.warn("Ignored load response for obsolete request #" + requestId + " (expected #" + node._requestId + ")");
source.rejectWith(this, [RECURSIVE_REQUEST_ERROR]);
return;
// } else {
// node.debug("Response returned for load request #" + requestId);
}
// postProcess is similar to the standard ajax dataFilter hook,
// but it is also called for JSONP
if( ctx.options.postProcess ){
try {
res = tree._triggerNodeEvent("postProcess", ctx, ctx.originalEvent, {
response: data, error: null, dataType: this.dataType
});
} catch(e) {
res = { error: e, message: "" + e, details: "postProcess failed"};
}
if( res.error ) {
errorObj = $.isPlainObject(res.error) ? res.error : {message: res.error};
errorObj = tree._makeHookContext(node, null, errorObj);
source.rejectWith(this, [errorObj]);
return;
}
data = $.isArray(res) ? res : data;
} else if (data && data.hasOwnProperty("d") && ctx.options.enableAspx ) {
// Process ASPX WebMethod JSON object inside "d" property
data = (typeof data.d === "string") ? $.parseJSON(data.d) : data.d;
}
source.resolveWith(this, [data]);
}).fail(function (jqXHR, textStatus, errorThrown) {
var errorObj = tree._makeHookContext(node, null, {
error: jqXHR,
args: Array.prototype.slice.call(arguments),
message: errorThrown,
details: jqXHR.status + ": " + errorThrown
});
source.rejectWith(this, [errorObj]);
});
}
// #383: accept and convert ECMAScript 6 Promise
if( $.isFunction(source.then) && $.isFunction(source["catch"]) ) {
dfd = source;
source = new $.Deferred();
dfd.then(function(value){
source.resolve(value);
}, function(reason){
source.reject(reason);
});
}
if($.isFunction(source.promise)){
// `source` is a deferred, i.e. ajax request
// _assert(!node.isLoading(), "recursive load");
tree.nodeSetStatus(ctx, "loading");
source.done(function (children) {
tree.nodeSetStatus(ctx, "ok");
node._requestId = null;
}).fail(function(error){
var ctxErr;
if ( error === RECURSIVE_REQUEST_ERROR ) {
node.warn("Ignored response for obsolete load request #" + requestId + " (expected #" + node._requestId + ")");
return;
} else if (error.node && error.error && error.message) {
// error is already a context object
ctxErr = error;
} else {
ctxErr = tree._makeHookContext(node, null, {
error: error, // it can be jqXHR or any custom error
args: Array.prototype.slice.call(arguments),
message: error ? (error.message || error.toString()) : ""
});
if( ctxErr.message === "[object Object]" ) {
ctxErr.message = "";
}
}
node.warn("Load children failed (" + ctxErr.message + ")", ctxErr);
if( tree._triggerNodeEvent("loadError", ctxErr, null) !== false ) {
tree.nodeSetStatus(ctx, "error", ctxErr.message, ctxErr.details);
}
});
}
// $.when(source) resolves also for non-deferreds
return $.when(source).done(function(children){
var metaData;
if( $.isPlainObject(children) ){
// We got {foo: 'abc', children: [...]}
// Copy extra properties to tree.data.foo
_assert(node.isRootNode(), "source may only be an object for root nodes (expecting an array of child objects otherwise)");
_assert($.isArray(children.children), "if an object is passed as source, it must contain a 'children' array (all other properties are added to 'tree.data')");
metaData = children;
children = children.children;
delete metaData.children;
$.extend(tree.data, metaData);
}
_assert($.isArray(children), "expected array of children");
node._setChildren(children);
// trigger fancytreeloadchildren
tree._triggerNodeEvent("loadChildren", node);
});
},
/** [Not Implemented] */
nodeLoadKeyPath: function(ctx, keyPathList) {
// TODO: implement and improve
// http://code.google.com/p/dynatree/issues/detail?id=222
},
/**
* Remove a single direct child of ctx.node.
* @param {EventData} ctx
* @param {FancytreeNode} childNode dircect child of ctx.node
*/
nodeRemoveChild: function(ctx, childNode) {
var idx,
node = ctx.node,
// opts = ctx.options,
subCtx = $.extend({}, ctx, {node: childNode}),
children = node.children;
// FT.debug("nodeRemoveChild()", node.toString(), childNode.toString());
if( children.length === 1 ) {
_assert(childNode === children[0], "invalid single child");
return this.nodeRemoveChildren(ctx);
}
if( this.activeNode && (childNode === this.activeNode || this.activeNode.isDescendantOf(childNode))){
this.activeNode.setActive(false); // TODO: don't fire events
}
if( this.focusNode && (childNode === this.focusNode || this.focusNode.isDescendantOf(childNode))){
this.focusNode = null;
}
// TODO: persist must take care to clear select and expand cookies
this.nodeRemoveMarkup(subCtx);
this.nodeRemoveChildren(subCtx);
idx = $.inArray(childNode, children);
_assert(idx >= 0, "invalid child");
// Notify listeners
node.triggerModifyChild("remove", childNode);
// Unlink to support GC
childNode.visit(function(n){
n.parent = null;
}, true);
this._callHook("treeRegisterNode", this, false, childNode);
// remove from child list
children.splice(idx, 1);
},
/**Remove HTML markup for all descendents of ctx.node.
* @param {EventData} ctx
*/
nodeRemoveChildMarkup: function(ctx) {
var node = ctx.node;
// FT.debug("nodeRemoveChildMarkup()", node.toString());
// TODO: Unlink attr.ftnode to support GC
if(node.ul){
if( node.isRootNode() ) {
$(node.ul).empty();
} else {
$(node.ul).remove();
node.ul = null;
}
node.visit(function(n){
n.li = n.ul = null;
});
}
},
/**Remove all descendants of ctx.node.
* @param {EventData} ctx
*/
nodeRemoveChildren: function(ctx) {
var subCtx,
tree = ctx.tree,
node = ctx.node,
children = node.children;
// opts = ctx.options;
// FT.debug("nodeRemoveChildren()", node.toString());
if(!children){
return;
}
if( this.activeNode && this.activeNode.isDescendantOf(node)){
this.activeNode.setActive(false); // TODO: don't fire events
}
if( this.focusNode && this.focusNode.isDescendantOf(node)){
this.focusNode = null;
}
// TODO: persist must take care to clear select and expand cookies
this.nodeRemoveChildMarkup(ctx);
// Unlink children to support GC
// TODO: also delete this.children (not possible using visit())
subCtx = $.extend({}, ctx);
node.triggerModifyChild("remove", null);
node.visit(function(n){
n.parent = null;
tree._callHook("treeRegisterNode", tree, false, n);
});
if( node.lazy ){
// 'undefined' would be interpreted as 'not yet loaded' for lazy nodes
node.children = [];
} else{
node.children = null;
}
if( !node.isRootNode() ) {
node.expanded = false; // #449, #459
}
this.nodeRenderStatus(ctx);
},
/**Remove HTML markup for ctx.node and all its descendents.
* @param {EventData} ctx
*/
nodeRemoveMarkup: function(ctx) {
var node = ctx.node;
// FT.debug("nodeRemoveMarkup()", node.toString());
// TODO: Unlink attr.ftnode to support GC
if(node.li){
$(node.li).remove();
node.li = null;
}
this.nodeRemoveChildMarkup(ctx);
},
/**
* Create `<li><span>..</span> .. </li>` tags for this node.
*
* This method takes care that all HTML markup is created that is required
* to display this node in its current state.
*
* Call this method to create new nodes, or after the strucuture
* was changed (e.g. after moving this node or adding/removing children)
* nodeRenderTitle() and nodeRenderStatus() are implied.
*
* <code>
* <li id='KEY' ftnode=NODE>
* <span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'>
* <span class="fancytree-expander"></span>
* <span class="fancytree-checkbox"></span> // only present in checkbox mode
* <span class="fancytree-icon"></span>
* <a href="#" class="fancytree-title"> Node 1 </a>
* </span>
* <ul> // only present if node has children
* <li id='KEY' ftnode=NODE> child1 ... </li>
* <li id='KEY' ftnode=NODE> child2 ... </li>
* </ul>
* </li>
* </code>
*
* @param {EventData} ctx
* @param {boolean} [force=false] re-render, even if html markup was already created
* @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
* @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later
*/
nodeRender: function(ctx, force, deep, collapsed, _recursive) {
/* This method must take care of all cases where the current data mode
* (i.e. node hierarchy) does not match the current markup.
*
* - node was not yet rendered:
* create markup
* - node was rendered: exit fast
* - children have been added
* - children have been removed
*/
var childLI, childNode1, childNode2, i, l, next, subCtx,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
aria = opts.aria,
firstTime = false,
parent = node.parent,
isRootNode = !parent,
children = node.children,
successorLi = null;
// FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString());
if( tree._enableUpdate === false ) {
// tree.debug("no render", tree._enableUpdate);
return;
}
if( ! isRootNode && ! parent.ul ) {
// Calling node.collapse on a deep, unrendered node
return;
}
_assert(isRootNode || parent.ul, "parent UL must exist");
// Render the node
if( !isRootNode ){
// Discard markup on force-mode, or if it is not linked to parent <ul>
if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){
if( node.li.parentNode === node.parent.ul ){
// #486: store following node, so we can insert the new markup there later
successorLi = node.li.nextSibling;
}else{
// May happen, when a top-level node was dropped over another
this.debug("Unlinking " + node + " (must be child of " + node.parent + ")");
}
// this.debug("nodeRemoveMarkup...");
this.nodeRemoveMarkup(ctx);
}
// Create <li><span /> </li>
// node.debug("render...");
if( !node.li ) {
// node.debug("render... really");
firstTime = true;
node.li = document.createElement("li");
node.li.ftnode = node;
// We set role 'treeitem' to the title span instead
if(aria){
// TODO: why does the next line don't work:
// node.li.role = "treeitem";
// $(node.li).attr("role", "treeitem");
// .attr("aria-labelledby", "ftal_" + opts.idPrefix + node.key);
}
if( node.key && opts.generateIds ){
node.li.id = opts.idPrefix + node.key;
}
node.span = document.createElement("span");
node.span.className = "fancytree-node";
// if(aria){
// $(node.li).attr("aria-labelledby", "ftal_" + opts.idPrefix + node.key);
// }
node.li.appendChild(node.span);
// Create inner HTML for the <span> (expander, checkbox, icon, and title)
this.nodeRenderTitle(ctx);
// Allow tweaking and binding, after node was created for the first time
if ( opts.createNode ){
opts.createNode.call(tree, {type: "createNode"}, ctx);
}
}else{
// this.nodeRenderTitle(ctx);
this.nodeRenderStatus(ctx);
}
// Allow tweaking after node state was rendered
if ( opts.renderNode ){
opts.renderNode.call(tree, {type: "renderNode"}, ctx);
}
}
// Visit child nodes
if( children ){
if( isRootNode || node.expanded || deep === true ) {
// Create a UL to hold the children
if( !node.ul ){
node.ul = document.createElement("ul");
if((collapsed === true && !_recursive) || !node.expanded){
// hide top UL, so we can use an animation to show it later
node.ul.style.display = "none";
}
if(aria){
$(node.ul).attr("role", "group");
}
if ( node.li ) { // issue #67
node.li.appendChild(node.ul);
} else {
node.tree.$div.append(node.ul);
}
}
// Add child markup
for(i=0, l=children.length; i<l; i++) {
subCtx = $.extend({}, ctx, {node: children[i]});
this.nodeRender(subCtx, force, deep, false, true);
}
// Remove <li> if nodes have moved to another parent
childLI = node.ul.firstChild;
while( childLI ){
childNode2 = childLI.ftnode;
if( childNode2 && childNode2.parent !== node ) {
node.debug("_fixParent: remove missing " + childNode2, childLI);
next = childLI.nextSibling;
childLI.parentNode.removeChild(childLI);
childLI = next;
}else{
childLI = childLI.nextSibling;
}
}
// Make sure, that <li> order matches node.children order.
childLI = node.ul.firstChild;
for(i=0, l=children.length-1; i<l; i++) {
childNode1 = children[i];
childNode2 = childLI.ftnode;
if( childNode1 !== childNode2 ) {
// node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2);
node.ul.insertBefore(childNode1.li, childNode2.li);
} else {
childLI = childLI.nextSibling;
}
}
}
}else{
// No children: remove markup if any
if( node.ul ){
// alert("remove child markup for " + node);
this.warn("remove child markup for " + node);
this.nodeRemoveChildMarkup(ctx);
}
}
if( !isRootNode ){
// Update element classes according to node state
// this.nodeRenderStatus(ctx);
// Finally add the whole structure to the DOM, so the browser can render
if( firstTime ){
// #486: successorLi is set, if we re-rendered (i.e. discarded)
// existing markup, which we want to insert at the same position.
// (null is equivalent to append)
// parent.ul.appendChild(node.li);
parent.ul.insertBefore(node.li, successorLi);
}
}
},
/** Create HTML inside the node's outer <span> (i.e. expander, checkbox,
* icon, and title).
*
* nodeRenderStatus() is implied.
* @param {EventData} ctx
* @param {string} [title] optinal new title
*/
nodeRenderTitle: function(ctx, title) {
// set node connector images, links and text
var id, icon, nodeTitle, role, tabindex, tooltip,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
aria = opts.aria,
level = node.getLevel(),
ares = [];
if(title !== undefined){
node.title = title;
}
if ( !node.span || tree._enableUpdate === false ) {
// Silently bail out if node was not rendered yet, assuming
// node.render() will be called as the node becomes visible
return;
}
// Connector (expanded, expandable or simple)
if( level < opts.minExpandLevel ) {
if( !node.lazy ) {
node.expanded = true;
}
if(level > 1){
if(aria){
ares.push("<span role='button' class='fancytree-expander fancytree-expander-fixed'></span>");
}else{
ares.push("<span class='fancytree-expander fancytree-expander-fixed''></span>");
}
}
// .. else (i.e. for root level) skip expander/connector alltogether
} else {
if(aria){
ares.push("<span role='button' class='fancytree-expander'></span>");
}else{
ares.push("<span class='fancytree-expander'></span>");
}
}
// Checkbox mode
if( opts.checkbox && node.hideCheckbox !== true && !node.isStatusNode() ) {
if(aria){
ares.push("<span role='checkbox' class='fancytree-checkbox'></span>");
}else{
ares.push("<span class='fancytree-checkbox'></span>");
}
}
// Folder or doctype icon
if( node.data.iconClass !== undefined ) { // 2015-11-16
// Handle / warn about backward compatibility
if( node.icon ) {
$.error("'iconClass' node option is deprecated since v2.14.0: use 'icon' only instead");
} else {
node.warn("'iconClass' node option is deprecated since v2.14.0: use 'icon' instead");
node.icon = node.data.iconClass;
}
}
// If opts.icon is a callback and returns something other than undefined, use that
// else if node.icon is a boolean or string, use that
// else if opts.icon is a boolean or string, use that
// else show standard icon (which may be different for folders or documents)
icon = FT.evalOption("icon", node, node, opts, true);
if( typeof icon !== "boolean" ) {
// icon is defined, but not true/false: must be a string
icon = "" + icon;
}
// if( $.isFunction(opts.icon) ) {
// icon = opts.icon.call(tree, {type: "icon"}, ctx);
// if( icon == null ) {
// icon = node.icon;
// }
// } else {
// icon = (node.icon != null) ? node.icon : opts.icon;
// }
// if( icon == null ) {
// icon = true; // no icon option at all: show default icon
// } else {
// if( typeof icon !== "boolean" ) {
// // icon is defined, but not true/false: must be a string
// icon = "" + icon;
// }
// }
if( icon !== false ) {
role = aria ? " role='img'" : "";
if ( typeof icon === "string" ) {
if( TEST_IMG.test(icon) ) {
// node.icon is an image url. Prepend imagePath
icon = (icon.charAt(0) === "/") ? icon : ((opts.imagePath || "") + icon);
ares.push("<img src='" + icon + "' class='fancytree-icon' alt='' />");
} else {
ares.push("<span " + role + " class='fancytree-custom-icon " + icon + "'></span>");
}
} else {
// standard icon: theme css will take care of this
ares.push("<span " + role + " class='fancytree-icon'></span>");
}
}
// Node title
nodeTitle = "";
if ( opts.renderTitle ){
nodeTitle = opts.renderTitle.call(tree, {type: "renderTitle"}, ctx) || "";
}
if ( !nodeTitle ) {
if( node.tooltip ) {
tooltip = node.tooltip;
} else if ( opts.tooltip ) {
tooltip = opts.tooltip === true ? node.title : opts.tooltip.call(tree, node);
}
tooltip = tooltip ? " title='" + _escapeTooltip(tooltip) + "'" : "";
// id = aria ? " id='ftal_" + opts.idPrefix + node.key + "'" : "";
id = "";
// role = "";
role = (aria && !node.tr) ? " role='treeitem'" : "";
tabindex = opts.titlesTabbable ? " tabindex='0'" : "";
nodeTitle = "<span " + role + " class='fancytree-title'" +
id + tooltip + tabindex + ">" +
(opts.escapeTitles ? _escapeHtml(node.title) : node.title) +
"</span>";
}
ares.push(nodeTitle);
// Note: this will trigger focusout, if node had the focus
//$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly
node.span.innerHTML = ares.join("");
// Update CSS classes
this.nodeRenderStatus(ctx);
if ( opts.enhanceTitle ){
ctx.$title = $(">span.fancytree-title", node.span);
nodeTitle = opts.enhanceTitle.call(tree, {type: "enhanceTitle"}, ctx) || "";
}
},
/** Update element classes according to node state.
* @param {EventData} ctx
*/
nodeRenderStatus: function(ctx) {
// Set classes for current status
var $ariaElem,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
// nodeContainer = node[tree.nodeContainerAttrName],
hasChildren = node.hasChildren(),
isLastSib = node.isLastSibling(),
aria = opts.aria,
// $ariaElem = aria ? $(node[tree.ariaPropName]) : null,
// $ariaElem = $(node.span).find(".fancytree-title"),
cn = opts._classNames,
cnList = [],
statusElem = node[tree.statusClassPropName];
if( !statusElem || tree._enableUpdate === false ){
// if this function is called for an unrendered node, ignore it (will be updated on nect render anyway)
return;
}
if( aria ) {
$ariaElem = node.tr ? $(node.tr) : $(node.span).find(".fancytree-title");
}
// Build a list of class names that we will add to the node <span>
cnList.push(cn.node);
if( tree.activeNode === node ){
cnList.push(cn.active);
// $(">span.fancytree-title", statusElem).attr("tabindex", "0");
// tree.$container.removeAttr("tabindex");
// }else{
// $(">span.fancytree-title", statusElem).removeAttr("tabindex");
// tree.$container.attr("tabindex", "0");
}
if( tree.focusNode === node ){
cnList.push(cn.focused);
}
// node.debug("aria", node.expanded, aria, $ariaElem);
if( node.expanded ){
cnList.push(cn.expanded);
if(aria){
$ariaElem.attr("aria-expanded", true);
}
}else if( aria ){
if( hasChildren ) {
$ariaElem.attr("aria-expanded", false);
} else {
$ariaElem.removeAttr("aria-expanded");
}
}
if( node.folder ){
cnList.push(cn.folder);
}
if( hasChildren !== false ){
cnList.push(cn.hasChildren);
}
// TODO: required?
if( isLastSib ){
cnList.push(cn.lastsib);
}
if( node.lazy && node.children == null ){
cnList.push(cn.lazy);
}
if( node.partload ){
cnList.push(cn.partload);
}
if( node.partsel ){
cnList.push(cn.partsel);
}
if( node.unselectable ){
cnList.push(cn.unselectable);
}
if( node._isLoading ){
cnList.push(cn.loading);
}
if( node._error ){
cnList.push(cn.error);
}
if( node.statusNodeType ) {
cnList.push(cn.statusNodePrefix + node.statusNodeType);
}
if( node.selected ){
cnList.push(cn.selected);
if(aria){
$ariaElem.attr("aria-selected", true);
}
}else if(aria){
$ariaElem.attr("aria-selected", false);
}
if( node.extraClasses ){
cnList.push(node.extraClasses);
}
// IE6 doesn't correctly evaluate multiple class names,
// so we create combined class names that can be used in the CSS
if( hasChildren === false ){
cnList.push(cn.combinedExpanderPrefix + "n" +
(isLastSib ? "l" : "")
);
}else{
cnList.push(cn.combinedExpanderPrefix +
(node.expanded ? "e" : "c") +
(node.lazy && node.children == null ? "d" : "") +
(isLastSib ? "l" : "")
);
}
cnList.push(cn.combinedIconPrefix +
(node.expanded ? "e" : "c") +
(node.folder ? "f" : "")
);
// node.span.className = cnList.join(" ");
statusElem.className = cnList.join(" ");
// TODO: we should not set this in the <span> tag also, if we set it here:
// Maybe most (all) of the classes should be set in LI instead of SPAN?
if(node.li){
// #719: we have to consider that there may be already other classes:
$(node.li).toggleClass(cn.lastsib, isLastSib);
}
},
/** Activate node.
* flag defaults to true.
* If flag is true, the node is activated (must be a synchronous operation)
* If flag is false, the node is deactivated (must be a synchronous operation)
* @param {EventData} ctx
* @param {boolean} [flag=true]
* @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false}
* @returns {$.Promise}
*/
nodeSetActive: function(ctx, flag, callOpts) {
// Handle user click / [space] / [enter], according to clickFolderMode.
callOpts = callOpts || {};
var subCtx,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
noEvents = (callOpts.noEvents === true),
noFocus = (callOpts.noFocus === true),
isActive = (node === tree.activeNode);
// flag defaults to true
flag = (flag !== false);
// node.debug("nodeSetActive", flag);
if(isActive === flag){
// Nothing to do
return _getResolvedPromise(node);
}else if(flag && !noEvents && this._triggerNodeEvent("beforeActivate", node, ctx.originalEvent) === false ){
// Callback returned false
return _getRejectedPromise(node, ["rejected"]);
}
if(flag){
if(tree.activeNode){
_assert(tree.activeNode !== node, "node was active (inconsistency)");
subCtx = $.extend({}, ctx, {node: tree.activeNode});
tree.nodeSetActive(subCtx, false);
_assert(tree.activeNode === null, "deactivate was out of sync?");
}
if(opts.activeVisible){
// If no focus is set (noFocus: true) and there is no focused node, this node is made visible.
node.makeVisible({scrollIntoView: noFocus && tree.focusNode == null});
}
tree.activeNode = node;
tree.nodeRenderStatus(ctx);
if( !noFocus ) {
tree.nodeSetFocus(ctx);
}
if( !noEvents ) {
tree._triggerNodeEvent("activate", node, ctx.originalEvent);
}
}else{
_assert(tree.activeNode === node, "node was not active (inconsistency)");
tree.activeNode = null;
this.nodeRenderStatus(ctx);
if( !noEvents ) {
ctx.tree._triggerNodeEvent("deactivate", node, ctx.originalEvent);
}
}
return _getResolvedPromise(node);
},
/** Expand or collapse node, return Deferred.promise.
*
* @param {EventData} ctx
* @param {boolean} [flag=true]
* @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
* @returns {$.Promise} The deferred will be resolved as soon as the (lazy)
* data was retrieved, rendered, and the expand animation finshed.
*/
nodeSetExpanded: function(ctx, flag, callOpts) {
callOpts = callOpts || {};
var _afterLoad, dfd, i, l, parents, prevAC,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
noAnimation = (callOpts.noAnimation === true),
noEvents = (callOpts.noEvents === true);
// flag defaults to true
flag = (flag !== false);
// node.debug("nodeSetExpanded(" + flag + ")");
if((node.expanded && flag) || (!node.expanded && !flag)){
// Nothing to do
// node.debug("nodeSetExpanded(" + flag + "): nothing to do");
return _getResolvedPromise(node);
}else if(flag && !node.lazy && !node.hasChildren() ){
// Prevent expanding of empty nodes
// return _getRejectedPromise(node, ["empty"]);
return _getResolvedPromise(node);
}else if( !flag && node.getLevel() < opts.minExpandLevel ) {
// Prevent collapsing locked levels
return _getRejectedPromise(node, ["locked"]);
}else if ( !noEvents && this._triggerNodeEvent("beforeExpand", node, ctx.originalEvent) === false ){
// Callback returned false
return _getRejectedPromise(node, ["rejected"]);
}
// If this node inside a collpased node, no animation and scrolling is needed
if( !noAnimation && !node.isVisible() ) {
noAnimation = callOpts.noAnimation = true;
}
dfd = new $.Deferred();
// Auto-collapse mode: collapse all siblings
if( flag && !node.expanded && opts.autoCollapse ) {
parents = node.getParentList(false, true);
prevAC = opts.autoCollapse;
try{
opts.autoCollapse = false;
for(i=0, l=parents.length; i<l; i++){
// TODO: should return promise?
this._callHook("nodeCollapseSiblings", parents[i], callOpts);
}
}finally{
opts.autoCollapse = prevAC;
}
}
// Trigger expand/collapse after expanding
dfd.done(function(){
var lastChild = node.getLastChild();
if( flag && opts.autoScroll && !noAnimation && lastChild ) {
// Scroll down to last child, but keep current node visible
lastChild.scrollIntoView(true, {topNode: node}).always(function(){
if( !noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
});
} else {
if( !noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
}
});
// vvv Code below is executed after loading finished:
_afterLoad = function(callback){
var cn = opts._classNames,
isVisible, isExpanded,
effect = opts.toggleEffect;
node.expanded = flag;
// Create required markup, but make sure the top UL is hidden, so we
// can animate later
tree._callHook("nodeRender", ctx, false, false, true);
// Hide children, if node is collapsed
if( node.ul ) {
isVisible = (node.ul.style.display !== "none");
isExpanded = !!node.expanded;
if ( isVisible === isExpanded ) {
node.warn("nodeSetExpanded: UL.style.display already set");
} else if ( !effect || noAnimation ) {
node.ul.style.display = ( node.expanded || !parent ) ? "" : "none";
} else {
// The UI toggle() effect works with the ext-wide extension,
// while jQuery.animate() has problems when the title span
// has positon: absolute.
// Since jQuery UI 1.12, the blind effect requires the parent
// element to have 'position: relative'.
// See #716, #717
$(node.li).addClass(cn.animating); // #717
// node.info("fancytree-animating start: " + node.li.className);
$(node.ul)
.addClass(cn.animating) // # 716
.toggle(effect.effect, effect.options, effect.duration, function(){
// node.info("fancytree-animating end: " + node.li.className);
$(this).removeClass(cn.animating); // #716
$(node.li).removeClass(cn.animating); // #717
callback();
});
return;
}
}
callback();
};
// ^^^ Code above is executed after loading finshed.
// Load lazy nodes, if any. Then continue with _afterLoad()
if(flag && node.lazy && node.hasChildren() === undefined){
// node.debug("nodeSetExpanded: load start...");
node.load().done(function(){
// node.debug("nodeSetExpanded: load done");
if(dfd.notifyWith){ // requires jQuery 1.6+
dfd.notifyWith(node, ["loaded"]);
}
_afterLoad(function () { dfd.resolveWith(node); });
}).fail(function(errMsg){
_afterLoad(function () { dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); });
});
/*
var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent);
_assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
node.debug("nodeSetExpanded: load start...");
this._callHook("nodeLoadChildren", ctx, source).done(function(){
node.debug("nodeSetExpanded: load done");
if(dfd.notifyWith){ // requires jQuery 1.6+
dfd.notifyWith(node, ["loaded"]);
}
_afterLoad.call(tree);
}).fail(function(errMsg){
dfd.rejectWith(node, ["load failed (" + errMsg + ")"]);
});
*/
}else{
_afterLoad(function () { dfd.resolveWith(node); });
}
// node.debug("nodeSetExpanded: returns");
return dfd.promise();
},
/** Focus or blur this node.
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
nodeSetFocus: function(ctx, flag) {
// ctx.node.debug("nodeSetFocus(" + flag + ")");
var ctx2,
tree = ctx.tree,
node = ctx.node,
opts = tree.options,
// et = ctx.originalEvent && ctx.originalEvent.type,
isInput = ctx.originalEvent ? $(ctx.originalEvent.target).is(":input") : false;
flag = (flag !== false);
// (node || tree).debug("nodeSetFocus(" + flag + "), event: " + et + ", isInput: "+ isInput);
// Blur previous node if any
if(tree.focusNode){
if(tree.focusNode === node && flag){
// node.debug("nodeSetFocus(" + flag + "): nothing to do");
return;
}
ctx2 = $.extend({}, ctx, {node: tree.focusNode});
tree.focusNode = null;
this._triggerNodeEvent("blur", ctx2);
this._callHook("nodeRenderStatus", ctx2);
}
// Set focus to container and node
if(flag){
if( !this.hasFocus() ){
node.debug("nodeSetFocus: forcing container focus");
this._callHook("treeSetFocus", ctx, true, {calledByNode: true});
}
node.makeVisible({scrollIntoView: false});
tree.focusNode = node;
if( opts.titlesTabbable ) {
if( !isInput ) { // #621
$(node.span).find(".fancytree-title").focus();
}
} else {
// We cannot set KB focus to a node, so use the tree container
// #563, #570: IE scrolls on every call to .focus(), if the container
// is partially outside the viewport. So do it only, when absolutely
// neccessary:
if( $(document.activeElement).closest(".fancytree-container").length === 0 ) {
$(tree.$container).focus();
}
}
if( opts.aria ){
// Set active descendant to node's span ID (create one, if needed)
$(tree.$container).attr("aria-activedescendant",
$( node.tr || node.span ).uniqueId().attr("id"));
// "ftal_" + opts.idPrefix + node.key);
}
// $(node.span).find(".fancytree-title").focus();
this._triggerNodeEvent("focus", ctx);
// if( opts.autoActivate ){
// tree.nodeSetActive(ctx, true);
// }
if( opts.autoScroll ){
node.scrollIntoView();
}
this._callHook("nodeRenderStatus", ctx);
}
},
/** (De)Select node, return new status (sync).
*
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
nodeSetSelected: function(ctx, flag) {
var node = ctx.node,
tree = ctx.tree,
opts = ctx.options;
// flag defaults to true
flag = (flag !== false);
// node.debug("nodeSetSelected(" + flag + ")", ctx);
if( node.unselectable){
return;
}
// TODO: !!node.expanded is nicer, but doesn't pass jshint
// https://github.com/jshint/jshint/issues/455
// if( !!node.expanded === !!flag){
if((node.selected && flag) || (!node.selected && !flag)){
return !!node.selected;
}else if ( this._triggerNodeEvent("beforeSelect", node, ctx.originalEvent) === false ){
return !!node.selected;
}
if(flag && opts.selectMode === 1){
// single selection mode
if(tree.lastSelectedNode){
tree.lastSelectedNode.setSelected(false);
}
}else if(opts.selectMode === 3){
// multi.hier selection mode
node.selected = flag;
// this._fixSelectionState(node);
node.fixSelection3AfterClick();
}
node.selected = flag;
this.nodeRenderStatus(ctx);
tree.lastSelectedNode = flag ? node : null;
tree._triggerNodeEvent("select", ctx);
},
/** Show node status (ok, loading, error, nodata) using styles and a dummy child node.
*
* @param {EventData} ctx
* @param status
* @param message
* @param details
* @since 2.3
*/
nodeSetStatus: function(ctx, status, message, details) {
var node = ctx.node,
tree = ctx.tree;
function _clearStatusNode() {
// Remove dedicated dummy node, if any
var firstChild = ( node.children ? node.children[0] : null );
if ( firstChild && firstChild.isStatusNode() ) {
try{
// I've seen exceptions here with loadKeyPath...
if(node.ul){
node.ul.removeChild(firstChild.li);
firstChild.li = null; // avoid leaks (DT issue 215)
}
}catch(e){}
if( node.children.length === 1 ){
node.children = [];
}else{
node.children.shift();
}
}
}
function _setStatusNode(data, type) {
// Create/modify the dedicated dummy node for 'loading...' or
// 'error!' status. (only called for direct child of the invisible
// system root)
var firstChild = ( node.children ? node.children[0] : null );
if ( firstChild && firstChild.isStatusNode() ) {
$.extend(firstChild, data);
firstChild.statusNodeType = type;
tree._callHook("nodeRenderTitle", firstChild);
} else {
node._setChildren([data]);
node.children[0].statusNodeType = type;
tree.render();
}
return node.children[0];
}
switch( status ){
case "ok":
_clearStatusNode();
node._isLoading = false;
node._error = null;
node.renderStatus();
break;
case "loading":
if( !node.parent ) {
_setStatusNode({
title: tree.options.strings.loading + (message ? " (" + message + ")" : ""),
// icon: true, // needed for 'loding' icon
checkbox: false,
tooltip: details
}, status);
}
node._isLoading = true;
node._error = null;
node.renderStatus();
break;
case "error":
_setStatusNode({
title: tree.options.strings.loadError + (message ? " (" + message + ")" : ""),
// icon: false,
checkbox: false,
tooltip: details
}, status);
node._isLoading = false;
node._error = { message: message, details: details };
node.renderStatus();
break;
case "nodata":
_setStatusNode({
title: tree.options.strings.noData,
// icon: false,
checkbox: false,
tooltip: details
}, status);
node._isLoading = false;
node._error = null;
node.renderStatus();
break;
default:
$.error("invalid node status " + status);
}
},
/**
*
* @param {EventData} ctx
*/
nodeToggleExpanded: function(ctx) {
return this.nodeSetExpanded(ctx, !ctx.node.expanded);
},
/**
* @param {EventData} ctx
*/
nodeToggleSelected: function(ctx) {
return this.nodeSetSelected(ctx, !ctx.node.selected);
},
/** Remove all nodes.
* @param {EventData} ctx
*/
treeClear: function(ctx) {
var tree = ctx.tree;
tree.activeNode = null;
tree.focusNode = null;
tree.$div.find(">ul.fancytree-container").empty();
// TODO: call destructors and remove reference loops
tree.rootNode.children = null;
},
/** Widget was created (called only once, even it re-initialized).
* @param {EventData} ctx
*/
treeCreate: function(ctx) {
},
/** Widget was destroyed.
* @param {EventData} ctx
*/
treeDestroy: function(ctx) {
this.$div.find(">ul.fancytree-container").remove();
this.$source && this.$source.removeClass("ui-helper-hidden");
},
/** Widget was (re-)initialized.
* @param {EventData} ctx
*/
treeInit: function(ctx) {
var tree = ctx.tree,
opts = tree.options;
//this.debug("Fancytree.treeInit()");
// Add container to the TAB chain
// See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant
// #577: Allow to set tabindex to "0", "-1" and ""
tree.$container.attr("tabindex", opts.tabindex);
if( opts.rtl ) {
tree.$container.attr("DIR", "RTL").addClass("fancytree-rtl");
}else{
tree.$container.removeAttr("DIR").removeClass("fancytree-rtl");
}
if( opts.aria ){
tree.$container.attr("role", "tree");
if( opts.selectMode !== 1 ) {
tree.$container.attr("aria-multiselectable", true);
}
}
this.treeLoad(ctx);
},
/** Parse Fancytree from source, as configured in the options.
* @param {EventData} ctx
* @param {object} [source] optional new source (use last data otherwise)
*/
treeLoad: function(ctx, source) {
var metaData, type, $ul,
tree = ctx.tree,
$container = ctx.widget.element,
dfd,
// calling context for root node
rootCtx = $.extend({}, ctx, {node: this.rootNode});
if(tree.rootNode.children){
this.treeClear(ctx);
}
source = source || this.options.source;
if(!source){
type = $container.data("type") || "html";
switch(type){
case "html":
$ul = $container.find(">ul:first");
$ul.addClass("ui-fancytree-source ui-helper-hidden");
source = $.ui.fancytree.parseHtml($ul);
// allow to init tree.data.foo from <ul data-foo=''>
this.data = $.extend(this.data, _getElementDataAsDict($ul));
break;
case "json":
source = $.parseJSON($container.text());
// $container already contains the <ul>, but we remove the plain (json) text
// $container.empty();
$container.contents().filter(function(){
return (this.nodeType === 3);
}).remove();
if( $.isPlainObject(source) ){
// We got {foo: 'abc', children: [...]}
// Copy extra properties to tree.data.foo
_assert($.isArray(source.children), "if an object is passed as source, it must contain a 'children' array (all other properties are added to 'tree.data')");
metaData = source;
source = source.children;
delete metaData.children;
$.extend(tree.data, metaData);
}
break;
default:
$.error("Invalid data-type: " + type);
}
}else if(typeof source === "string"){
// TODO: source is an element ID
$.error("Not implemented");
}
// Trigger fancytreeinit after nodes have been loaded
dfd = this.nodeLoadChildren(rootCtx, source).done(function(){
tree.render();
if( ctx.options.selectMode === 3 ){
tree.rootNode.fixSelection3FromEndNodes();
}
if( tree.activeNode && tree.options.activeVisible ) {
tree.activeNode.makeVisible();
}
tree._triggerTreeEvent("init", null, { status: true });
}).fail(function(){
tree.render();
tree._triggerTreeEvent("init", null, { status: false });
});
return dfd;
},
/** Node was inserted into or removed from the tree.
* @param {EventData} ctx
* @param {boolean} add
* @param {FancytreeNode} node
*/
treeRegisterNode: function(ctx, add, node) {
},
/** Widget got focus.
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
treeSetFocus: function(ctx, flag, callOpts) {
function ensureTreeFocus(thisTree) {
if (!thisTree.activeNode && thisTree.getFirstChild()) {
thisTree.getFirstChild().setFocus();
}
}
flag = (flag !== false);
// this.debug("treeSetFocus(" + flag + "), callOpts: ", callOpts, this.hasFocus());
// this.debug(" focusNode: " + this.focusNode);
// this.debug(" activeNode: " + this.activeNode);
if( flag !== this.hasFocus() ){
this._hasFocus = flag;
if( !flag && this.focusNode ) {
// Node also looses focus if widget blurs
this.focusNode.setFocus(false);
} else if ( flag && (!callOpts || !callOpts.calledByNode) ) {
$(this.$container).focus();
}
this.$container.toggleClass("fancytree-treefocus", flag);
this._triggerTreeEvent(flag ? "focusTree" : "blurTree");
if( flag ) {
// Check after timeout to ensure mousedown processing is complete
// and the clicked node is already activated
var thisTree = this;
setTimeout(function() { ensureTreeFocus(thisTree); }, 0);
}
}
},
/** Widget option was set using `$().fancytree("option", "foo", "bar")`.
* @param {EventData} ctx
* @param {string} key option name
* @param {any} value option value
*/
treeSetOption: function(ctx, key, value) {
var tree = ctx.tree,
callDefault = true,
rerender = false;
switch( key ) {
case "aria":
case "checkbox":
case "icon":
case "minExpandLevel":
case "tabindex":
tree._callHook("treeCreate", tree);
rerender = true;
break;
case "escapeTitles":
case "tooltip":
rerender = true;
break;
case "rtl":
if( value === false ) {
tree.$container.removeAttr("DIR").removeClass("fancytree-rtl");
}else{
tree.$container.attr("DIR", "RTL").addClass("fancytree-rtl");
}
rerender = true;
break;
case "source":
callDefault = false;
tree._callHook("treeLoad", tree, value);
rerender = true;
break;
}
tree.debug("set option " + key + "=" + value + " <" + typeof(value) + ">");
if(callDefault){
if( this.widget._super ) {
// jQuery UI 1.9+
this.widget._super.call( this.widget, key, value );
} else {
// jQuery UI <= 1.8, we have to manually invoke the _setOption method from the base widget
$.Widget.prototype._setOption.call(this.widget, key, value);
}
}
if(rerender){
tree.render(true, false); // force, not-deep
}
}
});
/* ******************************************************************************
* jQuery UI widget boilerplate
*/
/**
* The plugin (derrived from <a href=" http://api.jqueryui.com/jQuery.widget/">jQuery.Widget</a>).<br>
* This constructor is not called directly. Use `$(selector).fancytree({})`
* to initialize the plugin instead.<br>
* <pre class="sh_javascript sunlight-highlight-javascript">// Access widget methods and members:
* var tree = $("#tree").fancytree("getTree");
* var node = $("#tree").fancytree("getActiveNode", "1234");
* </pre>
*
* @mixin Fancytree_Widget
*/
$.widget("ui.fancytree",
/** @lends Fancytree_Widget# */
{
/**These options will be used as defaults
* @type {FancytreeOptions}
*/
options:
{
activeVisible: true,
ajax: {
type: "GET",
cache: false, // false: Append random '_' argument to the request url to prevent caching.
// timeout: 0, // >0: Make sure we get an ajax error if server is unreachable
dataType: "json" // Expect json format and pass json object to callbacks.
}, //
aria: false,
autoActivate: true,
autoCollapse: false,
autoScroll: false,
checkbox: false,
clickFolderMode: 4,
debugLevel: null, // 0..2 (null: use global setting $.ui.fancytree.debugInfo)
disabled: false, // TODO: required anymore?
enableAspx: true, // TODO: document
escapeTitles: false,
extensions: [],
// fx: { height: "toggle", duration: 200 },
// toggleEffect: { effect: "drop", options: {direction: "left"}, duration: 200 },
// toggleEffect: { effect: "slide", options: {direction: "up"}, duration: 200 },
toggleEffect: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 },
generateIds: false,
icon: true,
idPrefix: "ft_",
focusOnSelect: false,
keyboard: true,
keyPathSeparator: "/",
minExpandLevel: 1,
quicksearch: false,
rtl: false,
scrollOfs: {top: 0, bottom: 0},
scrollParent: null,
selectMode: 2,
strings: {
loading: "Loading...", // … would be escaped when escapeTitles is true
loadError: "Load error!",
moreData: "More...",
noData: "No data."
},
tabindex: "0",
titlesTabbable: false,
tooltip: false,
_classNames: {
node: "fancytree-node",
folder: "fancytree-folder",
animating: "fancytree-animating",
combinedExpanderPrefix: "fancytree-exp-",
combinedIconPrefix: "fancytree-ico-",
hasChildren: "fancytree-has-children",
active: "fancytree-active",
selected: "fancytree-selected",
expanded: "fancytree-expanded",
lazy: "fancytree-lazy",
focused: "fancytree-focused",
partload: "fancytree-partload",
partsel: "fancytree-partsel",
unselectable: "fancytree-unselectable",
lastsib: "fancytree-lastsib",
loading: "fancytree-loading",
error: "fancytree-error",
statusNodePrefix: "fancytree-statusnode-"
},
// events
lazyLoad: null,
postProcess: null
},
/* Set up the widget, Called on first $().fancytree() */
_create: function() {
this.tree = new Fancytree(this);
this.$source = this.source || this.element.data("type") === "json" ? this.element
: this.element.find(">ul:first");
// Subclass Fancytree instance with all enabled extensions
var extension, extName, i,
opts = this.options,
extensions = opts.extensions,
base = this.tree;
for(i=0; i<extensions.length; i++){
extName = extensions[i];
extension = $.ui.fancytree._extensions[extName];
if(!extension){
$.error("Could not apply extension '" + extName + "' (it is not registered, did you forget to include it?)");
}
// Add extension options as tree.options.EXTENSION
// _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName);
this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]);
// Add a namespace tree.ext.EXTENSION, to hold instance data
_assert(this.tree.ext[extName] === undefined, "Extension name must not exist as Fancytree.ext attribute: '" + extName + "'");
// this.tree[extName] = extension;
this.tree.ext[extName] = {};
// Subclass Fancytree methods using proxies.
_subclassObject(this.tree, base, extension, extName);
// current extension becomes base for the next extension
base = extension;
}
//
if( opts.icons !== undefined ) { // 2015-11-16
if( opts.icon !== true ) {
$.error("'icons' tree option is deprecated since v2.14.0: use 'icon' only instead");
} else {
this.tree.warn("'icons' tree option is deprecated since v2.14.0: use 'icon' instead");
opts.icon = opts.icons;
}
}
if( opts.iconClass !== undefined ) { // 2015-11-16
if( opts.icon ) {
$.error("'iconClass' tree option is deprecated since v2.14.0: use 'icon' only instead");
} else {
this.tree.warn("'iconClass' tree option is deprecated since v2.14.0: use 'icon' instead");
opts.icon = opts.iconClass;
}
}
if( opts.tabbable !== undefined ) { // 2016-04-04
opts.tabindex = opts.tabbable ? "0" : "-1";
this.tree.warn("'tabbable' tree option is deprecated since v2.17.0: use 'tabindex='" + opts.tabindex + "' instead");
}
//
this.tree._callHook("treeCreate", this.tree);
// Note: 'fancytreecreate' event is fired by widget base class
// this.tree._triggerTreeEvent("create");
},
/* Called on every $().fancytree() */
_init: function() {
this.tree._callHook("treeInit", this.tree);
// TODO: currently we call bind after treeInit, because treeInit
// might change tree.$container.
// It would be better, to move ebent binding into hooks altogether
this._bind();
},
/* Use the _setOption method to respond to changes to options */
_setOption: function(key, value) {
return this.tree._callHook("treeSetOption", this.tree, key, value);
},
/** Use the destroy method to clean up any modifications your widget has made to the DOM */
destroy: function() {
this._unbind();
this.tree._callHook("treeDestroy", this.tree);
// In jQuery UI 1.8, you must invoke the destroy method from the base widget
$.Widget.prototype.destroy.call(this);
// TODO: delete tree and nodes to make garbage collect easier?
// TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method
},
// -------------------------------------------------------------------------
/* Remove all event handlers for our namespace */
_unbind: function() {
var ns = this.tree._ns;
this.element.off(ns);
this.tree.$container.off(ns);
$(document).off(ns);
},
/* Add mouse and kyboard handlers to the container */
_bind: function() {
var that = this,
opts = this.options,
tree = this.tree,
ns = tree._ns
// selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" )
;
// Remove all previuous handlers for this tree
this._unbind();
//alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container);
// tree.debug("bind events; container: ", tree.$container);
tree.$container.on("focusin" + ns + " focusout" + ns, function(event){
var node = FT.getNode(event),
flag = (event.type === "focusin");
// tree.debug("Tree container got event " + event.type, node, event);
// tree.treeOnFocusInOut.call(tree, event);
if(node){
// For example clicking into an <input> that is part of a node
tree._callHook("nodeSetFocus", tree._makeHookContext(node, event), flag);
// tree._callHook("nodeSetFocus", node, flag);
}else{
tree._callHook("treeSetFocus", tree, flag);
}
}).on("selectstart" + ns, "span.fancytree-title", function(event){
// prevent mouse-drags to select text ranges
// tree.debug("<span title> got event " + event.type);
event.preventDefault();
}).on("keydown" + ns, function(event){
// TODO: also bind keyup and keypress
// tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus());
// if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){
if(opts.disabled || opts.keyboard === false ){
return true;
}
var res,
node = tree.focusNode, // node may be null
ctx = tree._makeHookContext(node || tree, event),
prevPhase = tree.phase;
try {
tree.phase = "userEvent";
// If a 'fancytreekeydown' handler returns false, skip the default
// handling (implemented by tree.nodeKeydown()).
if(node){
res = tree._triggerNodeEvent("keydown", node, event);
}else{
res = tree._triggerTreeEvent("keydown", event);
}
if ( res === "preventNav" ){
res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls
} else if ( res !== false ){
res = tree._callHook("nodeKeydown", ctx);
}
return res;
} finally {
tree.phase = prevPhase;
}
}).on("mousedown" + ns + " dblclick" + ns, function(event){
// that.tree.debug("event(" + event + "): !");
if(opts.disabled){
return true;
}
var ctx,
et = FT.getEventTarget(event),
node = et.node,
tree = that.tree,
prevPhase = tree.phase;
// that.tree.debug("event(" + event.type + "): node: ", node);
if( !node ){
return true; // Allow bubbling of other events
}
ctx = tree._makeHookContext(node, event);
// that.tree.debug("event(" + event.type + "): node: ", node);
try {
tree.phase = "userEvent";
switch(event.type) {
case "mousedown":
ctx.targetType = et.type;
if( node.isPagingNode() ) {
return tree._triggerNodeEvent("clickPaging", ctx, event) === true;
}
return ( tree._triggerNodeEvent("click", ctx, event) === false ) ? false : tree._callHook("nodeClick", ctx);
case "dblclick":
ctx.targetType = et.type;
return ( tree._triggerNodeEvent("dblclick", ctx, event) === false ) ? false : tree._callHook("nodeDblclick", ctx);
}
// } catch(e) {
// // var _ = null; // DT issue 117 // TODO
// $.error(e);
} finally {
tree.phase = prevPhase;
}
});
},
/** Return the active node or null.
* @returns {FancytreeNode}
*/
getActiveNode: function() {
return this.tree.activeNode;
},
/** Return the matching node or null.
* @param {string} key
* @returns {FancytreeNode}
*/
getNodeByKey: function(key) {
return this.tree.getNodeByKey(key);
},
/** Return the invisible system root node.
* @returns {FancytreeNode}
*/
getRootNode: function() {
return this.tree.rootNode;
},
/** Return the current tree instance.
* @returns {Fancytree}
*/
getTree: function() {
return this.tree;
}
});
// $.ui.fancytree was created by the widget factory. Create a local shortcut:
FT = $.ui.fancytree;
/**
* Static members in the `$.ui.fancytree` namespace.<br>
* <br>
* <pre class="sh_javascript sunlight-highlight-javascript">// Access static members:
* var node = $.ui.fancytree.getNode(element);
* alert($.ui.fancytree.version);
* </pre>
*
* @mixin Fancytree_Static
*/
$.extend($.ui.fancytree,
/** @lends Fancytree_Static# */
{
/** @type {string} */
version: "2.22.3", // Set to semver by 'grunt release'
/** @type {string} */
buildType: "production", // Set to 'production' by 'grunt build'
/** @type {int} */
debugLevel: 1, // Set to 1 by 'grunt build'
// Used by $.ui.fancytree.debug() and as default for tree.options.debugLevel
_nextId: 1,
_nextNodeKey: 1,
_extensions: {},
// focusTree: null,
/** Expose class object as $.ui.fancytree._FancytreeClass */
_FancytreeClass: Fancytree,
/** Expose class object as $.ui.fancytree._FancytreeNodeClass */
_FancytreeNodeClass: FancytreeNode,
/* Feature checks to provide backwards compatibility */
jquerySupports: {
// http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
positionMyOfs: isVersionAtLeast($.ui.version, 1, 9)
},
/** Throw an error if condition fails (debug method).
* @param {boolean} cond
* @param {string} msg
*/
assert: function(cond, msg){
return _assert(cond, msg);
},
/** Return a function that executes *fn* at most every *timeout* ms.
* @param {integer} timeout
* @param {function} fn
* @param {boolean} [invokeAsap=false]
* @param {any} [ctx]
*/
debounce: function(timeout, fn, invokeAsap, ctx) {
var timer;
if(arguments.length === 3 && typeof invokeAsap !== "boolean") {
ctx = invokeAsap;
invokeAsap = false;
}
return function() {
var args = arguments;
ctx = ctx || this;
invokeAsap && !timer && fn.apply(ctx, args);
clearTimeout(timer);
timer = setTimeout(function() {
invokeAsap || fn.apply(ctx, args);
timer = null;
}, timeout);
};
},
/** Write message to console if debugLevel >= 2
* @param {string} msg
*/
debug: function(msg){
/*jshint expr:true */
($.ui.fancytree.debugLevel >= 2) && consoleApply("log", arguments);
},
/** Write error message to console.
* @param {string} msg
*/
error: function(msg){
consoleApply("error", arguments);
},
/** Convert <, >, &, ", ', / to the equivalent entities.
*
* @param {string} s
* @returns {string}
*/
escapeHtml: _escapeHtml,
/** Make jQuery.position() arguments backwards compatible, i.e. if
* jQuery UI version <= 1.8, convert
* { my: "left+3 center", at: "left bottom", of: $target }
* to
* { my: "left center", at: "left bottom", of: $target, offset: "3 0" }
*
* See http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
* and http://jsfiddle.net/mar10/6xtu9a4e/
*/
fixPositionOptions: function(opts) {
if( opts.offset || ("" + opts.my + opts.at ).indexOf("%") >= 0 ) {
$.error("expected new position syntax (but '%' is not supported)");
}
if( ! $.ui.fancytree.jquerySupports.positionMyOfs ) {
var // parse 'left+3 center' into ['left+3 center', 'left', '+3', 'center', undefined]
myParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(opts.my),
atParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(opts.at),
// convert to numbers
dx = (myParts[2] ? (+myParts[2]) : 0) + (atParts[2] ? (+atParts[2]) : 0),
dy = (myParts[4] ? (+myParts[4]) : 0) + (atParts[4] ? (+atParts[4]) : 0);
opts = $.extend({}, opts, { // make a copy and overwrite
my: myParts[1] + " " + myParts[3],
at: atParts[1] + " " + atParts[3]
});
if( dx || dy ) {
opts.offset = "" + dx + " " + dy;
}
}
return opts;
},
/** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
*
* @param {Event} event Mouse event, e.g. click, ...
* @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
*/
getEventTargetType: function(event){
return this.getEventTarget(event).type;
},
/** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
*
* @param {Event} event Mouse event, e.g. click, ...
* @returns {object} Return a {node: FancytreeNode, type: TYPE} object
* TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
*/
getEventTarget: function(event){
var tcn = event && event.target ? event.target.className : "",
res = {node: this.getNode(event.target), type: undefined};
// We use a fast version of $(res.node).hasClass()
// See http://jsperf.com/test-for-classname/2
if( /\bfancytree-title\b/.test(tcn) ){
res.type = "title";
}else if( /\bfancytree-expander\b/.test(tcn) ){
res.type = (res.node.hasChildren() === false ? "prefix" : "expander");
}else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){
res.type = "checkbox";
}else if( /\bfancytree-icon\b/.test(tcn) ){
res.type = "icon";
}else if( /\bfancytree-node\b/.test(tcn) ){
// Somewhere near the title
res.type = "title";
}else if( event && event.target && $(event.target).closest(".fancytree-title").length ) {
// #228: clicking an embedded element inside a title
res.type = "title";
}
return res;
},
/** Return a FancytreeNode instance from element, event, or jQuery object.
*
* @param {Element | jQueryObject | Event} el
* @returns {FancytreeNode} matching node or null
*/
getNode: function(el){
if(el instanceof FancytreeNode){
return el; // el already was a FancytreeNode
}else if( el instanceof jQuery ){
el = el[0]; // el was a jQuery object: use the DOM element
}else if(el.originalEvent !== undefined){
el = el.target; // el was an Event
}
while( el ) {
if(el.ftnode) {
return el.ftnode;
}
el = el.parentNode;
}
return null;
},
/** Return a Fancytree instance, from element, index, event, or jQueryObject.
*
* @param {Element | jQueryObject | Event | integer | string} [el]
* @returns {Fancytree} matching tree or null
* @example
* $.ui.fancytree.getTree(); // Get first Fancytree instance on page
* $.ui.fancytree.getTree(1); // Get second Fancytree instance on page
* $.ui.fancytree.getTree("#tree"); // Get tree for this matching element
*
* @since 2.13
*/
getTree: function(el){
var widget;
if( el instanceof Fancytree ) {
return el; // el already was a Fancytree
}
if( el === undefined ) {
el = 0; // get first tree
}
if( typeof el === "number" ) {
el = $(".fancytree-container").eq(el); // el was an integer: return nth instance
} else if( typeof el === "string" ) {
el = $(el).eq(0); // el was a selector: use first match
} else if( el.selector !== undefined ) {
el = el.eq(0); // el was a jQuery object: use the first DOM element
} else if( el.originalEvent !== undefined ) {
el = $(el.target); // el was an Event
}
el = el.closest(":ui-fancytree");
widget = el.data("ui-fancytree") || el.data("fancytree"); // the latter is required by jQuery <= 1.8
return widget ? widget.tree : null;
},
/** Return an option value that has a default, but may be overridden by a
* callback or a node instance attribute.
*
* Evaluation sequence:<br>
*
* If tree.options.<optionName> is a callback that returns something, use that.<br>
* Else if node.<optionName> is defined, use that.<br>
* Else if tree.options.<optionName> is a value, use that.<br>
* Else use `defaultValue`.
*
* @param {string} optionName name of the option property (on node and tree)
* @param {FancytreeNode} node passed to the callback
* @param {object} nodeObject where to look for the local option property, e.g. `node` or `node.data`
* @param {object} treeOption where to look for the tree option, e.g. `tree.options` or `tree.options.dnd5`
* @param {any} [defaultValue]
* @returns {any}
*
* @example
* // Check for node.foo, tree,options.foo(), and tree.options.foo:
* $.ui.fancytree.evalOption("foo", node, node, tree.options);
* // Check for node.data.bar, tree,options.qux.bar(), and tree.options.qux.bar:
* $.ui.fancytree.evalOption("bar", node, node.data, tree.options.qux);
*
* @since 2.22
*/
evalOption: function(optionName, node, nodeObject, treeOptions, defaultValue) {
var ctx, res,
tree = node.tree,
treeOpt = treeOptions[optionName],
nodeOpt = nodeObject[optionName];
if( $.isFunction(treeOpt) ) {
ctx = { node: node, tree: tree, widget: tree.widget, options: tree.widget.options };
res = treeOpt.call(tree, {type: optionName}, ctx);
if( res == null ) {
res = nodeOpt;
}
} else {
res = (nodeOpt != null) ? nodeOpt : treeOpt;
}
if( res == null ) {
res = defaultValue; // no option set at all: return default
}
return res;
},
/** Convert a keydown or mouse event to a canonical string like 'ctrl+a',
* 'ctrl+shift+f2', 'shift+leftdblclick'.
*
* This is especially handy for switch-statements in event handlers.
*
* @param {event}
* @returns {string}
*
* @example
switch( $.ui.fancytree.eventToString(event) ) {
case "-":
tree.nodeSetExpanded(ctx, false);
break;
case "shift+return":
tree.nodeSetActive(ctx, true);
break;
case "down":
res = node.navigate(event.which, activate, true);
break;
default:
handled = false;
}
if( handled ){
event.preventDefault();
}
*/
eventToString: function(event) {
// Poor-man's hotkeys. See here for a complete implementation:
// https://github.com/jeresig/jquery.hotkeys
var which = event.which,
et = event.type,
s = [];
if( event.altKey ) { s.push("alt"); }
if( event.ctrlKey ) { s.push("ctrl"); }
if( event.metaKey ) { s.push("meta"); }
if( event.shiftKey ) { s.push("shift"); }
if( et === "click" || et === "dblclick" ) {
s.push(MOUSE_BUTTONS[event.button] + et);
} else {
if( !IGNORE_KEYCODES[which] ) {
s.push( SPECIAL_KEYCODES[which] || String.fromCharCode(which).toLowerCase() );
}
}
return s.join("+");
},
/** Write message to console if debugLevel >= 1
* @param {string} msg
*/
info: function(msg){
/*jshint expr:true */
($.ui.fancytree.debugLevel >= 1) && consoleApply("info", arguments);
},
/* @deprecated: use eventToString(event) instead.
*/
keyEventToString: function(event) {
this.warn("keyEventToString() is deprecated: use eventToString()");
return this.eventToString(event);
},
/** Return a wrapped handler method, that provides `this.super`.
*
* @example
// Implement `opts.createNode` event to add the 'draggable' attribute
$.ui.fancytree.overrideMethod(ctx.options, "createNode", function(event, data) {
// Default processing if any
this._super.apply(this, arguments);
// Add 'draggable' attribute
data.node.span.draggable = true;
});
*
* @param {object} instance
* @param {string} methodName
* @param {function} handler
*/
overrideMethod: function(instance, methodName, handler){
var prevSuper,
_super = instance[methodName] || $.noop;
// context = context || this;
instance[methodName] = function() {
try {
prevSuper = this._super;
this._super = _super;
return handler.apply(this, arguments);
} finally {
this._super = prevSuper;
}
};
},
/**
* Parse tree data from HTML <ul> markup
*
* @param {jQueryObject} $ul
* @returns {NodeData[]}
*/
parseHtml: function($ul) {
// TODO: understand this:
/*jshint validthis:true */
var classes, className, extraClasses, i, iPos, l, tmp, tmp2,
$children = $ul.find(">li"),
children = [];
$children.each(function() {
var allData, lowerCaseAttr,
$li = $(this),
$liSpan = $li.find(">span:first", this),
$liA = $liSpan.length ? null : $li.find(">a:first"),
d = { tooltip: null, data: {} };
if( $liSpan.length ) {
d.title = $liSpan.html();
} else if( $liA && $liA.length ) {
// If a <li><a> tag is specified, use it literally and extract href/target.
d.title = $liA.html();
d.data.href = $liA.attr("href");
d.data.target = $liA.attr("target");
d.tooltip = $liA.attr("title");
} else {
// If only a <li> tag is specified, use the trimmed string up to
// the next child <ul> tag.
d.title = $li.html();
iPos = d.title.search(/<ul/i);
if( iPos >= 0 ){
d.title = d.title.substring(0, iPos);
}
}
d.title = $.trim(d.title);
// Make sure all fields exist
for(i=0, l=CLASS_ATTRS.length; i<l; i++){
d[CLASS_ATTRS[i]] = undefined;
}
// Initialize to `true`, if class is set and collect extraClasses
classes = this.className.split(" ");
extraClasses = [];
for(i=0, l=classes.length; i<l; i++){
className = classes[i];
if(CLASS_ATTR_MAP[className]){
d[className] = true;
}else{
extraClasses.push(className);
}
}
d.extraClasses = extraClasses.join(" ");
// Parse node options from ID, title and class attributes
tmp = $li.attr("title");
if( tmp ){
d.tooltip = tmp; // overrides <a title='...'>
}
tmp = $li.attr("id");
if( tmp ){
d.key = tmp;
}
// Add <li data-NAME='...'> as node.data.NAME
allData = _getElementDataAsDict($li);
if( allData && !$.isEmptyObject(allData) ) {
// #507: convert data-hidecheckbox (lower case) to hideCheckbox
for( lowerCaseAttr in NODE_ATTR_LOWERCASE_MAP ) {
if( allData.hasOwnProperty(lowerCaseAttr) ) {
allData[NODE_ATTR_LOWERCASE_MAP[lowerCaseAttr]] = allData[lowerCaseAttr];
delete allData[lowerCaseAttr];
}
}
// #56: Allow to set special node.attributes from data-...
for(i=0, l=NODE_ATTRS.length; i<l; i++){
tmp = NODE_ATTRS[i];
tmp2 = allData[tmp];
if( tmp2 != null ) {
delete allData[tmp];
d[tmp] = tmp2;
}
}
// All other data-... goes to node.data...
$.extend(d.data, allData);
}
// Recursive reading of child nodes, if LI tag contains an UL tag
$ul = $li.find(">ul:first");
if( $ul.length ) {
d.children = $.ui.fancytree.parseHtml($ul);
}else{
d.children = d.lazy ? undefined : null;
}
children.push(d);
// FT.debug("parse ", d, children);
});
return children;
},
/** Add Fancytree extension definition to the list of globally available extensions.
*
* @param {object} definition
*/
registerExtension: function(definition){
_assert(definition.name != null, "extensions must have a `name` property.");
_assert(definition.version != null, "extensions must have a `version` property.");
$.ui.fancytree._extensions[definition.name] = definition;
},
/** Inverse of escapeHtml().
*
* @param {string} s
* @returns {string}
*/
unescapeHtml: function(s){
var e = document.createElement("div");
e.innerHTML = s;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
},
/** Write warning message to console.
* @param {string} msg
*/
warn: function(msg){
consoleApply("warn", arguments);
}
});
}(jQuery, window, document));
// Extending Fancytree
// ===================
//
// See also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html) of this code.
//
// Every extension should have a comment header containing some information
// about the author, copyright and licensing. Also a pointer to the latest
// source code.
// Prefix with `/*!` so the comment is not removed by the minifier.
/*!
* jquery.fancytree.childcounter.js
*
* Add a child counter bubble to tree nodes.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
// To keep the global namespace clean, we wrap everything in a closure
;(function($, undefined) {
// Consider to use [strict mode](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/)
"use strict";
// The [coding guidelines](http://contribute.jquery.org/style-guide/js/)
// require jshint compliance.
// But for this sample, we want to allow unused variables for demonstration purpose.
/*jshint unused:false */
// Adding methods
// --------------
// New member functions can be added to the `Fancytree` class.
// This function will be available for every tree instance:
//
// var tree = $("#tree").fancytree("getTree");
// tree.countSelected(false);
$.ui.fancytree._FancytreeClass.prototype.countSelected = function(topOnly){
var tree = this,
treeOptions = tree.options;
return tree.getSelectedNodes(topOnly).length;
};
// The `FancytreeNode` class can also be easily extended. This would be called
// like
// node.updateCounters();
//
// It is also good practice to add a docstring comment.
/**
* [ext-childcounter] Update counter badges for `node` and its parents.
* May be called in the `loadChildren` event, to update parents of lazy loaded
* nodes.
* @alias FancytreeNode#updateCounters
* @requires jquery.fancytree.childcounters.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.updateCounters = function(){
var node = this,
$badge = $("span.fancytree-childcounter", node.span),
extOpts = node.tree.options.childcounter,
count = node.countChildren(extOpts.deep);
node.data.childCounter = count;
if( (count || !extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ) {
if( !$badge.length ) {
$badge = $("<span class='fancytree-childcounter'/>").appendTo($("span.fancytree-icon", node.span));
}
$badge.text(count);
} else {
$badge.remove();
}
if( extOpts.deep && !node.isTopLevel() && !node.isRoot() ) {
node.parent.updateCounters();
}
};
// Finally, we can extend the widget API and create functions that are called
// like so:
//
// $("#tree").fancytree("widgetMethod1", "abc");
$.ui.fancytree.prototype.widgetMethod1 = function(arg1){
var tree = this.tree;
return arg1;
};
// Register a Fancytree extension
// ------------------------------
// A full blown extension, extension is available for all trees and can be
// enabled like so (see also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html)):
//
// <script src="../src/jquery.fancytree.js"></script>
// <script src="../src/jquery.fancytree.childcounter.js"></script>
// ...
//
// $("#tree").fancytree({
// extensions: ["childcounter"],
// childcounter: {
// hideExpanded: true
// },
// ...
// });
//
/* 'childcounter' extension */
$.ui.fancytree.registerExtension({
// Every extension must be registered by a unique name.
name: "childcounter",
// Version information should be compliant with [semver](http://semver.org)
version: "2.22.3",
// Extension specific options and their defaults.
// This options will be available as `tree.options.childcounter.hideExpanded`
options: {
deep: true,
hideZeros: true,
hideExpanded: false
},
// Attributes other than `options` (or functions) can be defined here, and
// will be added to the tree.ext.EXTNAME namespace, in this case `tree.ext.childcounter.foo`.
// They can also be accessed as `this._local.foo` from within the extension
// methods.
foo: 42,
// Local functions are prefixed with an underscore '_'.
// Callable as `this._local._appendCounter()`.
_appendCounter: function(bar){
var tree = this;
},
// **Override virtual methods for this extension.**
//
// Fancytree implements a number of 'hook methods', prefixed by 'node...' or 'tree...'.
// with a `ctx` argument (see [EventData](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/global.html#EventData)
// for details) and an extended calling context:<br>
// `this` : the Fancytree instance<br>
// `this._local`: the namespace that contains extension attributes and private methods (same as this.ext.EXTNAME)<br>
// `this._super`: the virtual function that was overridden (member of previous extension or Fancytree)
//
// See also the [complete list of available hook functions](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree_Hooks.html).
/* Init */
// `treeInit` is triggered when a tree is initalized. We can set up classes or
// bind event handlers here...
treeInit: function(ctx){
var tree = this, // same as ctx.tree,
opts = ctx.options,
extOpts = ctx.options.childcounter;
// Optionally check for dependencies with other extensions
/* this._requireExtension("glyph", false, false); */
// Call the base implementation
this._superApply(arguments);
// Add a class to the tree container
this.$container.addClass("fancytree-ext-childcounter");
},
// Destroy this tree instance (we only call the default implementation, so
// this method could as well be omitted).
treeDestroy: function(ctx){
this._superApply(arguments);
},
// Overload the `renderTitle` hook, to append a counter badge
nodeRenderTitle: function(ctx, title) {
var node = ctx.node,
extOpts = ctx.options.childcounter,
count = (node.data.childCounter == null) ? node.countChildren(extOpts.deep) : +node.data.childCounter;
// Let the base implementation render the title
// We use `_super()` instead of `_superApply()` here, since it is a little bit
// more performant when called often
this._super(ctx, title);
// Append a counter badge
if( (count || ! extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ){
$("span.fancytree-icon", node.span).append($("<span class='fancytree-childcounter'/>").text(count));
}
},
// Overload the `setExpanded` hook, so the counters are updated
nodeSetExpanded: function(ctx, flag, callOpts) {
var tree = ctx.tree,
node = ctx.node;
// Let the base implementation expand/collapse the node, then redraw the title
// after the animation has finished
return this._superApply(arguments).always(function(){
tree.nodeRenderTitle(ctx);
});
}
// End of extension definition
});
// End of namespace closure
}(jQuery));
/*!
*
* jquery.fancytree.clones.js
* Support faster lookup of nodes by key and shared ref-ids.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
function _assert(cond, msg){
// TODO: see qunit.js extractStacktrace()
if(!cond){
msg = msg ? ": " + msg : "";
$.error("Assertion failed" + msg);
}
}
/* Return first occurrence of member from array. */
function _removeArrayMember(arr, elem) {
// TODO: use Array.indexOf for IE >= 9
var i;
for (i = arr.length - 1; i >= 0; i--) {
if (arr[i] === elem) {
arr.splice(i, 1);
return true;
}
}
return false;
}
// /**
// * Calculate a 32 bit FNV-1a hash
// * Found here: https://gist.github.com/vaiorabbit/5657561
// * Ref.: http://isthe.com/chongo/tech/comp/fnv/
// *
// * @param {string} str the input value
// * @param {boolean} [asString=false] set to true to return the hash value as
// * 8-digit hex string instead of an integer
// * @param {integer} [seed] optionally pass the hash of the previous chunk
// * @returns {integer | string}
// */
// function hashFnv32a(str, asString, seed) {
// /*jshint bitwise:false */
// var i, l,
// hval = (seed === undefined) ? 0x811c9dc5 : seed;
// for (i = 0, l = str.length; i < l; i++) {
// hval ^= str.charCodeAt(i);
// hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
// }
// if( asString ){
// // Convert to 8 digit hex string
// return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
// }
// return hval >>> 0;
// }
/**
* JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)
*
* @author <a href="mailto:[email protected]">Gary Court</a>
* @see http://github.com/garycourt/murmurhash-js
* @author <a href="mailto:[email protected]">Austin Appleby</a>
* @see http://sites.google.com/site/murmurhash/
*
* @param {string} key ASCII only
* @param {boolean} [asString=false]
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
function hashMurmur3(key, asString, seed) {
/*jshint bitwise:false */
var h1b, k1,
remainder = key.length & 3,
bytes = key.length - remainder,
h1 = seed,
c1 = 0xcc9e2d51,
c2 = 0x1b873593,
i = 0;
while (i < bytes) {
k1 =
((key.charCodeAt(i) & 0xff)) |
((key.charCodeAt(++i) & 0xff) << 8) |
((key.charCodeAt(++i) & 0xff) << 16) |
((key.charCodeAt(++i) & 0xff) << 24);
++i;
k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19);
h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;
h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));
}
k1 = 0;
switch (remainder) {
/*jshint -W086:true */
case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
case 1: k1 ^= (key.charCodeAt(i) & 0xff);
k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1;
}
h1 ^= key.length;
h1 ^= h1 >>> 16;
h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
h1 ^= h1 >>> 13;
h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;
h1 ^= h1 >>> 16;
if( asString ){
// Convert to 8 digit hex string
return ("0000000" + (h1 >>> 0).toString(16)).substr(-8);
}
return h1 >>> 0;
}
// console.info(hashMurmur3("costarring"));
// console.info(hashMurmur3("costarring", true));
// console.info(hashMurmur3("liquid"));
// console.info(hashMurmur3("liquid", true));
/*
* Return a unique key for node by calculationg the hash of the parents refKey-list
*/
function calcUniqueKey(node) {
var key,
path = $.map(node.getParentList(false, true), function(e){ return e.refKey || e.key; });
path = path.join("/");
key = "id_" + hashMurmur3(path, true);
// node.debug(path + " -> " + key);
return key;
}
/**
* [ext-clones] Return a list of clone-nodes or null.
* @param {boolean} [includeSelf=false]
* @returns {FancytreeNode[] | null}
*
* @alias FancytreeNode#getCloneList
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.getCloneList = function(includeSelf){
var key,
tree = this.tree,
refList = tree.refMap[this.refKey] || null,
keyMap = tree.keyMap;
if( refList ) {
key = this.key;
// Convert key list to node list
if( includeSelf ) {
refList = $.map(refList, function(val){ return keyMap[val]; });
} else {
refList = $.map(refList, function(val){ return val === key ? null : keyMap[val]; });
if( refList.length < 1 ) {
refList = null;
}
}
}
return refList;
};
/**
* [ext-clones] Return true if this node has at least another clone with same refKey.
* @returns {boolean}
*
* @alias FancytreeNode#isClone
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.isClone = function(){
var refKey = this.refKey || null,
refList = refKey && this.tree.refMap[refKey] || null;
return !!(refList && refList.length > 1);
};
/**
* [ext-clones] Update key and/or refKey for an existing node.
* @param {string} key
* @param {string} refKey
* @returns {boolean}
*
* @alias FancytreeNode#reRegister
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.reRegister = function(key, refKey){
key = (key == null) ? null : "" + key;
refKey = (refKey == null) ? null : "" + refKey;
// this.debug("reRegister", key, refKey);
var tree = this.tree,
prevKey = this.key,
prevRefKey = this.refKey,
keyMap = tree.keyMap,
refMap = tree.refMap,
refList = refMap[prevRefKey] || null,
// curCloneKeys = refList ? node.getCloneList(true),
modified = false;
// Key has changed: update all references
if( key != null && key !== this.key ) {
if( keyMap[key] ) {
$.error("[ext-clones] reRegister(" + key + "): already exists: " + this);
}
// Update keyMap
delete keyMap[prevKey];
keyMap[key] = this;
// Update refMap
if( refList ) {
refMap[prevRefKey] = $.map(refList, function(e){
return e === prevKey ? key : e;
});
}
this.key = key;
modified = true;
}
// refKey has changed
if( refKey != null && refKey !== this.refKey ) {
// Remove previous refKeys
if( refList ){
if( refList.length === 1 ){
delete refMap[prevRefKey];
}else{
refMap[prevRefKey] = $.map(refList, function(e){
return e === prevKey ? null : e;
});
}
}
// Add refKey
if( refMap[refKey] ) {
refMap[refKey].append(key);
}else{
refMap[refKey] = [ this.key ];
}
this.refKey = refKey;
modified = true;
}
return modified;
};
/**
* [ext-clones] Define a refKey for an existing node.
* @param {string} refKey
* @returns {boolean}
*
* @alias FancytreeNode#setRefKey
* @requires jquery.fancytree.clones.js
* @since 2.16
*/
$.ui.fancytree._FancytreeNodeClass.prototype.setRefKey = function(refKey){
return this.reRegister(null, refKey);
};
/**
* [ext-clones] Return all nodes with a given refKey (null if not found).
* @param {string} refKey
* @param {FancytreeNode} [rootNode] optionally restrict results to descendants of this node
* @returns {FancytreeNode[] | null}
* @alias Fancytree#getNodesByRef
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeClass.prototype.getNodesByRef = function(refKey, rootNode){
var keyMap = this.keyMap,
refList = this.refMap[refKey] || null;
if( refList ) {
// Convert key list to node list
if( rootNode ) {
refList = $.map(refList, function(val){
var node = keyMap[val];
return node.isDescendantOf(rootNode) ? node : null;
});
}else{
refList = $.map(refList, function(val){ return keyMap[val]; });
}
if( refList.length < 1 ) {
refList = null;
}
}
return refList;
};
/**
* [ext-clones] Replace a refKey with a new one.
* @param {string} oldRefKey
* @param {string} newRefKey
* @alias Fancytree#changeRefKey
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeClass.prototype.changeRefKey = function(oldRefKey, newRefKey) {
var i, node,
keyMap = this.keyMap,
refList = this.refMap[oldRefKey] || null;
if (refList) {
for (i = 0; i < refList.length; i++) {
node = keyMap[refList[i]];
node.refKey = newRefKey;
}
delete this.refMap[oldRefKey];
this.refMap[newRefKey] = refList;
}
};
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "clones",
version: "2.22.3",
// Default options for this extension.
options: {
highlightActiveClones: true, // set 'fancytree-active-clone' on active clones and all peers
highlightClones: false // set 'fancytree-clone' class on any node that has at least one clone
},
treeCreate: function(ctx){
this._superApply(arguments);
ctx.tree.refMap = {};
ctx.tree.keyMap = {};
},
treeInit: function(ctx){
this.$container.addClass("fancytree-ext-clones");
_assert(ctx.options.defaultKey == null);
// Generate unique / reproducible default keys
ctx.options.defaultKey = function(node){
return calcUniqueKey(node);
};
// The default implementation loads initial data
this._superApply(arguments);
},
treeClear: function(ctx){
ctx.tree.refMap = {};
ctx.tree.keyMap = {};
return this._superApply(arguments);
},
treeRegisterNode: function(ctx, add, node) {
var refList, len,
tree = ctx.tree,
keyMap = tree.keyMap,
refMap = tree.refMap,
key = node.key,
refKey = (node && node.refKey != null) ? "" + node.refKey : null;
// ctx.tree.debug("clones.treeRegisterNode", add, node);
if( node.isStatusNode() ){
return this._super(ctx, add, node);
}
if( add ) {
if( keyMap[node.key] != null ) {
$.error("clones.treeRegisterNode: node.key already exists: " + node);
}
keyMap[key] = node;
if( refKey ) {
refList = refMap[refKey];
if( refList ) {
refList.push(key);
if( refList.length === 2 && ctx.options.clones.highlightClones ) {
// Mark peer node, if it just became a clone (no need to
// mark current node, since it will be rendered later anyway)
keyMap[refList[0]].renderStatus();
}
} else {
refMap[refKey] = [key];
}
// node.debug("clones.treeRegisterNode: add clone =>", refMap[refKey]);
}
}else {
if( keyMap[key] == null ) {
$.error("clones.treeRegisterNode: node.key not registered: " + node.key);
}
delete keyMap[key];
if( refKey ) {
refList = refMap[refKey];
// node.debug("clones.treeRegisterNode: remove clone BEFORE =>", refMap[refKey]);
if( refList ) {
len = refList.length;
if( len <= 1 ){
_assert(len === 1);
_assert(refList[0] === key);
delete refMap[refKey];
}else{
_removeArrayMember(refList, key);
// Unmark peer node, if this was the only clone
if( len === 2 && ctx.options.clones.highlightClones ) {
// node.debug("clones.treeRegisterNode: last =>", node.getCloneList());
keyMap[refList[0]].renderStatus();
}
}
// node.debug("clones.treeRegisterNode: remove clone =>", refMap[refKey]);
}
}
}
return this._super(ctx, add, node);
},
nodeRenderStatus: function(ctx) {
var $span, res,
node = ctx.node;
res = this._super(ctx);
if( ctx.options.clones.highlightClones ) {
$span = $(node[ctx.tree.statusClassPropName]);
// Only if span already exists
if( $span.length && node.isClone() ){
// node.debug("clones.nodeRenderStatus: ", ctx.options.clones.highlightClones);
$span.addClass("fancytree-clone");
}
}
return res;
},
nodeSetActive: function(ctx, flag, callOpts) {
var res,
scpn = ctx.tree.statusClassPropName,
node = ctx.node;
res = this._superApply(arguments);
if( ctx.options.clones.highlightActiveClones && node.isClone() ) {
$.each(node.getCloneList(true), function(idx, n){
// n.debug("clones.nodeSetActive: ", flag !== false);
$(n[scpn]).toggleClass("fancytree-active-clone", flag !== false);
});
}
return res;
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.dnd.js
*
* Drag-and-drop support (jQuery UI draggable/droppable).
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
;(function($, window, document, undefined) {
"use strict";
/* *****************************************************************************
* Private functions and variables
*/
var didRegisterDnd = false,
classDropAccept = "fancytree-drop-accept",
classDropAfter = "fancytree-drop-after",
classDropBefore = "fancytree-drop-before",
classDropOver = "fancytree-drop-over",
classDropReject = "fancytree-drop-reject",
classDropTarget = "fancytree-drop-target";
/* Convert number to string and prepend +/-; return empty string for 0.*/
function offsetString(n){
return n === 0 ? "" : (( n > 0 ) ? ("+" + n) : ("" + n));
}
//--- Extend ui.draggable event handling --------------------------------------
function _registerDnd() {
if(didRegisterDnd){
return;
}
// Register proxy-functions for draggable.start/drag/stop
$.ui.plugin.add("draggable", "connectToFancytree", {
start: function(event, ui) {
// 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("ftSourceNode") || null;
if(sourceNode) {
// Adjust helper offset, so cursor is slightly outside top/left corner
draggable.offset.click.top = -2;
draggable.offset.click.left = + 16;
// Trigger dragStart event
// TODO: when called as connectTo..., the return value is ignored(?)
return sourceNode.tree.ext.dnd._onDragEvent("start", sourceNode, null, event, ui, draggable);
}
},
drag: function(event, ui) {
var ctx, isHelper, logObject,
// 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("ftSourceNode") || null,
prevTargetNode = ui.helper.data("ftTargetNode") || null,
targetNode = $.ui.fancytree.getNode(event.target),
dndOpts = sourceNode && sourceNode.tree.options.dnd;
// logObject = sourceNode || prevTargetNode || $.ui.fancytree;
// logObject.debug("Drag event:", event, event.shiftKey);
if(event.target && !targetNode){
// We got a drag event, but the targetNode could not be found
// at the event location. This may happen,
// 1. if the mouse jumped over the drag helper,
// 2. or if a non-fancytree element is dragged
// We ignore it:
isHelper = $(event.target).closest("div.fancytree-drag-helper,#fancytree-drop-marker").length > 0;
if(isHelper){
logObject = sourceNode || prevTargetNode || $.ui.fancytree;
logObject.debug("Drag event over helper: ignored.");
return;
}
}
ui.helper.data("ftTargetNode", targetNode);
if( dndOpts && dndOpts.updateHelper ) {
ctx = sourceNode.tree._makeHookContext(sourceNode, event, {
otherNode: targetNode,
ui: ui,
draggable: draggable,
dropMarker: $("#fancytree-drop-marker")
});
dndOpts.updateHelper.call(sourceNode.tree, sourceNode, ctx);
}
// Leaving a tree node
if(prevTargetNode && prevTargetNode !== targetNode ) {
prevTargetNode.tree.ext.dnd._onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
}
if(targetNode){
if(!targetNode.tree.options.dnd.dragDrop) {
// not enabled as drop target
} else if(targetNode === prevTargetNode) {
// Moving over same node
targetNode.tree.ext.dnd._onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
}else{
// Entering this node first time
targetNode.tree.ext.dnd._onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
targetNode.tree.ext.dnd._onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
}
}
// else go ahead with standard event handling
},
stop: function(event, ui) {
var logObject,
// 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10:
draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("ftSourceNode") || null,
targetNode = ui.helper.data("ftTargetNode") || null,
dropped = (event.type === "mouseup" && event.which === 1);
if(!dropped){
logObject = sourceNode || targetNode || $.ui.fancytree;
logObject.debug("Drag was cancelled");
}
if(targetNode) {
if(dropped){
targetNode.tree.ext.dnd._onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
}
targetNode.tree.ext.dnd._onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
}
if(sourceNode){
sourceNode.tree.ext.dnd._onDragEvent("stop", sourceNode, null, event, ui, draggable);
}
}
});
didRegisterDnd = true;
}
/* *****************************************************************************
* Drag and drop support
*/
function _initDragAndDrop(tree) {
var dnd = tree.options.dnd || null,
glyph = tree.options.glyph || null;
// Register 'connectToFancytree' option with ui.draggable
if( dnd ) {
_registerDnd();
}
// Attach ui.draggable to this Fancytree instance
if(dnd && dnd.dragStart ) {
tree.widget.element.draggable($.extend({
addClasses: false,
// DT issue 244: helper should be child of scrollParent:
appendTo: tree.$container,
// appendTo: "body",
containment: false,
// containment: "parent",
delay: 0,
distance: 4,
revert: false,
scroll: true, // to disable, also set css 'position: inherit' on ul.fancytree-container
scrollSpeed: 7,
scrollSensitivity: 10,
// Delegate draggable.start, drag, and stop events to our handler
connectToFancytree: true,
// Let source tree create the helper element
helper: function(event) {
var $helper, $nodeTag, opts,
sourceNode = $.ui.fancytree.getNode(event.target);
if(!sourceNode){
// #405, DT issue 211: might happen, if dragging a table *header*
return "<div>ERROR?: helper requested but sourceNode not found</div>";
}
opts = sourceNode.tree.options.dnd;
$nodeTag = $(sourceNode.span);
// Only event and node argument is available
$helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>")
.css({zIndex: 3, position: "relative"}) // so it appears above ext-wide selection bar
.append($nodeTag.find("span.fancytree-title").clone());
// Attach node reference to helper object
$helper.data("ftSourceNode", sourceNode);
// Support glyph symbols instead of icons
if( glyph ) {
$helper.find(".fancytree-drag-helper-img")
.addClass(glyph.map.dragHelper);
}
// Allow to modify the helper, e.g. to add multi-node-drag feedback
if( opts.initHelper ) {
opts.initHelper.call(sourceNode.tree, sourceNode, {
node: sourceNode,
tree: sourceNode.tree,
originalEvent: event,
ui: { helper: $helper }
});
}
// We return an unconnected element, so `draggable` will add this
// to the parent specified as `appendTo` option
return $helper;
},
start: function(event, ui) {
var sourceNode = ui.helper.data("ftSourceNode");
return !!sourceNode; // Abort dragging if no node could be found
}
}, tree.options.dnd.draggable));
}
// Attach ui.droppable to this Fancytree instance
if(dnd && dnd.dragDrop) {
tree.widget.element.droppable($.extend({
addClasses: false,
tolerance: "intersect",
greedy: false
/*
activate: function(event, ui) {
tree.debug("droppable - activate", event, ui, this);
},
create: function(event, ui) {
tree.debug("droppable - create", event, ui);
},
deactivate: function(event, ui) {
tree.debug("droppable - deactivate", event, ui);
},
drop: function(event, ui) {
tree.debug("droppable - drop", event, ui);
},
out: function(event, ui) {
tree.debug("droppable - out", event, ui);
},
over: function(event, ui) {
tree.debug("droppable - over", event, ui);
}
*/
}, tree.options.dnd.droppable));
}
}
/* *****************************************************************************
*
*/
$.ui.fancytree.registerExtension({
name: "dnd",
version: "2.22.3",
// Default options for this extension.
options: {
// Make tree nodes accept draggables
autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering.
draggable: null, // Additional options passed to jQuery draggable
droppable: null, // Additional options passed to jQuery droppable
focusOnClick: false, // Focus, although draggable cancels mousedown event (#270)
preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
preventRecursiveMoves: true,// Prevent dropping nodes on own descendants
smartRevert: true, // set draggable.revert = true if drop was rejected
dropMarkerOffsetX: -24, // absolute position offset for .fancytree-drop-marker relatively to ..fancytree-title (icon/img near a node accepting drop)
dropMarkerInsertOffsetX: -16, // additional offset for drop-marker with hitMode = "before"/"after"
// Events (drag support)
dragStart: null, // Callback(sourceNode, data), return true, to enable dnd
dragStop: null, // Callback(sourceNode, data)
initHelper: null, // Callback(sourceNode, data)
updateHelper: null, // Callback(sourceNode, data)
// Events (drop support)
dragEnter: null, // Callback(targetNode, data)
dragOver: null, // Callback(targetNode, data)
dragExpand: null, // Callback(targetNode, data), return false to prevent autoExpand
dragDrop: null, // Callback(targetNode, data)
dragLeave: null // Callback(targetNode, data)
},
treeInit: function(ctx){
var tree = ctx.tree;
this._superApply(arguments);
// issue #270: draggable eats mousedown events
if( tree.options.dnd.dragStart ){
tree.$container.on("mousedown", function(event){
// if( !tree.hasFocus() && ctx.options.dnd.focusOnClick ) {
if( ctx.options.dnd.focusOnClick ) { // #270
var node = $.ui.fancytree.getNode(event);
if (node){
node.debug("Re-enable focus that was prevented by jQuery UI draggable.");
// node.setFocus();
// $(node.span).closest(":tabbable").focus();
// $(event.target).trigger("focus");
// $(event.target).closest(":tabbable").trigger("focus");
}
setTimeout(function() { // #300
$(event.target).closest(":tabbable").focus();
}, 10);
}
});
}
_initDragAndDrop(tree);
},
/* Display drop marker according to hitMode ('after', 'before', 'over'). */
_setDndStatus: function(sourceNode, targetNode, helper, hitMode, accept) {
var markerOffsetX,
markerAt = "center",
instData = this._local,
dndOpt = this.options.dnd ,
glyphOpt = this.options.glyph,
$source = sourceNode ? $(sourceNode.span) : null,
$target = $(targetNode.span),
$targetTitle = $target.find("span.fancytree-title");
if( !instData.$dropMarker ) {
instData.$dropMarker = $("<div id='fancytree-drop-marker'></div>")
.hide()
.css({"z-index": 1000})
.prependTo($(this.$div).parent());
// .prependTo("body");
if( glyphOpt ) {
// instData.$dropMarker.addClass(glyph.map.dragHelper);
instData.$dropMarker
.addClass(glyphOpt.map.dropMarker);
}
}
if( hitMode === "after" || hitMode === "before" || hitMode === "over" ){
markerOffsetX = dndOpt.dropMarkerOffsetX || 0;
switch(hitMode){
case "before":
markerAt = "top";
markerOffsetX += (dndOpt.dropMarkerInsertOffsetX || 0);
break;
case "after":
markerAt = "bottom";
markerOffsetX += (dndOpt.dropMarkerInsertOffsetX || 0);
break;
}
instData.$dropMarker
.toggleClass(classDropAfter, hitMode === "after")
.toggleClass(classDropOver, hitMode === "over")
.toggleClass(classDropBefore, hitMode === "before")
.show()
.position($.ui.fancytree.fixPositionOptions({
my: "left" + offsetString(markerOffsetX) + " center",
at: "left " + markerAt,
of: $targetTitle
}));
} else {
instData.$dropMarker.hide();
}
if( $source ){
$source
.toggleClass(classDropAccept, accept === true)
.toggleClass(classDropReject, accept === false);
}
$target
.toggleClass(classDropTarget, hitMode === "after" || hitMode === "before" || hitMode === "over")
.toggleClass(classDropAfter, hitMode === "after")
.toggleClass(classDropBefore, hitMode === "before")
.toggleClass(classDropAccept, accept === true)
.toggleClass(classDropReject, accept === false);
helper
.toggleClass(classDropAccept, accept === true)
.toggleClass(classDropReject, accept === false);
},
/*
* Handles drag'n'drop functionality.
*
* A standard jQuery drag-and-drop process may generate these calls:
*
* start:
* _onDragEvent("start", sourceNode, null, event, ui, draggable);
* drag:
* _onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
* _onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
* _onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
* stop:
* _onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
* _onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
* _onDragEvent("stop", sourceNode, null, event, ui, draggable);
*/
_onDragEvent: function(eventName, node, otherNode, event, ui, draggable) {
// if(eventName !== "over"){
// this.debug("tree.ext.dnd._onDragEvent(%s, %o, %o) - %o", eventName, node, otherNode, this);
// }
var accept, nodeOfs, parentRect, rect, relPos, relPos2,
enterResponse, hitMode, r,
opts = this.options,
dnd = opts.dnd,
ctx = this._makeHookContext(node, event, {otherNode: otherNode, ui: ui, draggable: draggable}),
res = null,
that = this,
$nodeTag = $(node.span);
if( dnd.smartRevert ) {
draggable.options.revert = "invalid";
}
switch (eventName) {
case "start":
if( node.isStatusNode() ) {
res = false;
} else if(dnd.dragStart) {
res = dnd.dragStart(node, ctx);
}
if(res === false) {
this.debug("tree.dragStart() cancelled");
//draggable._clear();
// NOTE: the return value seems to be ignored (drag is not cancelled, when false is returned)
// TODO: call this._cancelDrag()?
ui.helper.trigger("mouseup")
.hide();
} else {
if( dnd.smartRevert ) {
// #567, #593: fix revert position
// rect = node.li.getBoundingClientRect();
rect = node[ctx.tree.nodeContainerAttrName].getBoundingClientRect();
parentRect = $(draggable.options.appendTo)[0].getBoundingClientRect();
draggable.originalPosition.left = Math.max(0, rect.left - parentRect.left);
draggable.originalPosition.top = Math.max(0, rect.top - parentRect.top);
}
$nodeTag.addClass("fancytree-drag-source");
// Register global handlers to allow cancel
$(document)
.on("keydown.fancytree-dnd,mousedown.fancytree-dnd", function(event){
// node.tree.debug("dnd global event", event.type, event.which);
if( event.type === "keydown" && event.which === $.ui.keyCode.ESCAPE ) {
that.ext.dnd._cancelDrag();
} else if( event.type === "mousedown" ) {
that.ext.dnd._cancelDrag();
}
});
}
break;
case "enter":
if(dnd.preventRecursiveMoves && node.isDescendantOf(otherNode)){
r = false;
}else{
r = dnd.dragEnter ? dnd.dragEnter(node, ctx) : null;
}
if(!r){
// convert null, undefined, false to false
res = false;
}else if ( $.isArray(r) ) {
// TODO: also accept passing an object of this format directly
res = {
over: ($.inArray("over", r) >= 0),
before: ($.inArray("before", r) >= 0),
after: ($.inArray("after", r) >= 0)
};
}else{
res = {
over: ((r === true) || (r === "over")),
before: ((r === true) || (r === "before")),
after: ((r === true) || (r === "after"))
};
}
ui.helper.data("enterResponse", res);
// this.debug("helper.enterResponse: %o", res);
break;
case "over":
enterResponse = ui.helper.data("enterResponse");
hitMode = null;
if(enterResponse === false){
// Don't call dragOver if onEnter returned false.
// break;
} else if(typeof enterResponse === "string") {
// Use hitMode from onEnter if provided.
hitMode = enterResponse;
} else {
// Calculate hitMode from relative cursor position.
nodeOfs = $nodeTag.offset();
relPos = { x: event.pageX - nodeOfs.left,
y: event.pageY - nodeOfs.top };
relPos2 = { x: relPos.x / $nodeTag.width(),
y: relPos.y / $nodeTag.height() };
if( enterResponse.after && relPos2.y > 0.75 ){
hitMode = "after";
} else if(!enterResponse.over && enterResponse.after && relPos2.y > 0.5 ){
hitMode = "after";
} else if(enterResponse.before && relPos2.y <= 0.25) {
hitMode = "before";
} else if(!enterResponse.over && enterResponse.before && relPos2.y <= 0.5) {
hitMode = "before";
} else if(enterResponse.over) {
hitMode = "over";
}
// Prevent no-ops like 'before source node'
// TODO: these are no-ops when moving nodes, but not in copy mode
if( dnd.preventVoidMoves ){
if(node === otherNode){
this.debug(" drop over source node prevented");
hitMode = null;
}else if(hitMode === "before" && otherNode && node === otherNode.getNextSibling()){
this.debug(" drop after source node prevented");
hitMode = null;
}else if(hitMode === "after" && otherNode && node === otherNode.getPrevSibling()){
this.debug(" drop before source node prevented");
hitMode = null;
}else if(hitMode === "over" && otherNode && otherNode.parent === node && otherNode.isLastSibling() ){
this.debug(" drop last child over own parent prevented");
hitMode = null;
}
}
// this.debug("hitMode: %s - %s - %s", hitMode, (node.parent === otherNode), node.isLastSibling());
ui.helper.data("hitMode", hitMode);
}
// Auto-expand node (only when 'over' the node, not 'before', or 'after')
if(hitMode !== "before" && hitMode !== "after" && dnd.autoExpandMS &&
node.hasChildren() !== false && !node.expanded &&
(!dnd.dragExpand || dnd.dragExpand(node, ctx) !== false)
) {
node.scheduleAction("expand", dnd.autoExpandMS);
}
if(hitMode && dnd.dragOver){
// TODO: http://code.google.com/p/dynatree/source/detail?r=625
ctx.hitMode = hitMode;
res = dnd.dragOver(node, ctx);
}
accept = (res !== false && hitMode !== null);
if( dnd.smartRevert ) {
draggable.options.revert = !accept;
}
this._local._setDndStatus(otherNode, node, ui.helper, hitMode, accept);
break;
case "drop":
hitMode = ui.helper.data("hitMode");
if(hitMode && dnd.dragDrop){
ctx.hitMode = hitMode;
dnd.dragDrop(node, ctx);
}
break;
case "leave":
// Cancel pending expand request
node.scheduleAction("cancel");
ui.helper.data("enterResponse", null);
ui.helper.data("hitMode", null);
this._local._setDndStatus(otherNode, node, ui.helper, "out", undefined);
if(dnd.dragLeave){
dnd.dragLeave(node, ctx);
}
break;
case "stop":
$nodeTag.removeClass("fancytree-drag-source");
$(document).off(".fancytree-dnd");
if(dnd.dragStop){
dnd.dragStop(node, ctx);
}
break;
default:
$.error("Unsupported drag event: " + eventName);
}
return res;
},
_cancelDrag: function() {
var dd = $.ui.ddmanager.current;
if(dd){
dd.cancel();
}
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.dnd5.js
*
* Drag-and-drop support (native HTML5).
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
/*
#TODO
- glyph
Compatiblity when dragging between *separate* windows:
Drag from Chrome Edge FF IE11 Safari
To Chrome ok ok ok NO ?
Edge ok ok ok NO ?
FF ok ok ok NO ?
IE 11 ok ok ok ok ?
Safari ? ? ? ? ok
*/
;(function($, window, document, undefined) {
"use strict";
/* *****************************************************************************
* Private functions and variables
*/
var
classDragSource = "fancytree-drag-source",
classDragRemove = "fancytree-drag-remove",
classDropAccept = "fancytree-drop-accept",
classDropAfter = "fancytree-drop-after",
classDropBefore = "fancytree-drop-before",
classDropOver = "fancytree-drop-over",
classDropReject = "fancytree-drop-reject",
classDropTarget = "fancytree-drop-target",
nodeMimeType = "application/x-fancytree-node",
$dropMarker = null,
SOURCE_NODE = null,
DRAG_ENTER_RESPONSE = null,
LAST_HIT_MODE = null;
/* Convert number to string and prepend +/-; return empty string for 0.*/
function offsetString(n){
return n === 0 ? "" : (( n > 0 ) ? ("+" + n) : ("" + n));
}
/* Convert a dragEnter() or dragOver() response to a canonical form.
* Return false or plain object
* @param {string|object|boolean} r
* @return {object|false}
*/
function normalizeDragEnterResponse(r) {
var res;
if( !r ){
return false;
}
if ( $.isPlainObject(r) ) {
res = {
over: !!r.over,
before: !!r.before,
after: !!r.after
};
}else if ( $.isArray(r) ) {
res = {
over: ($.inArray("over", r) >= 0),
before: ($.inArray("before", r) >= 0),
after: ($.inArray("after", r) >= 0)
};
}else{
res = {
over: ((r === true) || (r === "over")),
before: ((r === true) || (r === "before")),
after: ((r === true) || (r === "after"))
};
}
if( Object.keys(res).length === 0 ) {
return false;
}
// if( Object.keys(res).length === 1 ) {
// res.unique = res[0];
// }
return res;
}
/* Implement auto scrolling when drag cursor is in top/bottom area of scroll parent. */
function autoScroll(tree, event) {
var spOfs, scrollTop, delta,
dndOpts = tree.options.dnd5,
sp = tree.$scrollParent[0],
sensitivity = dndOpts.scrollSensitivity,
speed = dndOpts.scrollSpeed,
scrolled = 0;
if ( sp !== document && sp.tagName !== "HTML" ) {
spOfs = tree.$scrollParent.offset();
scrollTop = sp.scrollTop;
if ( spOfs.top + sp.offsetHeight - event.pageY < sensitivity ) {
delta = (sp.scrollHeight - tree.$scrollParent.innerHeight() - scrollTop);
// console.log ("sp.offsetHeight: " + sp.offsetHeight
// + ", spOfs.top: " + spOfs.top
// + ", scrollTop: " + scrollTop
// + ", innerHeight: " + tree.$scrollParent.innerHeight()
// + ", scrollHeight: " + sp.scrollHeight
// + ", delta: " + delta
// );
if( delta > 0 ) {
sp.scrollTop = scrolled = scrollTop + speed;
}
} else if ( scrollTop > 0 && event.pageY - spOfs.top < sensitivity ) {
sp.scrollTop = scrolled = scrollTop - speed;
}
} else {
scrollTop = $(document).scrollTop();
if (scrollTop > 0 && event.pageY - scrollTop < sensitivity) {
scrolled = scrollTop - speed;
$(document).scrollTop(scrolled);
} else if ($(window).height() - (event.pageY - scrollTop) < sensitivity) {
scrolled = scrollTop + speed;
$(document).scrollTop(scrolled);
}
}
if( scrolled ) {
tree.debug("autoScroll: " + scrolled + "px");
}
return scrolled;
}
/* Handle dragover event (fired every x ms) and return hitMode. */
function handleDragOver(event, data) {
// Implement auto-scrolling
if ( data.options.dnd5.scroll ) {
autoScroll(data.tree, event);
}
// Bail out with previous response if we get an invalid dragover
if( !data.node ) {
data.tree.warn("Ignore dragover for non-node"); //, event, data);
return LAST_HIT_MODE;
}
var markerOffsetX, nodeOfs, relPosY, //res,
// eventHash = getEventHash(event),
hitMode = null,
tree = data.tree,
options = tree.options,
dndOpts = options.dnd5,
targetNode = data.node,
sourceNode = data.otherNode,
markerAt = "center",
// glyph = options.glyph || null,
// $source = sourceNode ? $(sourceNode.span) : null,
$target = $(targetNode.span),
$targetTitle = $target.find("span.fancytree-title");
if(DRAG_ENTER_RESPONSE === false){
tree.warn("Ignore dragover, since dragenter returned false"); //, event, data);
// $.error("assert failed: dragenter returned false");
return false;
} else if(typeof DRAG_ENTER_RESPONSE === "string") {
$.error("assert failed: dragenter returned string");
// Use hitMode from onEnter if provided.
// hitMode = DRAG_ENTER_RESPONSE;
} else {
// Calculate hitMode from relative cursor position.
nodeOfs = $target.offset();
relPosY = (event.pageY - nodeOfs.top) / $target.height();
if( DRAG_ENTER_RESPONSE.after && relPosY > 0.75 ){
hitMode = "after";
} else if(!DRAG_ENTER_RESPONSE.over && DRAG_ENTER_RESPONSE.after && relPosY > 0.5 ){
hitMode = "after";
} else if(DRAG_ENTER_RESPONSE.before && relPosY <= 0.25) {
hitMode = "before";
} else if(!DRAG_ENTER_RESPONSE.over && DRAG_ENTER_RESPONSE.before && relPosY <= 0.5) {
hitMode = "before";
} else if(DRAG_ENTER_RESPONSE.over) {
hitMode = "over";
}
// Prevent no-ops like 'before source node'
// TODO: these are no-ops when moving nodes, but not in copy mode
if( dndOpts.preventVoidMoves ){
if(targetNode === sourceNode){
targetNode.debug("drop over source node prevented");
hitMode = null;
}else if(hitMode === "before" && sourceNode && targetNode === sourceNode.getNextSibling()){
targetNode.debug("drop after source node prevented");
hitMode = null;
}else if(hitMode === "after" && sourceNode && targetNode === sourceNode.getPrevSibling()){
targetNode.debug("drop before source node prevented");
hitMode = null;
}else if(hitMode === "over" && sourceNode && sourceNode.parent === targetNode && sourceNode.isLastSibling() ){
targetNode.debug("drop last child over own parent prevented");
hitMode = null;
}
}
}
// Let callback modify the calculated hitMode
data.hitMode = hitMode;
if(hitMode && dndOpts.dragOver){
// TODO: http://code.google.com/p/dynatree/source/detail?r=625
dndOpts.dragOver(targetNode, data);
hitMode = data.hitMode;
}
// LAST_DROP_EFFECT = data.dataTransfer.dropEffect;
// LAST_EFFECT_ALLOWED = data.dataTransfer.effectAllowed;
LAST_HIT_MODE = hitMode;
//
if( hitMode === "after" || hitMode === "before" || hitMode === "over" ){
markerOffsetX = dndOpts.dropMarkerOffsetX || 0;
switch(hitMode){
case "before":
markerAt = "top";
markerOffsetX += (dndOpts.dropMarkerInsertOffsetX || 0);
break;
case "after":
markerAt = "bottom";
markerOffsetX += (dndOpts.dropMarkerInsertOffsetX || 0);
break;
}
$dropMarker
.toggleClass(classDropAfter, hitMode === "after")
.toggleClass(classDropOver, hitMode === "over")
.toggleClass(classDropBefore, hitMode === "before")
.show()
.position($.ui.fancytree.fixPositionOptions({
my: "left" + offsetString(markerOffsetX) + " center",
at: "left " + markerAt,
of: $targetTitle
}));
} else {
$dropMarker.hide();
// console.log("hide dropmarker")
}
// if( $source ){
// $source.toggleClass(classDragRemove, isMove);
// }
$(targetNode.span)
.toggleClass(classDropTarget, hitMode === "after" || hitMode === "before" || hitMode === "over")
.toggleClass(classDropAfter, hitMode === "after")
.toggleClass(classDropBefore, hitMode === "before")
.toggleClass(classDropAccept, hitMode === "over")
.toggleClass(classDropReject, hitMode === false);
return hitMode;
}
/* *****************************************************************************
*
*/
$.ui.fancytree.registerExtension({
name: "dnd5",
version: "2.22.3",
// Default options for this extension.
options: {
autoExpandMS: 1500, // Expand nodes after n milliseconds of hovering
setTextTypeJson: false, // Allow dragging of nodes to different IE windows
preventForeignNodes: false, // Prevent dropping nodes from different Fancytrees
preventNonNodes: false, // Prevent dropping items other than Fancytree nodes
preventRecursiveMoves: true, // Prevent dropping nodes on own descendants
preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
scroll: true, // Enable auto-scrolling while dragging
scrollSensitivity: 20, // Active top/bottom margin in pixel
scrollSpeed: 5, // Pixel per event
dropMarkerOffsetX: -24, // absolute position offset for .fancytree-drop-marker relatively to ..fancytree-title (icon/img near a node accepting drop)
dropMarkerInsertOffsetX: -16,// additional offset for drop-marker with hitMode = "before"/"after"
// Events (drag support)
dragStart: null, // Callback(sourceNode, data), return true, to enable dnd drag
dragDrag: $.noop, // Callback(sourceNode, data)
dragEnd: $.noop, // Callback(sourceNode, data)
// Events (drop support)
dragEnter: null, // Callback(targetNode, data), return true, to enable dnd drop
dragOver: $.noop, // Callback(targetNode, data)
dragExpand: $.noop, // Callback(targetNode, data), return false to prevent autoExpand
dragDrop: $.noop, // Callback(targetNode, data)
dragLeave: $.noop // Callback(targetNode, data)
},
treeInit: function(ctx){
var tree = ctx.tree,
opts = ctx.options,
dndOpts = opts.dnd5,
getNode = $.ui.fancytree.getNode;
if( $.inArray("dnd", opts.extensions) >= 0 ) {
$.error("Extensions 'dnd' and 'dnd5' are mutually exclusive.");
}
if( dndOpts.dragStop ) {
$.error("dragStop is not used by ext-dnd5. Use dragEnd instead.");
}
// Implement `opts.createNode` event to add the 'draggable' attribute
// #680: this must happen before calling super.treeInit()
if( dndOpts.dragStart ) {
$.ui.fancytree.overrideMethod(ctx.options, "createNode", function(event, data) {
// Default processing if any
this._super.apply(this, arguments);
data.node.span.draggable = true;
});
}
this._superApply(arguments);
this.$container.addClass("fancytree-ext-dnd5");
// Store the current scroll parent, which may be the tree
// container, any enclosing div, or the document
this.$scrollParent = this.$container.children(":first").scrollParent();
$dropMarker = $("#fancytree-drop-marker");
if( !$dropMarker.length ) {
$dropMarker = $("<div id='fancytree-drop-marker'></div>")
.hide()
.css({
"z-index": 1000,
// Drop marker should not steal dragenter/dragover events:
"pointer-events": "none"
}).prependTo("body");
// if( glyph ) {
// instData.$dropMarker
// .addClass(glyph.map.dropMarker);
// }
}
// Enable drag support if dragStart() is specified:
if( dndOpts.dragStart ) {
// Bind drag event handlers
tree.$container.on("dragstart drag dragend", function(event){
var json,
node = getNode(event),
dataTransfer = event.dataTransfer || event.originalEvent.dataTransfer,
isMove = dataTransfer.dropEffect === "move",
$source = node ? $(node.span) : null,
data = {
node: node,
tree: tree,
options: tree.options,
originalEvent: event,
dataTransfer: dataTransfer,
// dropEffect: undefined, // set by dragend
isCancelled: undefined // set by dragend
};
switch( event.type ) {
case "dragstart":
$(node.span).addClass(classDragSource);
// Store current source node in different formats
SOURCE_NODE = node;
// Set payload
// Note:
// Transfer data is only accessible on dragstart and drop!
// For all other events the formats and kinds in the drag
// data store list of items representing dragged data can be
// enumerated, but the data itself is unavailable and no new
// data can be added.
json = JSON.stringify(node.toDict());
try {
dataTransfer.setData(nodeMimeType, json);
dataTransfer.setData("text/html", $(node.span).html());
dataTransfer.setData("text/plain", node.title);
} catch(ex) {
// IE only accepts 'text' type
tree.warn("Could not set data (IE only accepts 'text') - " + ex);
}
// We always need to set the 'text' type if we want to drag
// Because IE 11 only accepts this single type.
// If we pass JSON here, IE can can access all node properties,
// even when the source lives in another window. (D'n'd inside
// the same window will always work.)
// The drawback is, that in this case ALL browsers will see
// the JSON representation as 'text', so dragging
// to a text field will insert the JSON string instead of
// the node title.
if( dndOpts.setTextTypeJson ) {
dataTransfer.setData("text", json);
} else {
dataTransfer.setData("text", node.title);
}
// Set the allowed and current drag mode (move, copy, or link)
dataTransfer.effectAllowed = "all"; // "copyMove"
// dataTransfer.dropEffect = "move";
// Set the title as drag image (otherwise it would contain the expander)
if( dataTransfer.setDragImage ) {
// IE 11 does not support this
dataTransfer.setDragImage($(node.span).find(".fancytree-title")[0], -10, -10);
// dataTransfer.setDragImage($(node.span)[0], -10, -10);
}
// Let user modify above settings
return dndOpts.dragStart(node, data) !== false;
case "drag":
// Called every few miliseconds
$source.toggleClass(classDragRemove, isMove);
dndOpts.dragDrag(node, data);
break;
case "dragend":
$(node.span).removeClass(classDragSource + " " + classDragRemove);
SOURCE_NODE = null;
DRAG_ENTER_RESPONSE = null;
// data.dropEffect = dataTransfer.dropEffect;
data.isCancelled = (dataTransfer.dropEffect === "none");
$dropMarker.hide();
dndOpts.dragEnd(node, data);
break;
}
});
}
// Enable drop support if dragEnter() is specified:
if( dndOpts.dragEnter ) {
// Bind drop event handlers
tree.$container.on("dragenter dragover dragleave drop", function(event){
var json, nodeData, r, res,
allowDrop = null,
node = getNode(event),
dataTransfer = event.dataTransfer || event.originalEvent.dataTransfer,
// glyph = opts.glyph || null,
data = {
node: node,
tree: tree,
options: tree.options,
hitMode: DRAG_ENTER_RESPONSE,
originalEvent: event,
dataTransfer: dataTransfer,
otherNode: SOURCE_NODE || null,
otherNodeData: null, // set by drop event
dropEffect: undefined, // set by drop event
isCancelled: undefined // set by drop event
};
switch( event.type ) {
case "dragenter":
// The dragenter event is fired when a dragged element or
// text selection enters a valid drop target.
if( !node ) {
// Sometimes we get dragenter for the container element
tree.debug("Ignore non-node " + event.type + ": " + event.target.tagName + "." + event.target.className);
DRAG_ENTER_RESPONSE = false;
break;
}
$(node.span)
.addClass(classDropOver)
.removeClass(classDropAccept + " " + classDropReject);
if( dndOpts.preventNonNodes && !nodeData ) {
node.debug("Reject dropping a non-node");
DRAG_ENTER_RESPONSE = false;
break;
} else if( dndOpts.preventForeignNodes && (!SOURCE_NODE || SOURCE_NODE.tree !== node.tree ) ) {
node.debug("Reject dropping a foreign node");
DRAG_ENTER_RESPONSE = false;
break;
}
// NOTE: dragenter is fired BEFORE the dragleave event
// of the previous element!
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=19041
setTimeout(function(){
// node.info("DELAYED " + event.type, event.target, DRAG_ENTER_RESPONSE);
// Auto-expand node (only when 'over' the node, not 'before', or 'after')
if( dndOpts.autoExpandMS &&
node.hasChildren() !== false && !node.expanded &&
(!dndOpts.dragExpand || dndOpts.dragExpand(node, data) !== false)
) {
node.scheduleAction("expand", dndOpts.autoExpandMS);
}
}, 0);
$dropMarker.show();
// Call dragEnter() to figure out if (and where) dropping is allowed
if( dndOpts.preventRecursiveMoves && node.isDescendantOf(data.otherNode) ){
res = false;
}else{
r = dndOpts.dragEnter(node, data);
res = normalizeDragEnterResponse(r);
}
DRAG_ENTER_RESPONSE = res;
allowDrop = res && ( res.over || res.before || res.after );
break;
case "dragover":
// The dragover event is fired when an element or text
// selection is being dragged over a valid drop target
// (every few hundred milliseconds).
LAST_HIT_MODE = handleDragOver(event, data);
allowDrop = !!LAST_HIT_MODE;
break;
case "dragleave":
// NOTE: dragleave is fired AFTER the dragenter event of the
// FOLLOWING element.
if( !node ) {
tree.debug("Ignore non-node " + event.type + ": " + event.target.tagName + "." + event.target.className);
break;
}
if( !$(node.span).hasClass(classDropOver) ) {
node.debug("Ignore dragleave (multi)"); //, event.currentTarget);
break;
}
$(node.span).removeClass(classDropOver + " " + classDropAccept + " " + classDropReject);
node.scheduleAction("cancel");
dndOpts.dragLeave(node, data);
$dropMarker.hide();
break;
case "drop":
// Data is only readable in the (dragenter and) drop event:
if( $.inArray(nodeMimeType, dataTransfer.types) >= 0 ) {
nodeData = dataTransfer.getData(nodeMimeType);
tree.info(event.type + ": getData('application/x-fancytree-node'): '" + nodeData + "'");
}
if( !nodeData ) {
// 1. Source is not a Fancytree node, or
// 2. If the FT mime type was set, but returns '', this
// is probably IE 11 (which only supports 'text')
nodeData = dataTransfer.getData("text");
tree.info(event.type + ": getData('text'): '" + nodeData + "'");
}
if( nodeData ) {
try {
// 'text' type may contain JSON if IE is involved
// and setTextTypeJson option was set
json = JSON.parse(nodeData);
if( json.title !== undefined ) {
data.otherNodeData = json;
}
} catch(ex) {
// assume 'text' type contains plain text, so `otherNodeData`
// should not be set
}
}
tree.debug(event.type + ": nodeData: '" + nodeData + "', otherNodeData: ", data.otherNodeData);
$(node.span).removeClass(classDropOver + " " + classDropAccept + " " + classDropReject);
$dropMarker.hide();
data.hitMode = LAST_HIT_MODE;
data.dropEffect = dataTransfer.dropEffect;
data.isCancelled = data.dropEffect === "none";
// Let user implement the actual drop operation
dndOpts.dragDrop(node, data);
// Prevent browser's default drop handling
event.preventDefault();
break;
}
// Dnd API madness: we must PREVENT default handling to enable dropping
if( allowDrop ) {
event.preventDefault();
return false;
}
});
}
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.edit.js
*
* Make node titles editable.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
var isMac = /Mac/.test(navigator.platform),
escapeHtml = $.ui.fancytree.escapeHtml,
unescapeHtml = $.ui.fancytree.unescapeHtml;
/**
* [ext-edit] Start inline editing of current node title.
*
* @alias FancytreeNode#editStart
* @requires Fancytree
*/
$.ui.fancytree._FancytreeNodeClass.prototype.editStart = function(){
var $input,
node = this,
tree = this.tree,
local = tree.ext.edit,
instOpts = tree.options.edit,
$title = $(".fancytree-title", node.span),
eventData = {
node: node,
tree: tree,
options: tree.options,
isNew: $(node[tree.statusClassPropName]).hasClass("fancytree-edit-new"),
orgTitle: node.title,
input: null,
dirty: false
};
// beforeEdit may want to modify the title before editing
if( instOpts.beforeEdit.call(node, {type: "beforeEdit"}, eventData) === false ) {
return false;
}
$.ui.fancytree.assert(!local.currentNode, "recursive edit");
local.currentNode = this;
local.eventData = eventData;
// Disable standard Fancytree mouse- and key handling
tree.widget._unbind();
// #116: ext-dnd prevents the blur event, so we have to catch outer clicks
$(document).on("mousedown.fancytree-edit", function(event){
if( ! $(event.target).hasClass("fancytree-edit-input") ){
node.editEnd(true, event);
}
});
// Replace node with <input>
$input = $("<input />", {
"class": "fancytree-edit-input",
type: "text",
value: tree.options.escapeTitles ? eventData.orgTitle : unescapeHtml(eventData.orgTitle)
});
local.eventData.input = $input;
if ( instOpts.adjustWidthOfs != null ) {
$input.width($title.width() + instOpts.adjustWidthOfs);
}
if ( instOpts.inputCss != null ) {
$input.css(instOpts.inputCss);
}
$title.html($input);
// Focus <input> and bind keyboard handler
$input
.focus()
.change(function(event){
$input.addClass("fancytree-edit-dirty");
}).keydown(function(event){
switch( event.which ) {
case $.ui.keyCode.ESCAPE:
node.editEnd(false, event);
break;
case $.ui.keyCode.ENTER:
node.editEnd(true, event);
return false; // so we don't start editmode on Mac
}
event.stopPropagation();
}).blur(function(event){
return node.editEnd(true, event);
});
instOpts.edit.call(node, {type: "edit"}, eventData);
};
/**
* [ext-edit] Stop inline editing.
* @param {Boolean} [applyChanges=false] false: cancel edit, true: save (if modified)
* @alias FancytreeNode#editEnd
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function(applyChanges, _event){
var newVal,
node = this,
tree = this.tree,
local = tree.ext.edit,
eventData = local.eventData,
instOpts = tree.options.edit,
$title = $(".fancytree-title", node.span),
$input = $title.find("input.fancytree-edit-input");
if( instOpts.trim ) {
$input.val($.trim($input.val()));
}
newVal = $input.val();
eventData.dirty = ( newVal !== node.title );
eventData.originalEvent = _event;
// Find out, if saving is required
if( applyChanges === false ) {
// If true/false was passed, honor this (except in rename mode, if unchanged)
eventData.save = false;
} else if( eventData.isNew ) {
// In create mode, we save everyting, except for empty text
eventData.save = (newVal !== "");
} else {
// In rename mode, we save everyting, except for empty or unchanged text
eventData.save = eventData.dirty && (newVal !== "");
}
// Allow to break (keep editor open), modify input, or re-define data.save
if( instOpts.beforeClose.call(node, {type: "beforeClose"}, eventData) === false){
return false;
}
if( eventData.save && instOpts.save.call(node, {type: "save"}, eventData) === false){
return false;
}
$input
.removeClass("fancytree-edit-dirty")
.off();
// Unbind outer-click handler
$(document).off(".fancytree-edit");
if( eventData.save ) {
// # 171: escape user input (not required if global escaping is on)
node.setTitle( tree.options.escapeTitles ? newVal : escapeHtml(newVal) );
node.setFocus();
}else{
if( eventData.isNew ) {
node.remove();
node = eventData.node = null;
local.relatedNode.setFocus();
} else {
node.renderTitle();
node.setFocus();
}
}
local.eventData = null;
local.currentNode = null;
local.relatedNode = null;
// Re-enable mouse and keyboard handling
tree.widget._bind();
// Set keyboard focus, even if setFocus() claims 'nothing to do'
$(tree.$container).focus();
eventData.input = null;
instOpts.close.call(node, {type: "close"}, eventData);
return true;
};
/**
* [ext-edit] Create a new child or sibling node and start edit mode.
*
* @param {String} [mode='child'] 'before', 'after', or 'child'
* @param {Object} [init] NodeData (or simple title string)
* @alias FancytreeNode#editCreateNode
* @requires jquery.fancytree.edit.js
* @since 2.4
*/
$.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function(mode, init){
var newNode,
tree = this.tree,
self = this;
mode = mode || "child";
if( init == null ) {
init = { title: "" };
} else if( typeof init === "string" ) {
init = { title: init };
} else {
$.ui.fancytree.assert($.isPlainObject(init));
}
// Make sure node is expanded (and loaded) in 'child' mode
if( mode === "child" && !this.isExpanded() && this.hasChildren() !== false ) {
this.setExpanded().done(function(){
self.editCreateNode(mode, init);
});
return;
}
newNode = this.addNode(init, mode);
// #644: Don't filter new nodes.
newNode.match = true;
$(newNode[tree.statusClassPropName])
.removeClass("fancytree-hide")
.addClass("fancytree-match");
newNode.makeVisible(/*{noAnimation: true}*/).done(function(){
$(newNode[tree.statusClassPropName]).addClass("fancytree-edit-new");
self.tree.ext.edit.relatedNode = self;
newNode.editStart();
});
};
/**
* [ext-edit] Check if any node in this tree in edit mode.
*
* @returns {FancytreeNode | null}
* @alias Fancytree#isEditing
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeClass.prototype.isEditing = function(){
return this.ext.edit ? this.ext.edit.currentNode : null;
};
/**
* [ext-edit] Check if this node is in edit mode.
* @returns {Boolean} true if node is currently beeing edited
* @alias FancytreeNode#isEditing
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function(){
return this.tree.ext.edit ? this.tree.ext.edit.currentNode === this : false;
};
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "edit",
version: "2.22.3",
// Default options for this extension.
options: {
adjustWidthOfs: 4, // null: don't adjust input size to content
allowEmpty: false, // Prevent empty input
inputCss: {minWidth: "3em"},
// triggerCancel: ["esc", "tab", "click"],
// triggerStart: ["f2", "dblclick", "shift+click", "mac+enter"],
triggerStart: ["f2", "shift+click", "mac+enter"],
trim: true, // Trim whitespace before save
// Events:
beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available)
beforeEdit: $.noop, // Return false to prevent edit mode
close: $.noop, // Editor was removed
edit: $.noop, // Editor was opened (available as data.input)
// keypress: $.noop, // Not yet implemented
save: $.noop // Save data.input.val() or return false to keep editor open
},
// Local attributes
currentNode: null,
treeInit: function(ctx){
this._superApply(arguments);
this.$container.addClass("fancytree-ext-edit");
},
nodeClick: function(ctx) {
if( $.inArray("shift+click", ctx.options.edit.triggerStart) >= 0 ){
if( ctx.originalEvent.shiftKey ){
ctx.node.editStart();
return false;
}
}
return this._superApply(arguments);
},
nodeDblclick: function(ctx) {
if( $.inArray("dblclick", ctx.options.edit.triggerStart) >= 0 ){
ctx.node.editStart();
return false;
}
return this._superApply(arguments);
},
nodeKeydown: function(ctx) {
switch( ctx.originalEvent.which ) {
case 113: // [F2]
if( $.inArray("f2", ctx.options.edit.triggerStart) >= 0 ){
ctx.node.editStart();
return false;
}
break;
case $.ui.keyCode.ENTER:
if( $.inArray("mac+enter", ctx.options.edit.triggerStart) >= 0 && isMac ){
ctx.node.editStart();
return false;
}
break;
}
return this._superApply(arguments);
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.filter.js
*
* Remove or highlight tree nodes, based on a filter.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
var KeyNoData = "__not_found__",
escapeHtml = $.ui.fancytree.escapeHtml;
function _escapeRegex(str){
/*jshint regexdash:true */
return (str + "").replace(/([.?*+\^\$\[\]\\(){}|-])/g, "\\$1");
}
function extractHtmlText(s){
if( s.indexOf(">") >= 0 ) {
return $("<div/>").html(s).text();
}
return s;
}
$.ui.fancytree._FancytreeClass.prototype._applyFilterImpl = function(filter, branchMode, _opts){
var match, statusNode, re, reHighlight,
count = 0,
treeOpts = this.options,
escapeTitles = treeOpts.escapeTitles,
prevAutoCollapse = treeOpts.autoCollapse,
opts = $.extend({}, treeOpts.filter, _opts),
hideMode = opts.mode === "hide",
leavesOnly = !!opts.leavesOnly && !branchMode;
// Default to 'match title substring (not case sensitive)'
if(typeof filter === "string"){
// console.log("rex", filter.split('').join('\\w*').replace(/\W/, ""))
if( opts.fuzzy ) {
// See https://codereview.stackexchange.com/questions/23899/faster-javascript-fuzzy-string-matching-function/23905#23905
// and http://www.quora.com/How-is-the-fuzzy-search-algorithm-in-Sublime-Text-designed
// and http://www.dustindiaz.com/autocomplete-fuzzy-matching
match = filter.split("").reduce(function(a, b) {
return a + "[^" + b + "]*" + b;
});
} else {
match = _escapeRegex(filter); // make sure a '.' is treated literally
}
re = new RegExp(".*" + match + ".*", "i");
reHighlight = new RegExp(_escapeRegex(filter), "gi");
filter = function(node){
var display,
text = escapeTitles ? node.title : extractHtmlText(node.title),
res = !!re.test(text);
if( res && opts.highlight ) {
display = escapeTitles ? escapeHtml(node.title) : text;
node.titleWithHighlight = display.replace(reHighlight, function(s){
return "<mark>" + s + "</mark>";
});
// node.debug("filter", escapeTitles, text, node.titleWithHighlight);
}
return res;
};
}
this.enableFilter = true;
this.lastFilterArgs = arguments;
this.$div.addClass("fancytree-ext-filter");
if( hideMode ){
this.$div.addClass("fancytree-ext-filter-hide");
} else {
this.$div.addClass("fancytree-ext-filter-dimm");
}
this.$div.toggleClass("fancytree-ext-filter-hide-expanders", !!opts.hideExpanders);
// Reset current filter
this.visit(function(node){
delete node.match;
delete node.titleWithHighlight;
node.subMatchCount = 0;
});
statusNode = this.getRootNode()._findDirectChild(KeyNoData);
if( statusNode ) {
statusNode.remove();
}
// Adjust node.hide, .match, and .subMatchCount properties
treeOpts.autoCollapse = false; // #528
this.visit(function(node){
if ( leavesOnly && node.children != null ) {
return;
}
var res = filter(node),
matchedByBranch = false;
if( res === "skip" ) {
node.visit(function(c){
c.match = false;
}, true);
return "skip";
}
if( !res && (branchMode || res === "branch") && node.parent.match ) {
res = true;
matchedByBranch = true;
}
if( res ) {
count++;
node.match = true;
node.visitParents(function(p){
p.subMatchCount += 1;
// Expand match (unless this is no real match, but only a node in a matched branch)
if( opts.autoExpand && !matchedByBranch && !p.expanded ) {
p.setExpanded(true, {noAnimation: true, noEvents: true, scrollIntoView: false});
p._filterAutoExpanded = true;
}
});
}
});
treeOpts.autoCollapse = prevAutoCollapse;
if( count === 0 && opts.nodata && hideMode ) {
statusNode = opts.nodata;
if( $.isFunction(statusNode) ) {
statusNode = statusNode();
}
if( statusNode === true ) {
statusNode = {};
} else if( typeof statusNode === "string" ) {
statusNode = { title: statusNode };
}
statusNode = $.extend({
statusNodeType: "nodata",
key: KeyNoData,
title: this.options.strings.noData
}, statusNode);
this.getRootNode().addNode(statusNode).match = true;
}
// Redraw whole tree
this.render();
return count;
};
/**
* [ext-filter] Dimm or hide nodes.
*
* @param {function | string} filter
* @param {boolean} [opts={autoExpand: false, leavesOnly: false}]
* @returns {integer} count
* @alias Fancytree#filterNodes
* @requires jquery.fancytree.filter.js
*/
$.ui.fancytree._FancytreeClass.prototype.filterNodes = function(filter, opts) {
if( typeof opts === "boolean" ) {
opts = { leavesOnly: opts };
this.warn("Fancytree.filterNodes() leavesOnly option is deprecated since 2.9.0 / 2015-04-19. Use opts.leavesOnly instead.");
}
return this._applyFilterImpl(filter, false, opts);
};
/**
* @deprecated
*/
$.ui.fancytree._FancytreeClass.prototype.applyFilter = function(filter){
this.warn("Fancytree.applyFilter() is deprecated since 2.1.0 / 2014-05-29. Use .filterNodes() instead.");
return this.filterNodes.apply(this, arguments);
};
/**
* [ext-filter] Dimm or hide whole branches.
*
* @param {function | string} filter
* @param {boolean} [opts={autoExpand: false}]
* @returns {integer} count
* @alias Fancytree#filterBranches
* @requires jquery.fancytree.filter.js
*/
$.ui.fancytree._FancytreeClass.prototype.filterBranches = function(filter, opts){
return this._applyFilterImpl(filter, true, opts);
};
/**
* [ext-filter] Reset the filter.
*
* @alias Fancytree#clearFilter
* @requires jquery.fancytree.filter.js
*/
$.ui.fancytree._FancytreeClass.prototype.clearFilter = function(){
var $title,
statusNode = this.getRootNode()._findDirectChild(KeyNoData),
escapeTitles = this.options.escapeTitles,
enhanceTitle = this.options.enhanceTitle;
if( statusNode ) {
statusNode.remove();
}
this.visit(function(node){
if( node.match && node.span ) { // #491, #601
$title = $(node.span).find(">span.fancytree-title");
if( escapeTitles ) {
$title.text(node.title);
} else {
$title.html(node.title);
}
if( enhanceTitle ) {
enhanceTitle({type: "enhanceTitle"}, {node: node, $title: $title});
}
}
delete node.match;
delete node.subMatchCount;
delete node.titleWithHighlight;
if ( node.$subMatchBadge ) {
node.$subMatchBadge.remove();
delete node.$subMatchBadge;
}
if( node._filterAutoExpanded && node.expanded ) {
node.setExpanded(false, {noAnimation: true, noEvents: true, scrollIntoView: false});
}
delete node._filterAutoExpanded;
});
this.enableFilter = false;
this.lastFilterArgs = null;
this.$div.removeClass("fancytree-ext-filter fancytree-ext-filter-dimm fancytree-ext-filter-hide");
this.render();
};
/**
* [ext-filter] Return true if a filter is currently applied.
*
* @returns {Boolean}
* @alias Fancytree#isFilterActive
* @requires jquery.fancytree.filter.js
* @since 2.13
*/
$.ui.fancytree._FancytreeClass.prototype.isFilterActive = function(){
return !!this.enableFilter;
};
/**
* [ext-filter] Return true if this node is matched by current filter (or no filter is active).
*
* @returns {Boolean}
* @alias FancytreeNode#isMatched
* @requires jquery.fancytree.filter.js
* @since 2.13
*/
$.ui.fancytree._FancytreeNodeClass.prototype.isMatched = function(){
return !(this.tree.enableFilter && !this.match);
};
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "filter",
version: "2.22.3",
// Default options for this extension.
options: {
autoApply: true, // Re-apply last filter if lazy data is loaded
autoExpand: false, // Expand all branches that contain matches while filtered
counter: true, // Show a badge with number of matching child nodes near parent icons
fuzzy: false, // Match single characters in order, e.g. 'fb' will match 'FooBar'
hideExpandedCounter: true, // Hide counter badge if parent is expanded
hideExpanders: false, // Hide expanders if all child nodes are hidden by filter
highlight: true, // Highlight matches by wrapping inside <mark> tags
leavesOnly: false, // Match end nodes only
nodata: true, // Display a 'no data' status node if result is empty
mode: "dimm" // Grayout unmatched nodes (pass "hide" to remove unmatched node instead)
},
nodeLoadChildren: function(ctx, source) {
return this._superApply(arguments).done(function() {
if( ctx.tree.enableFilter && ctx.tree.lastFilterArgs && ctx.options.filter.autoApply ) {
ctx.tree._applyFilterImpl.apply(ctx.tree, ctx.tree.lastFilterArgs);
}
});
},
nodeSetExpanded: function(ctx, flag, callOpts) {
delete ctx.node._filterAutoExpanded;
// Make sure counter badge is displayed again, when node is beeing collapsed
if( !flag && ctx.options.filter.hideExpandedCounter && ctx.node.$subMatchBadge ) {
ctx.node.$subMatchBadge.show();
}
return this._superApply(arguments);
},
nodeRenderStatus: function(ctx) {
// Set classes for current status
var res,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options.filter,
$title = $(node.span).find("span.fancytree-title"),
$span = $(node[tree.statusClassPropName]),
enhanceTitle = ctx.options.enhanceTitle,
escapeTitles = ctx.options.escapeTitles;
res = this._super(ctx);
// nothing to do, if node was not yet rendered
if( !$span.length || !tree.enableFilter ) {
return res;
}
$span
.toggleClass("fancytree-match", !!node.match)
.toggleClass("fancytree-submatch", !!node.subMatchCount)
.toggleClass("fancytree-hide", !(node.match || node.subMatchCount));
// Add/update counter badge
if( opts.counter && node.subMatchCount && (!node.isExpanded() || !opts.hideExpandedCounter) ) {
if( !node.$subMatchBadge ) {
node.$subMatchBadge = $("<span class='fancytree-childcounter'/>");
$("span.fancytree-icon, span.fancytree-custom-icon", node.span).append(node.$subMatchBadge);
}
node.$subMatchBadge.show().text(node.subMatchCount);
} else if ( node.$subMatchBadge ) {
node.$subMatchBadge.hide();
}
// node.debug("nodeRenderStatus", node.titleWithHighlight, node.title)
// #601: also chek for $title.length, because we don't need to render
// if node.span is null (i.e. not rendered)
if( node.span && (!node.isEditing || !node.isEditing.call(node)) ) {
if( node.titleWithHighlight ) {
$title.html(node.titleWithHighlight);
} else if ( escapeTitles ) {
$title.text(node.title);
} else {
$title.html(node.title);
}
if( enhanceTitle ) {
enhanceTitle({type: "enhanceTitle"}, {node: node, $title: $title});
}
}
return res;
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.glyph.js
*
* Use glyph fonts as instead of icon sprites.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
;(function($, window, document, undefined) {
"use strict";
/* *****************************************************************************
* Private functions and variables
*/
function _getIcon(opts, type){
return opts.map[type];
}
$.ui.fancytree.registerExtension({
name: "glyph",
version: "2.22.3",
// Default options for this extension.
options: {
map: {
// Samples from Font Awesome 3.2
// http://fortawesome.github.io/Font-Awesome/3.2.1/icons/
// See here for alternatives:
// http://fortawesome.github.io/Font-Awesome/icons/
// http://getbootstrap.com/components/
checkbox: "icon-check-empty",
checkboxSelected: "icon-check",
checkboxUnknown: "icon-check icon-muted",
error: "icon-exclamation-sign",
expanderClosed: "icon-caret-right",
expanderLazy: "icon-angle-right",
expanderOpen: "icon-caret-down",
nodata: "icon-meh",
noExpander: "",
dragHelper: "icon-caret-right",
dropMarker: "icon-caret-right",
// Default node icons.
// (Use tree.options.icon callback to define custom icons
// based on node data)
doc: "icon-file-alt",
docOpen: "icon-file-alt",
loading: "icon-refresh icon-spin",
folder: "icon-folder-close-alt",
folderOpen: "icon-folder-open-alt"
}
},
treeInit: function(ctx){
var tree = ctx.tree;
this._superApply(arguments);
tree.$container.addClass("fancytree-ext-glyph");
},
nodeRenderStatus: function(ctx) {
var icon, res, span,
node = ctx.node,
$span = $(node.span),
opts = ctx.options.glyph,
map = opts.map;
res = this._super(ctx);
if( node.isRoot() ){
return res;
}
span = $span.children("span.fancytree-expander").get(0);
if( span ){
// if( node.isLoading() ){
// icon = "loading";
if( node.expanded && node.hasChildren() ){
icon = "expanderOpen";
}else if( node.isUndefined() ){
icon = "expanderLazy";
}else if( node.hasChildren() ){
icon = "expanderClosed";
}else{
icon = "noExpander";
}
span.className = "fancytree-expander " + map[icon];
}
if( node.tr ){
span = $("td", node.tr).find("span.fancytree-checkbox").get(0);
}else{
span = $span.children("span.fancytree-checkbox").get(0);
}
if( span ){
icon = node.selected ? "checkboxSelected" : (node.partsel ? "checkboxUnknown" : "checkbox");
span.className = "fancytree-checkbox " + map[icon];
}
// Standard icon (note that this does not match .fancytree-custom-icon,
// that might be set by opts.icon callbacks)
span = $span.children("span.fancytree-icon").get(0);
if( span ){
if( node.statusNodeType ){
icon = _getIcon(opts, node.statusNodeType); // loading, error
}else if( node.folder ){
icon = node.expanded && node.hasChildren() ? _getIcon(opts, "folderOpen") : _getIcon(opts, "folder");
}else{
icon = node.expanded ? _getIcon(opts, "docOpen") : _getIcon(opts, "doc");
}
span.className = "fancytree-icon " + icon;
}
return res;
},
nodeSetStatus: function(ctx, status, message, details) {
var res, span,
opts = ctx.options.glyph,
node = ctx.node;
res = this._superApply(arguments);
if( status === "error" || status === "loading" || status === "nodata" ){
if(node.parent){
span = $("span.fancytree-expander", node.span).get(0);
if( span ) {
span.className = "fancytree-expander " + _getIcon(opts, status);
}
}else{ //
span = $(".fancytree-statusnode-" + status, node[this.nodeContainerAttrName])
.find("span.fancytree-icon").get(0);
if( span ) {
span.className = "fancytree-icon " + _getIcon(opts, status);
}
}
}
return res;
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.gridnav.js
*
* Support keyboard navigation for trees with embedded input controls.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
// Allow these navigation keys even when input controls are focused
var KC = $.ui.keyCode,
// which keys are *not* handled by embedded control, but passed to tree
// navigation handler:
NAV_KEYS = {
"text": [KC.UP, KC.DOWN],
"checkbox": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"link": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"radiobutton": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"select-one": [KC.LEFT, KC.RIGHT],
"select-multiple": [KC.LEFT, KC.RIGHT]
};
/* Calculate TD column index (considering colspans).*/
function getColIdx($tr, $td) {
var colspan,
td = $td.get(0),
idx = 0;
$tr.children().each(function () {
if( this === td ) {
return false;
}
colspan = $(this).prop("colspan");
idx += colspan ? colspan : 1;
});
return idx;
}
/* Find TD at given column index (considering colspans).*/
function findTdAtColIdx($tr, colIdx) {
var colspan,
res = null,
idx = 0;
$tr.children().each(function () {
if( idx >= colIdx ) {
res = $(this);
return false;
}
colspan = $(this).prop("colspan");
idx += colspan ? colspan : 1;
});
return res;
}
/* Find adjacent cell for a given direction. Skip empty cells and consider merged cells */
function findNeighbourTd($target, keyCode){
var $tr, colIdx,
$td = $target.closest("td"),
$tdNext = null;
switch( keyCode ){
case KC.LEFT:
$tdNext = $td.prev();
break;
case KC.RIGHT:
$tdNext = $td.next();
break;
case KC.UP:
case KC.DOWN:
$tr = $td.parent();
colIdx = getColIdx($tr, $td);
while( true ) {
$tr = (keyCode === KC.UP) ? $tr.prev() : $tr.next();
if( !$tr.length ) {
break;
}
// Skip hidden rows
if( $tr.is(":hidden") ) {
continue;
}
// Find adjacent cell in the same column
$tdNext = findTdAtColIdx($tr, colIdx);
// Skip cells that don't conatain a focusable element
if( $tdNext && $tdNext.find(":input,a").length ) {
break;
}
}
break;
}
return $tdNext;
}
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "gridnav",
version: "2.22.3",
// Default options for this extension.
options: {
autofocusInput: false, // Focus first embedded input if node gets activated
handleCursorKeys: true // Allow UP/DOWN in inputs to move to prev/next node
},
treeInit: function(ctx){
// gridnav requires the table extension to be loaded before itself
this._requireExtension("table", true, true);
this._superApply(arguments);
this.$container.addClass("fancytree-ext-gridnav");
// Activate node if embedded input gets focus (due to a click)
this.$container.on("focusin", function(event){
var ctx2,
node = $.ui.fancytree.getNode(event.target);
if( node && !node.isActive() ){
// Call node.setActive(), but also pass the event
ctx2 = ctx.tree._makeHookContext(node, event);
ctx.tree._callHook("nodeSetActive", ctx2, true);
}
});
},
nodeSetActive: function(ctx, flag, callOpts) {
var $outer,
opts = ctx.options.gridnav,
node = ctx.node,
event = ctx.originalEvent || {},
triggeredByInput = $(event.target).is(":input");
flag = (flag !== false);
this._superApply(arguments);
if( flag ){
if( ctx.options.titlesTabbable ){
if( !triggeredByInput ) {
$(node.span).find("span.fancytree-title").focus();
node.setFocus();
}
// If one node is tabbable, the container no longer needs to be
ctx.tree.$container.attr("tabindex", "-1");
// ctx.tree.$container.removeAttr("tabindex");
} else if( opts.autofocusInput && !triggeredByInput ){
// Set focus to input sub input (if node was clicked, but not
// when TAB was pressed )
$outer = $(node.tr || node.span);
$outer.find(":input:enabled:first").focus();
}
}
},
nodeKeydown: function(ctx) {
var inputType, handleKeys, $td,
opts = ctx.options.gridnav,
event = ctx.originalEvent,
$target = $(event.target);
if( $target.is(":input:enabled") ) {
inputType = $target.prop("type");
} else if( $target.is("a") ) {
inputType = "link";
}
// ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType);
if( inputType && opts.handleCursorKeys ){
handleKeys = NAV_KEYS[inputType];
if( handleKeys && $.inArray(event.which, handleKeys) >= 0 ){
$td = findNeighbourTd($target, event.which);
if( $td && $td.length ) {
// ctx.node.debug("ignore keydown in input", event.which, handleKeys);
$td.find(":input:enabled,a").focus();
// Prevent Fancytree default navigation
return false;
}
}
return true;
}
// ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType);
return this._superApply(arguments);
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.persist.js
*
* Persist tree status in cookiesRemove or highlight tree nodes, based on a filter.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* @depends: js-cookie or jquery-cookie
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
;(function($, window, document, undefined) {
"use strict";
/* global Cookies:false */
/*******************************************************************************
* Private functions and variables
*/
var cookieGetter, cookieRemover, cookieSetter,
_assert = $.ui.fancytree.assert,
ACTIVE = "active",
EXPANDED = "expanded",
FOCUS = "focus",
SELECTED = "selected";
if( typeof Cookies === "function" ) {
// Assume https://github.com/js-cookie/js-cookie
cookieSetter = Cookies.set;
cookieGetter = Cookies.get;
cookieRemover = Cookies.remove;
} else {
// Fall back to https://github.com/carhartl/jquery-cookie
cookieSetter = cookieGetter = $.cookie;
cookieRemover = $.removeCookie;
}
/* Recursively load lazy nodes
* @param {string} mode 'load', 'expand', false
*/
function _loadLazyNodes(tree, local, keyList, mode, dfd) {
var i, key, l, node,
foundOne = false,
expandOpts = tree.options.persist.expandOpts,
deferredList = [],
missingKeyList = [];
keyList = keyList || [];
dfd = dfd || $.Deferred();
for( i=0, l=keyList.length; i<l; i++ ) {
key = keyList[i];
node = tree.getNodeByKey(key);
if( node ) {
if( mode && node.isUndefined() ) {
foundOne = true;
tree.debug("_loadLazyNodes: " + node + " is lazy: loading...");
if( mode === "expand" ) {
deferredList.push(node.setExpanded(true, expandOpts));
} else {
deferredList.push(node.load());
}
} else {
tree.debug("_loadLazyNodes: " + node + " already loaded.");
node.setExpanded(true, expandOpts);
}
} else {
missingKeyList.push(key);
tree.debug("_loadLazyNodes: " + node + " was not yet found.");
}
}
$.when.apply($, deferredList).always(function(){
// All lazy-expands have finished
if( foundOne && missingKeyList.length > 0 ) {
// If we read new nodes from server, try to resolve yet-missing keys
_loadLazyNodes(tree, local, missingKeyList, mode, dfd);
} else {
if( missingKeyList.length ) {
tree.warn("_loadLazyNodes: could not load those keys: ", missingKeyList);
for( i=0, l=missingKeyList.length; i<l; i++ ) {
key = keyList[i];
local._appendKey(EXPANDED, keyList[i], false);
}
}
dfd.resolve();
}
});
return dfd;
}
/**
* [ext-persist] Remove persistence cookies of the given type(s).
* Called like
* $("#tree").fancytree("getTree").clearCookies("active expanded focus selected");
*
* @alias Fancytree#clearCookies
* @requires jquery.fancytree.persist.js
*/
$.ui.fancytree._FancytreeClass.prototype.clearCookies = function(types){
var local = this.ext.persist,
prefix = local.cookiePrefix;
types = types || "active expanded focus selected";
if(types.indexOf(ACTIVE) >= 0){
local._data(prefix + ACTIVE, null);
}
if(types.indexOf(EXPANDED) >= 0){
local._data(prefix + EXPANDED, null);
}
if(types.indexOf(FOCUS) >= 0){
local._data(prefix + FOCUS, null);
}
if(types.indexOf(SELECTED) >= 0){
local._data(prefix + SELECTED, null);
}
};
/**
* [ext-persist] Return persistence information from cookies
*
* Called like
* $("#tree").fancytree("getTree").getPersistData();
*
* @alias Fancytree#getPersistData
* @requires jquery.fancytree.persist.js
*/
$.ui.fancytree._FancytreeClass.prototype.getPersistData = function(){
var local = this.ext.persist,
prefix = local.cookiePrefix,
delim = local.cookieDelimiter,
res = {};
res[ACTIVE] = local._data(prefix + ACTIVE);
res[EXPANDED] = (local._data(prefix + EXPANDED) || "").split(delim);
res[SELECTED] = (local._data(prefix + SELECTED) || "").split(delim);
res[FOCUS] = local._data(prefix + FOCUS);
return res;
};
/* *****************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "persist",
version: "2.22.3",
// Default options for this extension.
options: {
cookieDelimiter: "~",
cookiePrefix: undefined, // 'fancytree-<treeId>-' by default
cookie: {
raw: false,
expires: "",
path: "",
domain: "",
secure: false
},
expandLazy: false, // true: recursively expand and load lazy nodes
expandOpts: undefined, // optional `opts` argument passed to setExpanded()
fireActivate: true, // false: suppress `activate` event after active node was restored
overrideSource: true, // true: cookie takes precedence over `source` data attributes.
store: "auto", // 'cookie': force cookie, 'local': force localStore, 'session': force sessionStore
types: "active expanded focus selected"
},
/* Generic read/write string data to cookie, sessionStorage or localStorage. */
_data: function(key, value){
var ls = this._local.localStorage; // null, sessionStorage, or localStorage
if( value === undefined ) {
return ls ? ls.getItem(key) : cookieGetter(key);
} else if ( value === null ) {
if( ls ) {
ls.removeItem(key);
} else {
cookieRemover(key);
}
} else {
if( ls ) {
ls.setItem(key, value);
} else {
cookieSetter(key, value, this.options.persist.cookie);
}
}
},
/* Append `key` to a cookie. */
_appendKey: function(type, key, flag){
key = "" + key; // #90
var local = this._local,
instOpts = this.options.persist,
delim = instOpts.cookieDelimiter,
cookieName = local.cookiePrefix + type,
data = local._data(cookieName),
keyList = data ? data.split(delim) : [],
idx = $.inArray(key, keyList);
// Remove, even if we add a key, so the key is always the last entry
if(idx >= 0){
keyList.splice(idx, 1);
}
// Append key to cookie
if(flag){
keyList.push(key);
}
local._data(cookieName, keyList.join(delim));
},
treeInit: function(ctx){
var tree = ctx.tree,
opts = ctx.options,
local = this._local,
instOpts = this.options.persist;
// For 'auto' or 'cookie' mode, the cookie plugin must be available
_assert((instOpts.store !== "auto" && instOpts.store !== "cookie") || cookieGetter,
"Missing required plugin for 'persist' extension: js.cookie.js or jquery.cookie.js");
local.cookiePrefix = instOpts.cookiePrefix || ("fancytree-" + tree._id + "-");
local.storeActive = instOpts.types.indexOf(ACTIVE) >= 0;
local.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0;
local.storeSelected = instOpts.types.indexOf(SELECTED) >= 0;
local.storeFocus = instOpts.types.indexOf(FOCUS) >= 0;
if( instOpts.store === "cookie" || !window.localStorage ) {
local.localStorage = null;
} else {
local.localStorage = (instOpts.store === "local") ? window.localStorage : window.sessionStorage;
}
// Bind init-handler to apply cookie state
tree.$div.bind("fancytreeinit", function(event){
if ( tree._triggerTreeEvent("beforeRestore", null, {}) === false ) {
return;
}
var cookie, dfd, i, keyList, node,
prevFocus = local._data(local.cookiePrefix + FOCUS), // record this before node.setActive() overrides it;
noEvents = instOpts.fireActivate === false;
// tree.debug("document.cookie:", document.cookie);
cookie = local._data(local.cookiePrefix + EXPANDED);
keyList = cookie && cookie.split(instOpts.cookieDelimiter);
if( local.storeExpanded ) {
// Recursively load nested lazy nodes if expandLazy is 'expand' or 'load'
// Also remove expand-cookies for unmatched nodes
dfd = _loadLazyNodes(tree, local, keyList, instOpts.expandLazy ? "expand" : false , null);
} else {
// nothing to do
dfd = new $.Deferred().resolve();
}
dfd.done(function(){
if(local.storeSelected){
cookie = local._data(local.cookiePrefix + SELECTED);
if(cookie){
keyList = cookie.split(instOpts.cookieDelimiter);
for(i=0; i<keyList.length; i++){
node = tree.getNodeByKey(keyList[i]);
if(node){
if(node.selected === undefined || instOpts.overrideSource && (node.selected === false)){
// node.setSelected();
node.selected = true;
node.renderStatus();
}
}else{
// node is no longer member of the tree: remove from cookie also
local._appendKey(SELECTED, keyList[i], false);
}
}
}
// In selectMode 3 we have to fix the child nodes, since we
// only stored the selected *top* nodes
if( tree.options.selectMode === 3 ){
tree.visit(function(n){
if( n.selected ) {
n.fixSelection3AfterClick();
return "skip";
}
});
}
}
if(local.storeActive){
cookie = local._data(local.cookiePrefix + ACTIVE);
if(cookie && (opts.persist.overrideSource || !tree.activeNode)){
node = tree.getNodeByKey(cookie);
if(node){
node.debug("persist: set active", cookie);
// We only want to set the focus if the container
// had the keyboard focus before
node.setActive(true, {
noFocus: true,
noEvents: noEvents
});
}
}
}
if(local.storeFocus && prevFocus){
node = tree.getNodeByKey(prevFocus);
if(node){
// node.debug("persist: set focus", cookie);
if( tree.options.titlesTabbable ) {
$(node.span).find(".fancytree-title").focus();
} else {
$(tree.$container).focus();
}
// node.setFocus();
}
}
tree._triggerTreeEvent("restore", null, {});
});
});
// Init the tree
return this._superApply(arguments);
},
nodeSetActive: function(ctx, flag, callOpts) {
var res,
local = this._local;
flag = (flag !== false);
res = this._superApply(arguments);
if(local.storeActive){
local._data(local.cookiePrefix + ACTIVE, this.activeNode ? this.activeNode.key : null);
}
return res;
},
nodeSetExpanded: function(ctx, flag, callOpts) {
var res,
node = ctx.node,
local = this._local;
flag = (flag !== false);
res = this._superApply(arguments);
if(local.storeExpanded){
local._appendKey(EXPANDED, node.key, flag);
}
return res;
},
nodeSetFocus: function(ctx, flag) {
var res,
local = this._local;
flag = (flag !== false);
res = this._superApply(arguments);
if( local.storeFocus ) {
local._data(local.cookiePrefix + FOCUS, this.focusNode ? this.focusNode.key : null);
}
return res;
},
nodeSetSelected: function(ctx, flag) {
var res, selNodes,
tree = ctx.tree,
node = ctx.node,
local = this._local;
flag = (flag !== false);
res = this._superApply(arguments);
if(local.storeSelected){
if( tree.options.selectMode === 3 ){
// In selectMode 3 we only store the the selected *top* nodes.
// De-selecting a node may also de-select some parents, so we
// calculate the current status again
selNodes = $.map(tree.getSelectedNodes(true), function(n){
return n.key;
});
selNodes = selNodes.join(ctx.options.persist.cookieDelimiter);
local._data(local.cookiePrefix + SELECTED, selNodes);
} else {
// beforeSelect can prevent the change - flag doesn't reflect the node.selected state
local._appendKey(SELECTED, node.key, node.selected);
}
}
return res;
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.table.js
*
* Render tree as table (aka 'treegrid', 'tabletree').
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
;(function($, window, document, undefined) {
"use strict";
/* *****************************************************************************
* Private functions and variables
*/
function _assert(cond, msg){
msg = msg || "";
if(!cond){
$.error("Assertion failed " + msg);
}
}
function insertFirstChild(referenceNode, newNode) {
referenceNode.insertBefore(newNode, referenceNode.firstChild);
}
function insertSiblingAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
/* Show/hide all rows that are structural descendants of `parent`. */
function setChildRowVisibility(parent, flag) {
parent.visit(function(node){
var tr = node.tr;
// currentFlag = node.hide ? false : flag; // fix for ext-filter
if(tr){
tr.style.display = (node.hide || !flag) ? "none" : "";
}
if(!node.expanded){
return "skip";
}
});
}
/* Find node that is rendered in previous row. */
function findPrevRowNode(node){
var i, last, prev,
parent = node.parent,
siblings = parent ? parent.children : null;
if(siblings && siblings.length > 1 && siblings[0] !== node){
// use the lowest descendant of the preceeding sibling
i = $.inArray(node, siblings);
prev = siblings[i - 1];
_assert(prev.tr);
// descend to lowest child (with a <tr> tag)
while(prev.children && prev.children.length){
last = prev.children[prev.children.length - 1];
if(!last.tr){
break;
}
prev = last;
}
}else{
// if there is no preceding sibling, use the direct parent
prev = parent;
}
return prev;
}
/* Render callback for 'wide' mode. */
// function _renderStatusNodeWide(event, data) {
// var node = data.node,
// nodeColumnIdx = data.options.table.nodeColumnIdx,
// $tdList = $(node.tr).find(">td");
// $tdList.eq(nodeColumnIdx).attr("colspan", data.tree.columnCount);
// $tdList.not(":eq(" + nodeColumnIdx + ")").remove();
// }
$.ui.fancytree.registerExtension({
name: "table",
version: "2.22.3",
// Default options for this extension.
options: {
checkboxColumnIdx: null, // render the checkboxes into the this column index (default: nodeColumnIdx)
// customStatus: false, // true: generate renderColumns events for status nodes
indentation: 16, // indent every node level by 16px
nodeColumnIdx: 0 // render node expander, icon, and title to this column (default: #0)
},
// Overide virtual methods for this extension.
// `this` : is this extension object
// `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree)
treeInit: function(ctx){
var i, columnCount, n, $row, $tbody,
tree = ctx.tree,
opts = ctx.options,
tableOpts = opts.table,
$table = tree.widget.element;
if( tableOpts.customStatus != null ) {
if( opts.renderStatusColumns != null) {
$.error("The 'customStatus' option is deprecated since v2.15.0. Use 'renderStatusColumns' only instead.");
} else {
tree.warn("The 'customStatus' option is deprecated since v2.15.0. Use 'renderStatusColumns' instead.");
opts.renderStatusColumns = tableOpts.customStatus;
}
}
if( opts.renderStatusColumns ) {
if( opts.renderStatusColumns === true ) {
opts.renderStatusColumns = opts.renderColumns;
// } else if( opts.renderStatusColumns === "wide" ) {
// opts.renderStatusColumns = _renderStatusNodeWide;
}
}
$table.addClass("fancytree-container fancytree-ext-table");
tree.tbody = $table.find(">tbody")[0];
$tbody = $(tree.tbody);
// Prepare row templates:
// Determine column count from table header if any
columnCount = $("thead >tr:last >th", $table).length;
// Read TR templates from tbody if any
$row = $tbody.children("tr:first");
if( $row.length ) {
n = $row.children("td").length;
if( columnCount && n !== columnCount ) {
tree.warn("Column count mismatch between thead (" + columnCount + ") and tbody (" + n + "): using tbody.");
columnCount = n;
}
$row = $row.clone();
} else {
// Only thead is defined: create default row markup
_assert(columnCount >= 1, "Need either <thead> or <tbody> with <td> elements to determine column count.");
$row = $("<tr />");
for(i=0; i<columnCount; i++) {
$row.append("<td />");
}
}
$row.find(">td").eq(tableOpts.nodeColumnIdx)
.html("<span class='fancytree-node' />");
if( opts.aria ) {
$row.attr("role", "row");
$row.find("td").attr("role", "gridcell");
}
tree.rowFragment = document.createDocumentFragment();
tree.rowFragment.appendChild($row.get(0));
// // If tbody contains a second row, use this as status node template
// $row = $tbody.children("tr:eq(1)");
// if( $row.length === 0 ) {
// tree.statusRowFragment = tree.rowFragment;
// } else {
// $row = $row.clone();
// tree.statusRowFragment = document.createDocumentFragment();
// tree.statusRowFragment.appendChild($row.get(0));
// }
//
$tbody.empty();
// Make sure that status classes are set on the node's <tr> elements
tree.statusClassPropName = "tr";
tree.ariaPropName = "tr";
this.nodeContainerAttrName = "tr";
// #489: make sure $container is set to <table>, even if ext-dnd is listed before ext-table
tree.$container = $table;
this._superApply(arguments);
// standard Fancytree created a root UL
$(tree.rootNode.ul).remove();
tree.rootNode.ul = null;
// Add container to the TAB chain
// #577: Allow to set tabindex to "0", "-1" and ""
this.$container.attr("tabindex", opts.tabindex);
// this.$container.attr("tabindex", opts.tabbable ? "0" : "-1");
if(opts.aria) {
tree.$container
.attr("role", "treegrid")
.attr("aria-readonly", true);
}
},
nodeRemoveChildMarkup: function(ctx) {
var node = ctx.node;
// node.debug("nodeRemoveChildMarkup()");
node.visit(function(n){
if(n.tr){
$(n.tr).remove();
n.tr = null;
}
});
},
nodeRemoveMarkup: function(ctx) {
var node = ctx.node;
// node.debug("nodeRemoveMarkup()");
if(node.tr){
$(node.tr).remove();
node.tr = null;
}
this.nodeRemoveChildMarkup(ctx);
},
/* Override standard render. */
nodeRender: function(ctx, force, deep, collapsed, _recursive) {
var children, firstTr, i, l, newRow, prevNode, prevTr, subCtx,
tree = ctx.tree,
node = ctx.node,
opts = ctx.options,
isRootNode = !node.parent;
if( tree._enableUpdate === false ) {
// $.ui.fancytree.debug("*** nodeRender _enableUpdate: false");
return;
}
if( !_recursive ){
ctx.hasCollapsedParents = node.parent && !node.parent.expanded;
}
// $.ui.fancytree.debug("*** nodeRender " + node + ", isRoot=" + isRootNode, "tr=" + node.tr, "hcp=" + ctx.hasCollapsedParents, "parent.tr=" + (node.parent && node.parent.tr));
if( !isRootNode ){
if( node.tr && force ) {
this.nodeRemoveMarkup(ctx);
}
if( !node.tr ) {
if( ctx.hasCollapsedParents && !deep ) {
// #166: we assume that the parent will be (recursively) rendered
// later anyway.
node.debug("nodeRender ignored due to unrendered parent");
return;
}
// Create new <tr> after previous row
// if( node.isStatusNode() ) {
// newRow = tree.statusRowFragment.firstChild.cloneNode(true);
// } else {
newRow = tree.rowFragment.firstChild.cloneNode(true);
// }
prevNode = findPrevRowNode(node);
// $.ui.fancytree.debug("*** nodeRender " + node + ": prev: " + prevNode.key);
_assert(prevNode);
if(collapsed === true && _recursive){
// hide all child rows, so we can use an animation to show it later
newRow.style.display = "none";
}else if(deep && ctx.hasCollapsedParents){
// also hide this row if deep === true but any parent is collapsed
newRow.style.display = "none";
// newRow.style.color = "red";
}
if(!prevNode.tr){
_assert(!prevNode.parent, "prev. row must have a tr, or be system root");
// tree.tbody.appendChild(newRow);
insertFirstChild(tree.tbody, newRow); // #675
}else{
insertSiblingAfter(prevNode.tr, newRow);
}
node.tr = newRow;
if( node.key && opts.generateIds ){
node.tr.id = opts.idPrefix + node.key;
}
node.tr.ftnode = node;
// if(opts.aria){
// $(node.tr).attr("aria-labelledby", "ftal_" + opts.idPrefix + node.key);
// }
node.span = $("span.fancytree-node", node.tr).get(0);
// Set icon, link, and title (normally this is only required on initial render)
this.nodeRenderTitle(ctx);
// Allow tweaking, binding, after node was created for the first time
// tree._triggerNodeEvent("createNode", ctx);
if ( opts.createNode ){
opts.createNode.call(tree, {type: "createNode"}, ctx);
}
} else {
if( force ) {
// Set icon, link, and title (normally this is only required on initial render)
this.nodeRenderTitle(ctx); // triggers renderColumns()
} else {
// Update element classes according to node state
this.nodeRenderStatus(ctx);
}
}
}
// Allow tweaking after node state was rendered
// tree._triggerNodeEvent("renderNode", ctx);
if ( opts.renderNode ){
opts.renderNode.call(tree, {type: "renderNode"}, ctx);
}
// Visit child nodes
// Add child markup
children = node.children;
if(children && (isRootNode || deep || node.expanded)){
for(i=0, l=children.length; i<l; i++) {
subCtx = $.extend({}, ctx, {node: children[i]});
subCtx.hasCollapsedParents = subCtx.hasCollapsedParents || !node.expanded;
this.nodeRender(subCtx, force, deep, collapsed, true);
}
}
// Make sure, that <tr> order matches node.children order.
if(children && !_recursive){ // we only have to do it once, for the root branch
prevTr = node.tr || null;
firstTr = tree.tbody.firstChild;
// Iterate over all descendants
node.visit(function(n){
if(n.tr){
if(!n.parent.expanded && n.tr.style.display !== "none"){
// fix after a node was dropped over a collapsed
n.tr.style.display = "none";
setChildRowVisibility(n, false);
}
if(n.tr.previousSibling !== prevTr){
node.debug("_fixOrder: mismatch at node: " + n);
var nextTr = prevTr ? prevTr.nextSibling : firstTr;
tree.tbody.insertBefore(n.tr, nextTr);
}
prevTr = n.tr;
}
});
}
// Update element classes according to node state
// if(!isRootNode){
// this.nodeRenderStatus(ctx);
// }
},
nodeRenderTitle: function(ctx, title) {
var $cb, res,
node = ctx.node,
opts = ctx.options,
isStatusNode = node.isStatusNode();
res = this._super(ctx, title);
if( node.isRootNode() ) {
return res;
}
// Move checkbox to custom column
if(opts.checkbox && !isStatusNode && opts.table.checkboxColumnIdx != null ){
$cb = $("span.fancytree-checkbox", node.span); //.detach();
$(node.tr).find("td").eq(+opts.table.checkboxColumnIdx).html($cb);
}
// Update element classes according to node state
this.nodeRenderStatus(ctx);
if( isStatusNode ) {
if( opts.renderStatusColumns ) {
// Let user code write column content
opts.renderStatusColumns.call(ctx.tree, {type: "renderStatusColumns"}, ctx);
} // else: default rendering for status node: leave other cells empty
} else if ( opts.renderColumns ) {
opts.renderColumns.call(ctx.tree, {type: "renderColumns"}, ctx);
}
return res;
},
nodeRenderStatus: function(ctx) {
var indent,
node = ctx.node,
opts = ctx.options;
this._super(ctx);
$(node.tr).removeClass("fancytree-node");
// indent
indent = (node.getLevel() - 1) * opts.table.indentation;
$(node.span).css({paddingLeft: indent + "px"}); // #460
// $(node.span).css({marginLeft: indent + "px"});
},
/* Expand node, return Deferred.promise. */
nodeSetExpanded: function(ctx, flag, callOpts) {
// flag defaults to true
flag = (flag !== false);
if((ctx.node.expanded && flag) || (!ctx.node.expanded && !flag)) {
// Expanded state isn't changed - just call base implementation
return this._superApply(arguments);
}
var dfd = new $.Deferred(),
subOpts = $.extend({}, callOpts, {noEvents: true, noAnimation: true});
callOpts = callOpts || {};
function _afterExpand(ok) {
setChildRowVisibility(ctx.node, flag);
if( ok ) {
if( flag && ctx.options.autoScroll && !callOpts.noAnimation && ctx.node.hasChildren() ) {
// Scroll down to last child, but keep current node visible
ctx.node.getLastChild().scrollIntoView(true, {topNode: ctx.node}).always(function(){
if( !callOpts.noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
dfd.resolveWith(ctx.node);
});
} else {
if( !callOpts.noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
dfd.resolveWith(ctx.node);
}
} else {
if( !callOpts.noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
dfd.rejectWith(ctx.node);
}
}
// Call base-expand with disabled events and animation
this._super(ctx, flag, subOpts).done(function () {
_afterExpand(true);
}).fail(function () {
_afterExpand(false);
});
return dfd.promise();
},
nodeSetStatus: function(ctx, status, message, details) {
if(status === "ok"){
var node = ctx.node,
firstChild = ( node.children ? node.children[0] : null );
if ( firstChild && firstChild.isStatusNode() ) {
$(firstChild.tr).remove();
}
}
return this._superApply(arguments);
},
treeClear: function(ctx) {
this.nodeRemoveChildMarkup(this._makeHookContext(this.rootNode));
return this._superApply(arguments);
},
treeDestroy: function(ctx) {
this.$container.find("tbody").empty();
this.$source && this.$source.removeClass("ui-helper-hidden");
return this._superApply(arguments);
}
/*,
treeSetFocus: function(ctx, flag) {
// alert("treeSetFocus" + ctx.tree.$container);
ctx.tree.$container.focus();
$.ui.fancytree.focusTree = ctx.tree;
}*/
});
}(jQuery, window, document));
/*!
* jquery.fancytree.themeroller.js
*
* Enable jQuery UI ThemeRoller styles.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* @see http://jqueryui.com/themeroller/
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "themeroller",
version: "2.22.3",
// Default options for this extension.
options: {
activeClass: "ui-state-active", // Class added to active node
// activeClass: "ui-state-highlight",
addClass: "ui-corner-all", // Class added to all nodes
focusClass: "ui-state-focus", // Class added to focused node
hoverClass: "ui-state-hover", // Class added to hovered node
selectedClass: "ui-state-highlight" // Class added to selected nodes
// selectedClass: "ui-state-active"
},
treeInit: function(ctx){
var $el = ctx.widget.element,
opts = ctx.options.themeroller;
this._superApply(arguments);
if($el[0].nodeName === "TABLE"){
$el.addClass("ui-widget ui-corner-all");
$el.find(">thead tr").addClass("ui-widget-header");
$el.find(">tbody").addClass("ui-widget-conent");
}else{
$el.addClass("ui-widget ui-widget-content ui-corner-all");
}
$el.delegate(".fancytree-node", "mouseenter mouseleave", function(event){
var node = $.ui.fancytree.getNode(event.target),
flag = (event.type === "mouseenter");
$(node.tr ? node.tr : node.span)
.toggleClass(opts.hoverClass + " " + opts.addClass, flag);
});
},
treeDestroy: function(ctx){
this._superApply(arguments);
ctx.widget.element.removeClass("ui-widget ui-widget-content ui-corner-all");
},
nodeRenderStatus: function(ctx){
var classes = {},
node = ctx.node,
$el = $(node.tr ? node.tr : node.span),
opts = ctx.options.themeroller;
this._super(ctx);
/*
.ui-state-highlight: Class to be applied to highlighted or selected elements. Applies "highlight" container styles to an element and its child text, links, and icons.
.ui-state-error: Class to be applied to error messaging container elements. Applies "error" container styles to an element and its child text, links, and icons.
.ui-state-error-text: An additional class that applies just the error text color without background. Can be used on form labels for instance. Also applies error icon color to child icons.
.ui-state-default: Class to be applied to clickable button-like elements. Applies "clickable default" container styles to an element and its child text, links, and icons.
.ui-state-hover: Class to be applied on mouseover to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
.ui-state-focus: Class to be applied on keyboard focus to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
.ui-state-active: Class to be applied on mousedown to clickable button-like elements. Applies "clickable active" container styles to an element and its child text, links, and icons.
*/
// Set ui-state-* class (handle the case that the same class is assigned
// to different states)
classes[opts.activeClass] = false;
classes[opts.focusClass] = false;
classes[opts.selectedClass] = false;
if( node.isActive() ) { classes[opts.activeClass] = true; }
if( node.hasFocus() ) { classes[opts.focusClass] = true; }
// activeClass takes precedence before selectedClass:
if( node.isSelected() && !node.isActive() ) { classes[opts.selectedClass] = true; }
$el.toggleClass(opts.activeClass, classes[opts.activeClass]);
$el.toggleClass(opts.focusClass, classes[opts.focusClass]);
$el.toggleClass(opts.selectedClass, classes[opts.selectedClass]);
// Additional classes (e.g. 'ui-corner-all')
$el.addClass(opts.addClass);
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.wide.js
* Support for 100% wide selection bars.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.22.3
* @date 2017-05-05T05:59:51Z
*/
;(function($, window, document, undefined) {
"use strict";
var reNumUnit = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/; // split "1.5em" to ["1.5", "em"]
/*******************************************************************************
* Private functions and variables
*/
// var _assert = $.ui.fancytree.assert;
/* Calculate inner width without scrollbar */
// function realInnerWidth($el) {
// // http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/
// // inst.contWidth = parseFloat(this.$container.css("width"), 10);
// // 'Client width without scrollbar' - 'padding'
// return $el[0].clientWidth - ($el.innerWidth() - parseFloat($el.css("width"), 10));
// }
/* Create a global embedded CSS style for the tree. */
function defineHeadStyleElement(id, cssText) {
id = "fancytree-style-" + id;
var $headStyle = $("#" + id);
if( !cssText ) {
$headStyle.remove();
return null;
}
if( !$headStyle.length ) {
$headStyle = $("<style />")
.attr("id", id)
.addClass("fancytree-style")
.prop("type", "text/css")
.appendTo("head");
}
try {
$headStyle.html(cssText);
} catch ( e ) {
// fix for IE 6-8
$headStyle[0].styleSheet.cssText = cssText;
}
return $headStyle;
}
/* Calculate the CSS rules that indent title spans. */
function renderLevelCss(containerId, depth, levelOfs, lineOfs, labelOfs, measureUnit)
{
var i,
prefix = "#" + containerId + " span.fancytree-level-",
rules = [];
for(i = 0; i < depth; i++) {
rules.push(prefix + (i + 1) + " span.fancytree-title { padding-left: " +
(i * levelOfs + lineOfs) + measureUnit + "; }");
}
// Some UI animations wrap the UL inside a DIV and set position:relative on both.
// This breaks the left:0 and padding-left:nn settings of the title
rules.push(
"#" + containerId + " div.ui-effects-wrapper ul li span.fancytree-title, " +
"#" + containerId + " ul.fancytree-animating span.fancytree-title " + // #716
"{ padding-left: " + labelOfs + measureUnit + "; position: static; width: auto; }");
return rules.join("\n");
}
// /**
// * [ext-wide] Recalculate the width of the selection bar after the tree container
// * was resized.<br>
// * May be called explicitly on container resize, since there is no resize event
// * for DIV tags.
// *
// * @alias Fancytree#wideUpdate
// * @requires jquery.fancytree.wide.js
// */
// $.ui.fancytree._FancytreeClass.prototype.wideUpdate = function(){
// var inst = this.ext.wide,
// prevCw = inst.contWidth,
// prevLo = inst.lineOfs;
// inst.contWidth = realInnerWidth(this.$container);
// // Each title is precceeded by 2 or 3 icons (16px + 3 margin)
// // + 1px title border and 3px title padding
// // TODO: use code from treeInit() below
// inst.lineOfs = (this.options.checkbox ? 3 : 2) * 19;
// if( prevCw !== inst.contWidth || prevLo !== inst.lineOfs ) {
// this.debug("wideUpdate: " + inst.contWidth);
// this.visit(function(node){
// node.tree._callHook("nodeRenderTitle", node);
// });
// }
// };
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "wide",
version: "2.22.3",
// Default options for this extension.
options: {
iconWidth: null, // Adjust this if @fancy-icon-width != "16px"
iconSpacing: null, // Adjust this if @fancy-icon-spacing != "3px"
labelSpacing: null, // Adjust this if padding between icon and label != "3px"
levelOfs: null // Adjust this if ul padding != "16px"
},
treeCreate: function(ctx){
this._superApply(arguments);
this.$container.addClass("fancytree-ext-wide");
var containerId, cssText, iconSpacingUnit, labelSpacingUnit, iconWidthUnit, levelOfsUnit,
instOpts = ctx.options.wide,
// css sniffing
$dummyLI = $("<li id='fancytreeTemp'><span class='fancytree-node'><span class='fancytree-icon' /><span class='fancytree-title' /></span><ul />")
.appendTo(ctx.tree.$container),
$dummyIcon = $dummyLI.find(".fancytree-icon"),
$dummyUL = $dummyLI.find("ul"),
// $dummyTitle = $dummyLI.find(".fancytree-title"),
iconSpacing = instOpts.iconSpacing || $dummyIcon.css("margin-left"),
iconWidth = instOpts.iconWidth || $dummyIcon.css("width"),
labelSpacing = instOpts.labelSpacing || "3px",
levelOfs = instOpts.levelOfs || $dummyUL.css("padding-left");
$dummyLI.remove();
iconSpacingUnit = iconSpacing.match(reNumUnit)[2];
iconSpacing = parseFloat(iconSpacing, 10);
labelSpacingUnit = labelSpacing.match(reNumUnit)[2];
labelSpacing = parseFloat(labelSpacing, 10);
iconWidthUnit = iconWidth.match(reNumUnit)[2];
iconWidth = parseFloat(iconWidth, 10);
levelOfsUnit = levelOfs.match(reNumUnit)[2];
if( iconSpacingUnit !== iconWidthUnit || levelOfsUnit !== iconWidthUnit || labelSpacingUnit !== iconWidthUnit ) {
$.error("iconWidth, iconSpacing, and levelOfs must have the same css measure unit");
}
this._local.measureUnit = iconWidthUnit;
this._local.levelOfs = parseFloat(levelOfs);
this._local.lineOfs = (1 + (ctx.options.checkbox ? 1 : 0) +
(ctx.options.icon === false ? 0 : 1)) * (iconWidth + iconSpacing) +
iconSpacing;
this._local.labelOfs = labelSpacing;
this._local.maxDepth = 10;
// Get/Set a unique Id on the container (if not already exists)
containerId = this.$container.uniqueId().attr("id");
// Generated css rules for some levels (extended on demand)
cssText = renderLevelCss(containerId, this._local.maxDepth,
this._local.levelOfs, this._local.lineOfs, this._local.labelOfs,
this._local.measureUnit);
defineHeadStyleElement(containerId, cssText);
},
treeDestroy: function(ctx){
// Remove generated css rules
defineHeadStyleElement(this.$container.attr("id"), null);
return this._superApply(arguments);
},
nodeRenderStatus: function(ctx) {
var containerId, cssText, res,
node = ctx.node,
level = node.getLevel();
res = this._super(ctx);
// Generate some more level-n rules if required
if( level > this._local.maxDepth ) {
containerId = this.$container.attr("id");
this._local.maxDepth *= 2;
node.debug("Define global ext-wide css up to level " + this._local.maxDepth);
cssText = renderLevelCss(containerId, this._local.maxDepth,
this._local.levelOfs, this._local.lineOfs, this._local.labelSpacing,
this._local.measureUnit);
defineHeadStyleElement(containerId, cssText);
}
// Add level-n class to apply indentation padding.
// (Setting element style would not work, since it cannot easily be
// overriden while animations run)
$(node.span).addClass("fancytree-level-" + level);
return res;
}
});
}(jQuery, window, document));
|
demo/demo.js | geminiyellow/react-sparklines | import React from 'react';
import { Sparklines, SparklinesBars, SparklinesLine, SparklinesNormalBand, SparklinesReferenceLine, SparklinesSpots } from '../src/Sparklines';
function boxMullerRandom () {
let phase = false,
x1, x2, w, z;
return (function() {
if (phase = !phase) {
do {
x1 = 2.0 * Math.random() - 1.0;
x2 = 2.0 * Math.random() - 1.0;
w = x1 * x1 + x2 * x2;
} while (w >= 1.0);
w = Math.sqrt((-2.0 * Math.log(w)) / w);
return x1 * w;
} else {
return x2 * w;
}
})();
}
function randomData(n = 30) {
return Array.apply(0, Array(n)).map(boxMullerRandom);
}
const sampleData = randomData(30);
const sampleData100 = randomData(100);
class Header extends React.Component {
render() {
return (
<Sparklines data={sampleData} width={300} height={50}>
<SparklinesLine style={{ stroke: "white", fill: "none" }} />
<SparklinesReferenceLine style={{ stroke: 'white', strokeOpacity: .75, strokeDasharray: '2, 2' }} />
</Sparklines>
);
}
}
class Simple extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine />
</Sparklines>
);
}
}
class Customizable1 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine color="#1c8cdc" />
</Sparklines>
);
}
}
class Customizable2 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine color="#fa7e17" />
</Sparklines>
);
}
}
class Customizable3 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine color="#ea485c" />
</Sparklines>
);
}
}
class Customizable4 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine color="#56b45d" />
</Sparklines>
);
}
}
class Customizable5 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine color="#8e44af" />
</Sparklines>
);
}
}
class Customizable6 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine color="#253e56" />
</Sparklines>
);
}
}
class Spots1 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine style={{ fill: "none" }} />
<SparklinesSpots />
</Sparklines>
);
}
}
class Spots2 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine color="#56b45d" />
<SparklinesSpots style={{ fill: "#56b45d" }} />
</Sparklines>
);
}
}
class Spots3 extends React.Component {
render() {
return (
<Sparklines data={sampleData} margin={6}>
<SparklinesLine style={{ strokeWidth: 3, stroke: "#336aff", fill: "none" }} />
<SparklinesSpots size={4} style={{ stroke: "#336aff", strokeWidth: 3, fill: "white" }} />
</Sparklines>
);
}
}
class Bars1 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesBars style={{ fill: "#41c3f9" }} />
</Sparklines>
);
}
}
class Bars2 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesBars style={{ stroke: "white", fill: "#41c3f9", fillOpacity: ".25" }} />
<SparklinesLine style={{ stroke: "#41c3f9", fill: "none" }} />
</Sparklines>
);
}
}
class Dynamic1 extends React.Component {
constructor(props) {
super(props);
this.state = { data: [] };
setInterval(() =>
this.setState({
data: this.state.data.concat([boxMullerRandom()])
}), 100);
}
render() {
return (
<Sparklines data={this.state.data} limit={20}>
<SparklinesLine color="#1c8cdc" />
<SparklinesSpots />
</Sparklines>
);
}
}
class Dynamic2 extends React.Component {
constructor(props) {
super(props);
this.state = { data: [] };
setInterval(() =>
this.setState({
data: this.state.data.concat([boxMullerRandom()])
}), 100);
}
render() {
return (
<Sparklines data={this.state.data} limit={20}>
<SparklinesBars style={{ fill: "#41c3f9", fillOpacity: ".25" }} />
<SparklinesLine style={{ stroke: "#41c3f9", fill: "none" }} />
</Sparklines>
);
}
}
class Dynamic3 extends React.Component {
constructor(props) {
super(props);
this.state = { data: [] };
setInterval(() =>
this.setState({
data: this.state.data.concat([boxMullerRandom()])
}), 100);
}
render() {
return (
<Sparklines data={this.state.data} limit={20}>
<SparklinesLine style={{ stroke: "none", fill: "#8e44af", fillOpacity: "1" }}/>
</Sparklines>
);
}
}
class Dynamic4 extends React.Component {
constructor(props) {
super(props);
this.state = { data: [] };
setInterval(() =>
this.setState({
data: this.state.data.concat([boxMullerRandom()])
}), 100);
}
render() {
return (
<Sparklines data={this.state.data} limit={10} >
<SparklinesBars color="#0a83d8" />
</Sparklines>
);
}
}
class ReferenceLine1 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine />
<SparklinesReferenceLine type="max" />
</Sparklines>
);
}
}
class ReferenceLine2 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine />
<SparklinesReferenceLine type="min" />
</Sparklines>
);
}
}
class ReferenceLine3 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine />
<SparklinesReferenceLine type="mean" />
</Sparklines>
);
}
}
class ReferenceLine4 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine />
<SparklinesReferenceLine type="avg" />
</Sparklines>
);
}
}
class ReferenceLine5 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine />
<SparklinesReferenceLine type="median" />
</Sparklines>
);
}
}
class ReferenceLine6 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesBars style={{ fill: 'slategray', fillOpacity: ".5" }} />
<SparklinesReferenceLine />
</Sparklines>
);
}
}
class NormalBand1 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine style={{ fill: "none" }}/>
<SparklinesNormalBand />
</Sparklines>
);
}
}
class NormalBand2 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine style={{ fill: "none" }}/>
<SparklinesNormalBand />
<SparklinesReferenceLine type="mean" />
</Sparklines>
);
}
}
class RealWorld1 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesLine style={{ strokeWidth: 3, stroke: "#336aff", fill: "none" }} />
</Sparklines>
);
}
}
class RealWorld2 extends React.Component {
render() {
return (
<Sparklines data={sampleData100} width={200}>
<SparklinesLine style={{ stroke: "#2991c8", fill: "none"}} />
<SparklinesSpots />
<SparklinesNormalBand style={{ fill: "#2991c8", fillOpacity: .1 }} />
</Sparklines>
);
}
}
class RealWorld3 extends React.Component {
render() {
return (
<Sparklines data={sampleData100}>
<SparklinesLine style={{ stroke: "black", fill: "none" }} />
<SparklinesSpots style={{ fill: "orange" }} />
</Sparklines>
);
}
}
class RealWorld4 extends React.Component {
render() {
return (
<Sparklines data={sampleData}>
<SparklinesBars style={{ stroke: "white", strokeWidth: "1", fill: "#40c0f5" }} />
</Sparklines>
);
}
}
class RealWorld5 extends React.Component {
render() {
return (
<Sparklines data={sampleData} height={80}>
<SparklinesLine style={{ stroke: "#8ed53f", strokeWidth: "1", fill: "none" }} />
</Sparklines>
);
}
}
class RealWorld6 extends React.Component {
render() {
return (
<Sparklines data={sampleData} height={80}>
<SparklinesLine style={{ stroke: "#d1192e", strokeWidth: "1", fill: "none" }} />
</Sparklines>
);
}
}
class RealWorld7 extends React.Component {
render() {
return (
<Sparklines data={sampleData} height={40}>
<SparklinesLine style={{ stroke: "#559500", fill: "#8fc638", fillOpacity: "1" }} />
</Sparklines>
);
}
}
class RealWorld8 extends React.Component {
render() {
return (
<Sparklines data={sampleData} style={{background: "#272727"}} margin={10} height={40}>
<SparklinesLine style={{ stroke: "none", fill: "#d2673a", fillOpacity: ".5" }} />
</Sparklines>
);
}
}
class RealWorld9 extends React.Component {
render() {
return (
<Sparklines data={sampleData} style={{background: "#00bdcc"}} margin={10} height={40}>
<SparklinesLine style={{ stroke: "white", fill: "none" }} />
<SparklinesReferenceLine style={{ stroke: 'white', strokeOpacity: .75, strokeDasharray: '2, 2' }} />
</Sparklines>
);
}
}
const demos = {
'headersparklines': Header,
'simple': Simple,
'customizable1': Customizable1,
'customizable2': Customizable2,
'customizable3': Customizable3,
'customizable4': Customizable4,
'customizable5': Customizable5,
'customizable6': Customizable6,
'spots1': Spots1,
'spots2': Spots2,
'spots3': Spots3,
'bars1': Bars1,
'bars2': Bars2,
'dynamic1': Dynamic1,
'dynamic2': Dynamic2,
'dynamic3': Dynamic3,
'dynamic4': Dynamic4,
'referenceline1': ReferenceLine1,
'referenceline2': ReferenceLine2,
'referenceline3': ReferenceLine3,
'referenceline4': ReferenceLine4,
'referenceline5': ReferenceLine5,
'referenceline6': ReferenceLine6,
'normalband1': NormalBand1,
'normalband2': NormalBand2,
'realworld1': RealWorld1,
'realworld2': RealWorld2,
'realworld3': RealWorld3,
'realworld4': RealWorld4,
'realworld5': RealWorld5,
'realworld6': RealWorld6,
'realworld7': RealWorld7,
'realworld8': RealWorld8,
'realworld9': RealWorld9
};
for (let d in demos) {
React.render(React.createElement(demos[d]), document.getElementById(d));
}
|
__tests__/index.android.js | elderfo/elderfo-react-native-components | import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
data-browser-ui/public/app/components/tableComponents/td/aclComponents/aclRows.js | CloudBoost/cloudboost | import React from 'react'
import ReactDOM from 'react-dom'
import Checkbox from 'material-ui/Checkbox'
import AutoComplete from 'material-ui/AutoComplete'
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn
} from 'material-ui/Table'
class ACLRows extends React.Component {
constructor() {
super()
this.state = {
users: [],
roles: []
}
}
componentWillMount() {
let userQuery = new CB.CloudQuery('User')
userQuery.find().then((list) => {
this.state.users = list
this.setState(this.state)
})
let roleQuery = new CB.CloudQuery('Role')
roleQuery.find().then((list) => {
this.state.roles = list
this.setState(this.state)
})
}
getName(id, type) {
if (type == 'user' && this.state.users.length) {
return this.state.users.filter((x) => {
return x.id == id
})[0].document.username
} else if (type == 'role' && this.state.roles.length) {
return this.state.roles.filter((x) => {
return x.id == id
})[0].document.name
} else {
return ''
}
}
selectUser(chosen) {
let isPresent = this.props.aclList.filter(x => x.id == chosen.split(' - ')[1].split('(')[0].trim()).length
if (chosen && !isPresent) {
let aclObj = {}
aclObj.type = chosen.split(' - ')[0].toLowerCase()
aclObj.id = chosen.split(' - ')[1].split('(')[0].trim()
aclObj.data = {
read: false,
write: false
}
this.props.addAcl(aclObj)
}
}
getSearchItems() {
if (this.state.users.length || this.state.roles.length) {
return [
...this.state.users,
...this.state.roles
].map((x) => {
let str = x.document['_tableName'] + " - " + x.id
if (x.document.username)
str += ' ( ' + x.document.username + ' )'
if (x.document.name)
str += ' ( ' + x.document.name + ' )'
return str
})
} else
return []
}
removeAcl(id) {
this.props.removeAcl(id)
}
checkHandler(id, which, e, data) {
let aclData = {}
if (this.props.aclList.filter(x => x.id == id)[0]) {
aclData = this.props.aclList.filter(x => x.id == id)[0].data
aclData[which] = data
this.props.updateAclData(aclData, id)
} else {
let obj = {
type: 'user',
id: 'all',
data: {
read: false,
write: false
}
}
obj.data[which] = data
this.props.addAcl(obj)
}
}
render() {
let aclList = []
let publicAcl = {
data: {}
}
if (this.props.aclList) {
aclList = this.props.aclList.filter((x) => {
if (x.id == 'all') {
publicAcl = x
return false
} else
return true
}).map((x, i) => {
return <TableRow key={i}>
<TableRowColumn className="acltdthwidth">
{x.type == 'user'
? <i className="fa fa-user logoaclrow" aria-hidden="true"></i>
: <i className="fa fa-unlock-alt logoaclrow" aria-hidden="true"></i>
}
<p className="textaclrow">{this.getName(x.id, x.type)}
( {x.id}
)</p>
</TableRowColumn>
<TableRowColumn>
<p className="readwitetext">Read</p>
<Checkbox className='aclrowcheckbox' onCheck={this.checkHandler.bind(this, x.id, 'read')} checked={x.data.read}/>
</TableRowColumn>
<TableRowColumn>
<p className="readwitetext">Write</p>
<Checkbox className='aclrowcheckbox' onCheck={this.checkHandler.bind(this, x.id, 'write')} checked={x.data.write}/>
</TableRowColumn>
<TableRowColumn className="acltddeletethwidth">
<i className="fa fa-trash-o cancelaclrow" aria-hidden="true" onClick={this.removeAcl.bind(this, x.id)}></i>
</TableRowColumn>
</TableRow>
})
}
return (
<div className="relationselectordiv">
<Table selectable={false} multiSelectable={false} className="acltable">
<TableHeader displaySelectAll={false} adjustForCheckbox={false} enableSelectAll={false}>
<TableRow displayBorder={false}>
<TableRowColumn className="acltdthwidth">
<i className="fa fa-user logoaclrow" aria-hidden="true"></i>
<p className="textaclrow">Public(All)</p>
</TableRowColumn>
<TableRowColumn>
<p className="readwitetext">Read</p>
<Checkbox className='aclrowcheckbox' onCheck={this.checkHandler.bind(this, 'all', 'read')} checked={publicAcl.data.read || false}/>
</TableRowColumn>
<TableRowColumn>
<p className="readwitetext">Write</p>
<Checkbox className='aclrowcheckbox' onCheck={this.checkHandler.bind(this, 'all', 'write')} checked={publicAcl.data.write || false}/>
</TableRowColumn>
<TableRowColumn className="acltddeletethwidth"></TableRowColumn>
</TableRow>
</TableHeader>
<TableBody displayRowCheckbox={false}>
{aclList}
<TableRow>
<TableRowColumn className="acltdthwidth">
<AutoComplete floatingLabelText="Add User or Role" filter={AutoComplete.fuzzyFilter} dataSource={this.getSearchItems()} maxSearchResults={5} className="selectautoacl" onNewRequest={this.selectUser.bind(this)}/>
</TableRowColumn>
<TableRowColumn></TableRowColumn>
<TableRowColumn></TableRowColumn>
<TableRowColumn className="acltddeletethwidth"></TableRowColumn>
</TableRow>
</TableBody>
</Table>
</div>
);
}
}
export default ACLRows;
|
app/javascript/mastodon/components/missing_indicator.js | mecab/mastodon | import React from 'react';
import { FormattedMessage } from 'react-intl';
const MissingIndicator = () => (
<div className='missing-indicator'>
<div>
<FormattedMessage id='missing_indicator.label' defaultMessage='Not found' />
</div>
</div>
);
export default MissingIndicator;
|
src/ui/scoreboard.js | josmardias/tic-tac-toe | import React from 'react'
const isEqual = (x) => (n) => n === x
const Scoreboard = ({ statistics }) => (
<div style={{ fontSize: '36px', textAlign: 'center' }}>
<span style={{ fontStyle: 'italic' }}>Player 1</span>
<span style={{ marginLeft: '25px' }}>{statistics.filter(isEqual(1)).length || 0}</span>
<span style={{ margin: '0 10px' }}>x</span>
<span style={{ marginRight: '25px' }}>{statistics.filter(isEqual(2)).length || 0}</span>
<span style={{ fontStyle: 'italic' }}>Player 2</span>
</div>
)
export default Scoreboard
|
app/modules/common/publishes/list/cardList.js | theseushu/runcai | import React, { PropTypes } from 'react';
import injectSheet from 'react-jss';
import { breakpoints } from 'modules/common/styles';
import * as cards from '../cards';
const List = ({ type, entries, classes, brief, column, actions }) => {
const Card = brief ? cards[type].briefCard : cards[type].card;
let cellClassName = classes.column4;
if (column === 3) {
cellClassName = classes.column3;
} else if (column === 1) {
cellClassName = classes.column1;
}
return (
<div className={classes.entries}>
{
entries.map((entry, i) => (
<div key={i} className={cellClassName}>
<Card
key={i}
publish={entry}
actions={actions}
/>
</div>
))
}
</div>
);
};
List.propTypes = {
brief: PropTypes.bool,
column: PropTypes.oneOf([
1, 3, 4,
]),
type: PropTypes.string.isRequired,
entries: PropTypes.array.isRequired,
classes: PropTypes.object.isRequired,
actions: PropTypes.array,
};
export default injectSheet({
entries: {
display: 'flex',
flexWrap: 'wrap',
width: '100%',
},
column4: {
width: '25%',
boxSizing: 'border-box',
padding: '0 8px 16px',
[breakpoints.mediaSmallScreen]: {
width: '33.33%',
},
[breakpoints.mediaDestkopBelow]: {
width: '33.33%',
},
'@media (max-width: 680px)': {
width: '50%',
},
[breakpoints.mediaTabletBelow]: {
width: '100%',
},
},
column3: {
width: '33.3%',
boxSizing: 'border-box',
padding: '0 8px 16px',
[breakpoints.mediaSmallScreen]: {
width: '50%',
},
[breakpoints.mediaDestkopBelow]: {
width: '50%',
},
'@media (max-width: 680px)': {
width: '100%',
},
},
column1: {
width: '100%',
boxSizing: 'border-box',
padding: '0 8px 16px',
},
})(List);
|
ajax/libs/rxjs/2.2.10/rx.lite.compat.js | lxsli/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = { Internals: {} };
// Defaults
function noop() { }
function identity(x) { return x; }
var defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }());
function defaultComparer(x, y) { return isEqual(x, y); }
function defaultSubComparer(x, y) { return x - y; }
function defaultKeySerializer(x) { return x.toString(); }
function defaultError(err) { throw err; }
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() {
if (this.isDisposed) {
throw new Error(objectDisposed);
}
}
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
function isFunction(value) {
return typeof value == 'function';
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
var isEqual = Rx.Internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
var result;
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a &&
!(a && objectTypes[type]) &&
!(b && objectTypes[otherType])) {
return false;
}
// exit early for `null` and `undefined`, avoiding ES3's Function#call behavior
// http://es5.github.io/#x15.3.4.4
if (a == null || b == null) {
return a === b;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0`, treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `+0` vs. `-0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!suportNodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !supportsArgsClass && isArguments(a) ? Object : a.constructor,
ctorB = !supportsArgsClass && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB && !(
isFunction(ctorA) && ctorA instanceof ctorA &&
isFunction(ctorB) && ctorB instanceof ctorB
)) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
length = a.length;
size = b.length;
// compare lengths to determine if a deep comparison is necessary
result = size == a.length;
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
return result;
}
// deep compare each object
for(var key in b) {
if (hasOwnProperty.call(b, key)) {
// count properties and deep compare each property value
size++;
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], b[key], stackA, stackB));
}
}
if (result) {
// ensure both objects have the same number of properties
for (var key in a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.Internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.Internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.Internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Utilities
if (!Function.prototype.bind) {
Function.prototype.bind = function (that) {
var target = this,
args = slice.call(arguments, 1);
var bound = function () {
if (this instanceof bound) {
function F() { }
F.prototype = target.prototype;
var self = new F();
var result = target.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(that, args.concat(slice.call(arguments)));
}
};
return bound;
};
}
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, object);
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (predicate) {
var results = [], item, t = new Object(this);
for (var i = 0, len = t.length >>> 0; i < len; i++) {
item = t[i];
if (i in t && predicate.call(arguments[1], item, i, t)) {
results.push(item);
}
}
return results;
};
}
if (!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) == arrayClass;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(searchElement) {
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) {
n = 0;
} else if (n !== 0 && n != Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Collections
var IndexedItem = function (id, value) {
this.id = id;
this.value = value;
};
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
if (c === 0) {
c = this.id - other.id;
}
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.Internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) {
return;
}
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) {
return;
}
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
if (index === undefined) {
index = 0;
}
if (index >= this.length || index < 0) {
return;
}
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.
*/
CompositeDisposablePrototype.clear = function () {
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
};
/**
* Determines whether the CompositeDisposable contains a specific disposable.
* @param {Mixed} item Disposable to search for.
* @returns {Boolean} true if the disposable was found; otherwise, false.
*/
CompositeDisposablePrototype.contains = function (item) {
return this.disposables.indexOf(item) !== -1;
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var BooleanDisposable = (function () {
function BooleanDisposable (isSingle) {
this.isSingle = isSingle;
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
if (this.current && this.isSingle) {
throw new Error('Disposable has already been assigned');
}
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
if (old) {
old.dispose();
}
if (shouldDispose && value) {
value.dispose();
}
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
if (old) {
old.dispose();
}
};
return BooleanDisposable;
}());
/**
* Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
* If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error.
*/
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) {
inherits(SingleAssignmentDisposable, super_);
function SingleAssignmentDisposable() {
super_.call(this, true);
}
return SingleAssignmentDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
*/
var SerialDisposable = Rx.SerialDisposable = (function (super_) {
inherits(SerialDisposable, super_);
function SerialDisposable() {
super_.call(this, false);
}
return SerialDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
var ScheduledItem = Rx.Internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, function () {
action();
});
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodicWithState = function (state, period, action) {
var s = state, id = setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
clearInterval(id);
});
};
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () {
self(_action);
});
});
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, function (s, p) {
return invokeRecImmediate(s, p);
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
if (timeSpan < 0) {
timeSpan = 0;
}
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
/**
* Gets a scheduler that schedules work immediately on the current thread.
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dt);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function Trampoline() {
queue = new PriorityQueue(4);
}
Trampoline.prototype.dispose = function () {
queue = null;
};
Trampoline.prototype.run = function () {
var item;
while (queue.length > 0) {
item = queue.dequeue();
if (!item.isCancelled()) {
while (item.dueTime - Scheduler.now() > 0) { }
if (!item.isCancelled()) {
item.invoke();
}
}
}
};
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + normalizeTime(dueTime),
si = new ScheduledItem(this, state, action, dt),
t;
if (!queue) {
t = new Trampoline();
try {
queue.enqueue(si);
t.run();
} catch (e) {
throw e;
} finally {
t.dispose();
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return queue === null; };
currentScheduler.ensureTrampoline = function (action) {
if (queue === null) {
return this.schedule(action);
} else {
return action();
}
};
return currentScheduler;
}());
var SchedulePeriodicRecursive = Rx.Internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
var scheduleMethod, clearMethod = noop;
(function () {
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('','*');
root.onmessage = oldHandler;
return isAsync;
}
// Check for setImmediate first for Node v0.11+
if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return setTimeout(action, 0); };
clearMethod = clearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = setTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
clearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
var NotificationPrototype = Notification.prototype;
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) {
if (arguments.length === 1 && typeof observerOrOnNext === 'object') {
return this._acceptObservable(observerOrOnNext);
}
return this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notification
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
NotificationPrototype.toObservable = function (scheduler) {
var notification = this;
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
if (notification.kind === 'N') {
observer.onCompleted();
}
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) {
return onNext(this.value);
}
function _acceptObservable(observer) {
return observer.onNext(this.value);
}
function toString () {
return 'OnNext(' + this.value + ')';
}
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) {
return onError(this.exception);
}
function _acceptObservable(observer) {
return observer.onError(this.exception);
}
function toString () {
return 'OnError(' + this.exception + ')';
}
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) {
return onCompleted();
}
function _acceptObservable(observer) {
return observer.onCompleted();
}
function toString () {
return 'OnCompleted()';
}
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* @constructor
* @private
*/
var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent) {
this.moveNext = moveNext;
this.getCurrent = getCurrent;
};
/**
* @static
* @memberOf Enumerator
* @private
*/
var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent) {
var done = false;
return new Enumerator(function () {
if (done) {
return false;
}
var result = moveNext();
if (!result) {
done = true;
}
return result;
}, function () { return getCurrent(); });
};
var Enumerable = Rx.Internals.Enumerable = function (getEnumerator) {
this.getEnumerator = getEnumerator;
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e = sources.getEnumerator(), isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, hasNext;
if (isDisposed) { return; }
try {
hasNext = e.moveNext();
if (hasNext) {
current = e.getCurrent();
}
} catch (ex) {
observer.onError(ex);
return;
}
if (!hasNext) {
observer.onCompleted();
return;
}
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e = sources.getEnumerator(), isDisposed, lastException;
var subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, hasNext;
if (isDisposed) { return; }
try {
hasNext = e.moveNext();
if (hasNext) {
current = e.getCurrent();
}
} catch (ex) {
observer.onError(ex);
return;
}
if (!hasNext) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (arguments.length === 1) {
repeatCount = -1;
}
return new Enumerable(function () {
var current, left = repeatCount;
return enumeratorCreate(function () {
if (left === 0) {
return false;
}
if (left > 0) {
left--;
}
current = value;
return true;
}, function () { return current; });
});
};
var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var current, index = -1;
return enumeratorCreate(
function () {
if (++index < source.length) {
current = selector.call(thisArg, source[index], index, source);
return true;
}
return false;
},
function () { return current; }
);
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
*
* @static
* @memberOf Observer
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler) {
return new AnonymousObserver(function (x) {
return handler(notificationCreateOnNext(x));
}, function (exception) {
return handler(notificationCreateOnError(exception));
}, function () {
return handler(notificationCreateOnCompleted());
});
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.Internals.AbstractObserver = (function (_super) {
inherits(AbstractObserver, _super);
/**
* Creates a new observer in a non-stopped state.
*
* @constructor
*/
function AbstractObserver() {
this.isStopped = false;
_super.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
*
* @memberOf AbstractObserver
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) {
this.next(value);
}
};
/**
* Notifies the observer that an exception has occurred.
*
* @memberOf AbstractObserver
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
inherits(AnonymousObserver, _super);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
*
* @constructor
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
*
* @memberOf AnonymousObserver
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
*
* @memberOf AnonymousObserver
* @param {Any{ error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*
* @memberOf AnonymousObserver
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
/**
* @constructor
* @private
*/
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
observableProto.finalValue = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var hasValue = false, value;
return source.subscribe(function (x) {
hasValue = true;
value = x;
}, observer.onError.bind(observer), function () {
if (!hasValue) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
};
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber;
if (typeof observerOrOnNext === 'object') {
subscriber = observerOrOnNext;
} else {
subscriber = observerCreate(observerOrOnNext, onError, onCompleted);
}
return this._subscribe(subscriber);
};
/**
* Creates a list from an observable sequence.
*
* @memberOf Observable
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
function accumulator(list, i) {
var newList = list.slice(0);
newList.push(i);
return newList;
}
return this.scan([], accumulator).startWith([]).finalValue();
};
return Observable;
})();
/** @private */
var ScheduledObserver = Rx.Internals.ScheduledObserver = (function (_super) {
inherits(ScheduledObserver, _super);
function ScheduledObserver(scheduler, observer) {
_super.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
/** @private */
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
/** @private */
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
/** @private */
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
/** @private */
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
/** @private */
ScheduledObserver.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* var res = Rx.Observable.fromArray([1,2,3]);
* var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0;
return scheduler.scheduleRecursive(function (self) {
if (count < array.length) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
if (repeatCount == null) {
repeatCount = -1;
}
return observableReturn(value, scheduler).repeat(repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwException' for browsers <IE9.
*
* @example
* var res = Rx.Observable.throwException(new Error('Error'));
* var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout);
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) {
if (typeof handlerOrSecond === 'function') {
return observableCatchHandler(this, handlerOrSecond);
}
return observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable['catch'] = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(args[i].subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') {
return observableMerge(this, maxConcurrentOrOther);
}
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0,
group = new CompositeDisposable(),
isStopped = false,
q = [],
subscribe = function (xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
var s;
group.remove(subscription);
if (q.length > 0) {
s = q.shift();
subscribe(s);
} else {
activeCount--;
if (isStopped && activeCount === 0) {
observer.onCompleted();
}
}
}));
};
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
if (activeCount === 0) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(function (x) {
observer.onNext(x);
}, observer.onError.bind(observer), function () {
group.remove(innerSubscription);
if (isStopped && group.length === 1) {
observer.onCompleted();
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (group.length === 1) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
if (isOpen) {
observer.onNext(left);
}
}, observer.onError.bind(observer), function () {
if (isOpen) {
observer.onCompleted();
}
}));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
d.setDisposable(innerSource.subscribe(function (x) {
if (latest === id) {
observer.onNext(x);
}
}, function (e) {
if (latest === id) {
observer.onError(e);
}
}, function () {
if (latest === id) {
hasLatest = false;
if (isStopped) {
observer.onCompleted();
}
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (!hasLatest) {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
var next = function (i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0),
first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
queues[qIdx] = [];
}
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(observer);
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
*
* @example
* var res = observable.doAction(observer);
* var res = observable.doAction(onNext);
* var res = observable.doAction(onNext, onError);
* var res = observable.doAction(onNext, onError, onCompleted);
* @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (exception) {
if (!onError) {
observer.onError(exception);
} else {
try {
onError(exception);
} catch (e) {
observer.onError(e);
}
observer.onError(exception);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* var res = observable.finallyAction(function () { console.log('sequence ended'; });
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = source.subscribe(observer);
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* var res = repeated = source.repeat();
* var res = repeated = source.repeat(42);
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(42);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
try {
if (!hasValue) {
hasValue = true;
}
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
if (!hasValue && hasSeed) {
observer.onNext(seed);
}
observer.onCompleted();
}
);
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
observer.onNext(q.shift());
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
*
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
*
* @memberOf Observable#
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && 'now' in Object(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue.
*
* @example
* var res = source.takeLast(5);
* var res = source.takeLast(5, Rx.Scheduler.timeout);
*
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count, scheduler) {
return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); });
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
q.shift();
}
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var result;
try {
result = selector.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
function selectMany(selector) {
return this.select(selector).mergeObservable();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) {
if (resultSelector) {
return this.selectMany(function (x) {
return selector(x).select(function (y) {
return resultSelector(x, y);
});
});
}
if (typeof selector === 'function') {
return selectMany.call(this, selector);
}
return selectMany.call(this, function () {
return selector;
});
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
if (running) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
if (count === 0) {
return observableEmpty(scheduler);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining > 0) {
remaining--;
observer.onNext(x);
if (remaining === 0) {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
*
* @example
* var res = source.takeWhile(function (value) { return value < 10; });
* var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, scheduler, context, selector) {
scheduler || (scheduler = timeoutScheduler);
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
function handler(e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
} else {
if (results.length === 1) {
results = results[0];
}
}
observer.onNext(results);
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
});
});
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, scheduler, context, selector) {
scheduler || (scheduler = timeoutScheduler);
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var results = slice.call(arguments, 1);
if (selector) {
try {
results = selector(results);
} catch (e) {
observer.onError(e);
return;
}
} else {
if (results.length === 1) {
results = results[0];
}
}
observer.onNext(results);
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
});
});
};
};
function fixEvent(event) {
var stopPropagation = function () {
this.cancelBubble = true;
};
var preventDefault = function () {
this.bubbledKeyCode = this.keyCode;
if (this.ctrlKey) {
try {
this.keyCode = 0;
} catch (e) { }
}
this.defaultPrevented = true;
this.returnValue = false;
this.modified = true;
};
event || (event = window.event);
if (!event.target) {
event.target = event.target || event.srcElement;
if (event.type == 'mouseover') {
event.relatedTarget = event.fromElement;
}
if (event.type == 'mouseout') {
event.relatedTarget = event.toElement;
}
// Adding stopPropogation and preventDefault to IE
if (!event.stopPropagation){
event.stopPropagation = stopPropagation;
event.preventDefault = preventDefault;
}
// Normalize key events
switch(event.type){
case 'keypress':
var c = ('charCode' in event ? event.charCode : event.keyCode);
if (c == 10) {
c = 0;
event.keyCode = 13;
} else if (c == 13 || c == 27) {
c = 0;
} else if (c == 3) {
c = 99;
}
event.charCode = c;
event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : '';
break;
}
}
return event;
}
function createListener (element, name, handler) {
// Node.js specific
if (element.addListener) {
element.addListener(name, handler);
return disposableCreate(function () {
element.removeListener(name, handler);
});
}
// Standards compliant
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
} else if (element.attachEvent) {
// IE Specific
var innerHandler = function (event) {
handler(fixEvent(event));
};
element.attachEvent('on' + name, innerHandler);
return disposableCreate(function () {
element.detachEvent('on' + name, innerHandler);
});
} else {
// Level 1 DOM Events
element['on' + name] = handler;
return disposableCreate(function () {
element['on' + name] = null;
});
}
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (el && el.length) {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el[i], eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} A Promises A+ implementation instance.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
Observable.fromPromise = function (promise) {
return new AnonymousObservable(function (observer) {
promise.then(
function (value) {
observer.onNext(value);
observer.onCompleted();
},
function (reason) {
observer.onError(reason);
});
});
};
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return !selector ?
this.multicast(new Subject()) :
this.multicast(function () {
return new Subject();
}, selector);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.share();
*
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish(null).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return !selector ?
this.multicast(new AsyncSubject()) :
this.multicast(function () {
return new AsyncSubject();
}, selector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareValue(42);
*
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).
refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return !selector ?
this.multicast(new ReplaySubject(bufferSize, window, scheduler)) :
this.multicast(function () {
return new ReplaySubject(bufferSize, window, scheduler);
}, selector);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
/** @private */
var ConnectableObservable = Rx.ConnectableObservable = (function (_super) {
inherits(ConnectableObservable, _super);
/**
* @constructor
* @private
*/
function ConnectableObservable(source, subject) {
var state = {
subject: subject,
source: source.asObservable(),
hasSubscription: false,
subscription: null
};
this.connect = function () {
if (!state.hasSubscription) {
state.hasSubscription = true;
state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () {
state.hasSubscription = false;
}));
}
return state.subscription;
};
function subscribe(observer) {
return state.subject.subscribe(observer);
}
_super.call(this, subscribe);
}
/**
* @private
* @memberOf ConnectableObservable
*/
ConnectableObservable.prototype.connect = function () { return this.connect(); };
/**
* @private
* @memberOf ConnectableObservable
*/
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription = null, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect, subscription;
count++;
shouldConnect = count === 1;
subscription = source.subscribe(observer);
if (shouldConnect) {
connectableSubscription = source.connect();
}
return disposableCreate(function () {
subscription.dispose();
count--;
if (count === 0) {
connectableSubscription.dispose();
}
});
});
};
return ConnectableObservable;
}(Observable));
function observableTimerTimeSpan(dueTime, scheduler) {
var d = normalizeTime(dueTime);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(d, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
if (dueTime === period) {
return new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
});
}
return observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return observableTimerTimeSpanAndPeriod(period, period, scheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
*
* @example
* var res = Rx.Observable.timer(5000);
* var res = Rx.Observable.timer(5000, 1000);
* var res = Rx.Observable.timer(5000, Rx.Scheduler.timeout);
* var res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout);
*
* @param {Number} dueTime Relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
scheduler || (scheduler = timeoutScheduler);
if (typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (typeof periodOrScheduler === 'object' && 'now' in periodOrScheduler) {
scheduler = periodOrScheduler;
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* var res = Rx.Observable.delay(5000);
* var res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
*
* @example
* 1 - res = source.throttle(5000); // 5 seconds
* 2 - res = source.throttle(5000, scheduler);
*
* @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttle = function (dueTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); })
};
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return observableDefer(function () {
var last = scheduler.now();
return source.select(function (x) {
var now = scheduler.now(), span = now - last;
last = now;
return {
value: x,
interval: span
};
});
});
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
scheduler || (scheduler = timeoutScheduler);
return this.select(function (x) {
return {
value: x,
timestamp: scheduler.now()
};
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
if (atEnd) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
});
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = function (intervalOrSampler, scheduler) {
scheduler || (scheduler = timeoutScheduler);
if (typeof intervalOrSampler === 'number') {
return sampleObservable(this, observableinterval(intervalOrSampler, scheduler));
}
return sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
*
* @example
* 1 - res = source.timeout(new Date()); // As a date
* 2 - res = source.timeout(5000); // 5 seconds
* 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable
* 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable
* 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable
* 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable
*
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
var schedulerMethod, source = this;
other || (other = observableThrow(new Error('Timeout')));
scheduler || (scheduler = timeoutScheduler);
if (dueTime instanceof Date) {
schedulerMethod = function (dt, action) {
scheduler.scheduleWithAbsolute(dt, action);
};
} else {
schedulerMethod = function (dt, action) {
scheduler.scheduleWithRelative(dt, action);
};
}
return new AnonymousObservable(function (observer) {
var createTimer,
id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
createTimer = function () {
var myId = id;
timer.setDisposable(schedulerMethod(dueTime, function () {
switched = id === myId;
var timerWins = switched;
if (timerWins) {
subscription.setDisposable(other.subscribe(observer));
}
}));
};
createTimer();
original.setDisposable(source.subscribe(function (x) {
var onNextWins = !switched;
if (onNextWins) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
var onErrorWins = !switched;
if (onErrorWins) {
id++;
observer.onError(e);
}
}, function () {
var onCompletedWins = !switched;
if (onCompletedWins) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithRelativeTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return 500; }
* );
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithRelative(0, function (self) {
if (hasResult) {
observer.onNext(result);
}
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Time shifts the observable sequence by delaying the subscription.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Number} dueTime Absolute or relative time to perform the subscription at.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); });
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (typeof subscriptionDelay === 'function') {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, done = function () {
if (atEnd && delays.length === 0) {
observer.onCompleted();
}
}, subscription = new SerialDisposable(), start = function () {
subscription.setDisposable(source.subscribe(function (x) {
var delay;
try {
delay = selector(x);
} catch (error) {
observer.onError(error);
return;
}
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(function () {
observer.onNext(x);
delays.remove(d);
done();
}, observer.onError.bind(observer), function () {
observer.onNext(x);
delays.remove(d);
done();
}));
}, observer.onError.bind(observer), function () {
atEnd = true;
subscription.dispose();
done();
}));
};
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(function () {
start();
}, observer.onError.bind(observer), function () { start(); }));
}
return new CompositeDisposable(subscription, delays);
});
};
/**
* Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
*
* @example
* 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500));
* 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); });
* 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42));
*
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
var firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false, setTimer = function (timeout) {
var myId = id, timerWins = function () {
return id === myId;
};
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
if (timerWins()) {
subscription.setDisposable(other.subscribe(observer));
}
d.dispose();
}, function (e) {
if (timerWins()) {
observer.onError(e);
}
}, function () {
if (timerWins()) {
subscription.setDisposable(other.subscribe(observer));
}
}));
};
setTimer(firstTimeout);
var observerWins = function () {
var res = !switched;
if (res) {
id++;
}
return res;
};
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(timeout);
}
}, function (e) {
if (observerWins()) {
observer.onError(e);
}
}, function () {
if (observerWins()) {
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); });
*
* @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttleWithSelector = function (throttleDurationSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = throttleDurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
if (hasValue && id === currentid) {
observer.onNext(value);
}
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
if (hasValue && id === currentid) {
observer.onNext(value);
}
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
if (hasValue) {
observer.onNext(value);
}
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
observer.onCompleted();
});
});
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
*
* @example
* 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) {
return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); });
};
/**
* Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastBufferWithTime = function (duration, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now(), res = [];
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) {
res.push(next.value);
}
}
observer.onNext(res);
observer.onCompleted();
});
});
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var t = scheduler.scheduleWithRelative(duration, function () {
observer.onCompleted();
});
return new CompositeDisposable(t, source.subscribe(observer));
});
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false,
t = scheduler.scheduleWithRelative(duration, function () { open = true; }),
d = source.subscribe(function (x) {
if (open) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
return new CompositeDisposable(t, d);
});
};
/**
* Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time>.
*
* @examples
* 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]);
* @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var open = false,
t = scheduler.scheduleWithAbsolute(startTime, function () { open = true; }),
d = source.subscribe(function (x) {
if (open) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
return new CompositeDisposable(t, d);
});
};
/**
* Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]);
* @param {Number} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
* @param {Scheduler} scheduler Scheduler to run the timer on.
* @returns {Observable} An observable sequence with the elements taken until the specified end time.
*/
observableProto.takeUntilWithTime = function (endTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(scheduler.scheduleWithAbsolute(endTime, function () {
observer.onCompleted();
}), source.subscribe(observer));
});
};
var AnonymousObservable = Rx.Internals.AnonymousObservable = (function (_super) {
inherits(AnonymousObservable, _super);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (typeof subscriber === 'undefined') {
subscriber = disposableEmpty;
} else if (typeof subscriber === 'function') {
subscriber = disposableCreate(subscriber);
}
return subscriber;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
});
} else {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
}
return autoDetachObserver;
}
_super.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, _super);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
_super.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
var v = this.value;
var hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
this.hasValue = true;
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
/** @private */
var AnonymousSubject = (function (_super) {
inherits(AnonymousSubject, _super);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
/**
* @private
* @constructor
*/
function AnonymousSubject(observer, observable) {
_super.call(this, subscribe);
this.observer = observer;
this.observable = observable;
}
addProperties(AnonymousSubject.prototype, Observer, {
/**
* @private
* @memberOf AnonymousSubject#
*/
onCompleted: function () {
this.observer.onCompleted();
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onError: function (exception) {
this.observer.onError(exception);
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
if (ex) {
observer.onError(ex);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, _super);
/**
* @constructor
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
_super.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.exception = null;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (_super) {
function RemovableDisposable (subject, observer) {
this.subject = subject;
this.observer = observer;
};
RemovableDisposable.prototype.dispose = function () {
this.observer.dispose();
if (!this.subject.isDisposed) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
}
};
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = new RemovableDisposable(this, so);
checkDisposed.call(this);
this._trim(this.scheduler.now());
this.observers.push(so);
var n = this.q.length;
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
n++;
so.onError(this.error);
} else if (this.isStopped) {
n++;
so.onCompleted();
}
so.ensureActive(n);
return subscription;
}
inherits(ReplaySubject, _super);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;
this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
_super.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/* @private */
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onNext(value);
observer.ensureActive();
}
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onError(error);
observer.ensureActive();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers = [];
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
}.call(this)); |
app/javascript/mastodon/components/gifv.js | musashino205/mastodon | import React from 'react';
import PropTypes from 'prop-types';
export default class GIFV extends React.PureComponent {
static propTypes = {
src: PropTypes.string.isRequired,
alt: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
onClick: PropTypes.func,
};
state = {
loading: true,
};
handleLoadedData = () => {
this.setState({ loading: false });
}
componentWillReceiveProps (nextProps) {
if (nextProps.src !== this.props.src) {
this.setState({ loading: true });
}
}
handleClick = e => {
const { onClick } = this.props;
if (onClick) {
e.stopPropagation();
onClick();
}
}
render () {
const { src, width, height, alt } = this.props;
const { loading } = this.state;
return (
<div className='gifv' style={{ position: 'relative' }}>
{loading && (
<canvas
width={width}
height={height}
role='button'
tabIndex='0'
aria-label={alt}
title={alt}
onClick={this.handleClick}
/>
)}
<video
src={src}
role='button'
tabIndex='0'
aria-label={alt}
title={alt}
muted
loop
autoPlay
playsInline
onClick={this.handleClick}
onLoadedData={this.handleLoadedData}
style={{ position: loading ? 'absolute' : 'static', top: 0, left: 0 }}
/>
</div>
);
}
}
|
src/components/Datepicker/Date.js | wiki1024/sam-bs | import React from 'react'
import classnames from 'classnames'
const Date = (props) => {
let {id, date, month, selectDate, selected} = props
let classes = classnames('date', {
'current': date.month() === month,
'future': date.month() > month,
'past': date.month() < month,
'selected': (date.date() === selected.date() && date.month() === selected.month() && date.year() === selected.year()),
})
return (
<div
className={classes}
onClick={ (e)=> { selectDate({id:id,val:date});e.stopPropagation() } }>
{date.date()}
</div>
)
}
export default Date |
ajax/libs/rxjs/2.1.2/rx.js | xissy/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
(function (window, undefined) {
var freeExports = typeof exports == 'object' && exports &&
(typeof global == 'object' && global && global == global.global && (window = global), exports);
/**
* @name Rx
* @type Object
*/
var Rx = { Internals: {} };
// Defaults
function noop() { }
function identity(x) { return x; }
function defaultNow() { return new Date().getTime(); }
function defaultComparer(x, y) { return x === y; }
function defaultSubComparer(x, y) { return x - y; }
function defaultKeySerializer(x) { return x.toString(); }
function defaultError(err) { throw err; }
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() {
if (this.isDisposed) {
throw new Error(objectDisposed);
}
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.Internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.Internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.Internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Utilities
if (!Function.prototype.bind) {
Function.prototype.bind = function (that) {
var target = this,
args = slice.call(arguments, 1);
var bound = function () {
if (this instanceof bound) {
function F() { }
F.prototype = target.prototype;
var self = new F();
var result = target.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(that, args.concat(slice.call(arguments)));
}
};
return bound;
};
}
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = Object(this),
self = splitString && {}.toString.call(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if ({}.toString.call(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = Object(this),
self = splitString && {}.toString.call(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
if ({}.toString.call(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, object);
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (predicate) {
var results = [], item, t = new Object(this);
for (var i = 0, len = t.length >>> 0; i < len; i++) {
item = t[i];
if (i in t && predicate.call(arguments[1], item, i, t)) {
results.push(item);
}
}
return results;
};
}
if (!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) == '[object Array]';
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(searchElement) {
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) {
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Collections
var IndexedItem = function (id, value) {
this.id = id;
this.value = value;
};
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
if (c === 0) {
c = this.id - other.id;
}
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) {
return;
}
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) {
return;
}
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
if (index === undefined) {
index = 0;
}
if (index >= this.length || index < 0) {
return;
}
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () {
return this.items[0].value;
};
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
*
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
*
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
*
* @memberOf CompositeDisposable#
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*
* @memberOf CompositeDisposable#
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.
*
* @memberOf CompositeDisposable#
*/
CompositeDisposablePrototype.clear = function () {
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
};
/**
* Determines whether the CompositeDisposable contains a specific disposable.
*
* @memberOf CompositeDisposable#
* @param {Mixed} item Disposable to search for.
* @returns {Boolean} true if the disposable was found; otherwise, false.
*/
CompositeDisposablePrototype.contains = function (item) {
return this.disposables.indexOf(item) !== -1;
};
/**
* Converts the existing CompositeDisposable to an array of disposables
*
* @memberOf CompositeDisposable#
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action;
};
/**
* Performs the task of cleaning up resources.
*
* @memberOf Disposable#
*/
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
*
* @static
* @memberOf Disposable
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*
* @static
* @memberOf Disposable
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
* If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error.
*
* @constructor
*/
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
this.isDisposed = false;
this.current = null;
};
var SingleAssignmentDisposablePrototype = SingleAssignmentDisposable.prototype;
/**
* Gets or sets the underlying disposable. After disposal, the result of getting this method is undefined.
*
* @memberOf SingleAssignmentDisposable#
* @param {Disposable} [value] The new underlying disposable.
* @returns {Disposable} The underlying disposable.
*/
SingleAssignmentDisposablePrototype.disposable = function (value) {
return !value ? this.getDisposable() : this.setDisposable(value);
};
/**
* Gets the underlying disposable. After disposal, the result of getting this method is undefined.
*
* @memberOf SingleAssignmentDisposable#
* @returns {Disposable} The underlying disposable.
*/
SingleAssignmentDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
*
* @memberOf SingleAssignmentDisposable#
* @param {Disposable} value The new underlying disposable.
*/
SingleAssignmentDisposablePrototype.setDisposable = function (value) {
if (this.current) {
throw new Error('Disposable has already been assigned');
}
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
this.current = value;
}
if (shouldDispose && value) {
value.dispose();
}
};
/**
* Disposes the underlying disposable.
*
* @memberOf SingleAssignmentDisposable#
*/
SingleAssignmentDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
if (old) {
old.dispose();
}
};
/**
* Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
*
* @constructor
*/
var SerialDisposable = Rx.SerialDisposable = function () {
this.isDisposed = false;
this.current = null;
};
/**
* Gets the underlying disposable.
* @return The underlying disposable</returns>
*/
SerialDisposable.prototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
*
* @memberOf SerialDisposable#
* @param {Disposable} value The new underlying disposable.
*/
SerialDisposable.prototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
if (old) {
old.dispose();
}
if (shouldDispose && value) {
value.dispose();
}
};
/**
* Gets or sets the underlying disposable.
* If the SerialDisposable has already been disposed, assignment to this property causes immediate disposal of the given disposable object. Assigning this property disposes the previous disposable object.
*
* @memberOf SerialDisposable#
* @param {Disposable} [value] The new underlying disposable.
* @returns {Disposable} The underlying disposable.
*/
SerialDisposable.prototype.disposable = function (value) {
if (!value) {
return this.getDisposable();
} else {
this.setDisposable(value);
}
};
/**
* Disposes the underlying disposable as well as all future replacements.
*
* @memberOf SerialDisposable#
*/
SerialDisposable.prototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
if (old) {
old.dispose();
}
};
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
/**
* @constructor
* @private
*/
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
/** @private */
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
*
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*
* @memberOf RefCountDisposable#
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
*
* @memberOf RefCountDisposable#
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.H
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
/**
* @constructor
* @private
*/
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler, this.disposable = disposable, this.isDisposed = false;
}
/**
* @private
* @memberOf ScheduledDisposable#
*/
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
/**
* @private
* @constructor
*/
function ScheduledItem(scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
/**
* @private
* @memberOf ScheduledItem#
*/
ScheduledItem.prototype.invoke = function () {
this.disposable.disposable(this.invokeCore());
};
/**
* @private
* @memberOf ScheduledItem#
*/
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
/**
* @private
* @memberOf ScheduledItem#
*/
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
/**
* @private
* @memberOf ScheduledItem#
*/
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
/**
* @constructor
* @private
*/
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
*
* @memberOf Scheduler#
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchException = function (handler) {
return new CatchScheduler(this, handler);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
*
* @memberOf Scheduler#
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, function () {
action();
});
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
*
* @memberOf Scheduler#
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodicWithState = function (state, period, action) {
var s = state, id = window.setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
window.clearInterval(id);
});
};
/**
* Schedules an action to be executed.
*
* @memberOf Scheduler#
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
*
* @memberOf Scheduler#
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
*
* @memberOf Scheduler#
* @param {Function} action Action to execute.
* @param {Number}dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
*
* @memberOf Scheduler#
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
*
* @memberOf Scheduler#
* @param {Function} action Action to execute.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
*
* @memberOf Scheduler#
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/**
* Schedules an action to be executed recursively.
*
* @memberOf Scheduler#
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () {
self(_action);
});
});
};
/**
* Schedules an action to be executed recursively.
*
* @memberOf Scheduler#
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, function (s, p) {
return invokeRecImmediate(s, p);
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
*
* @memberOf Scheduler
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
*
* @memberOf Scheduler
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
*
* @memberOf Scheduler
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
*
* @memberOf Scheduler
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
*
* @static
* @memberOf Scheduler
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
if (timeSpan < 0) {
timeSpan = 0;
}
return timeSpan;
};
return Scheduler;
}());
var schedulerNoBlockError = 'Scheduler is not allowed to block the thread';
/**
* Gets a scheduler that schedules work immediately on the current thread.
*
* @memberOf Scheduler
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) {
return action(this, state);
}
function scheduleRelative(state, dueTime, action) {
if (dueTime > 0) throw new Error(schedulerNoBlockError);
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
/**
* @private
* @constructor
*/
function Trampoline() {
queue = new PriorityQueue(4);
}
/**
* @private
* @memberOf Trampoline
*/
Trampoline.prototype.dispose = function () {
queue = null;
};
/**
* @private
* @memberOf Trampoline
*/
Trampoline.prototype.run = function () {
var item;
while (queue.length > 0) {
item = queue.dequeue();
if (!item.isCancelled()) {
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
};
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt),
t;
if (!queue) {
t = new Trampoline();
try {
queue.enqueue(si);
t.run();
} catch (e) {
throw e;
} finally {
t.dispose();
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return queue === null; };
currentScheduler.ensureTrampoline = function (action) {
if (queue === null) {
return this.schedule(action);
} else {
return action();
}
};
return currentScheduler;
}());
/**
* @private
*/
var SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
/**
* @constructor
* @private
*/
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (_super) {
function localNow() {
return this.toDateTimeOffset(this.clock);
}
function scheduleNow(state, action) {
return this.scheduleAbsoluteWithState(state, this.clock, action);
}
function scheduleRelative(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action);
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
inherits(VirtualTimeScheduler, _super);
/**
* Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function VirtualTimeScheduler(initialClock, comparer) {
this.clock = initialClock;
this.comparer = comparer;
this.isEnabled = false;
this.queue = new PriorityQueue(1024);
_super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
*
* @memberOf VirtualTimeScheduler#
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) {
var s = new SchedulePeriodicRecursive(this, state, period, action);
return s.start();
};
/**
* Schedules an action to be executed after dueTime.
*
* @memberOf VirtualTimeScheduler#
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) {
var runAt = this.add(this.clock, dueTime);
return this.scheduleAbsoluteWithState(state, runAt, action);
};
/**
* Schedules an action to be executed at dueTime.
*
* @memberOf VirtualTimeScheduler#
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) {
return this.scheduleRelativeWithState(action, dueTime, invokeAction);
};
/**
* Starts the virtual time scheduler.
*
* @memberOf VirtualTimeScheduler#
*/
VirtualTimeSchedulerPrototype.start = function () {
var next;
if (!this.isEnabled) {
this.isEnabled = true;
do {
next = this.getNext();
if (next !== null) {
if (this.comparer(next.dueTime, this.clock) > 0) {
this.clock = next.dueTime;
}
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
}
};
/**
* Stops the virtual time scheduler.
*
* @memberOf VirtualTimeScheduler#
*/
VirtualTimeSchedulerPrototype.stop = function () {
this.isEnabled = false;
};
/**
* Advances the scheduler's clock to the specified time, running all work till that point.
*
* @param {Number} time Absolute time to advance the scheduler's clock to.
*/
VirtualTimeSchedulerPrototype.advanceTo = function (time) {
var next;
var dueToClock = this.comparer(this.clock, time);
if (this.comparer(this.clock, time) > 0) {
throw new Error(argumentOutOfRange);
}
if (dueToClock === 0) {
return;
}
if (!this.isEnabled) {
this.isEnabled = true;
do {
next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
if (this.comparer(next.dueTime, this.clock) > 0) {
this.clock = next.dueTime;
}
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled)
this.clock = time;
}
};
/**
* Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
*
* @memberOf VirtualTimeScheduler#
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time);
var dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) {
throw new Error(argumentOutOfRange);
}
if (dueToClock === 0) {
return;
}
return this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
*
* @memberOf VirtualTimeScheduler#
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.sleep = function (time) {
var dt = this.add(this.clock, time);
if (this.comparer(this.clock, dt) >= 0) {
throw new Error(argumentOutOfRange);
}
this.clock = dt;
};
/**
* Gets the next scheduled item to be executed.
*
* @memberOf VirtualTimeScheduler#
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
var next;
while (this.queue.length > 0) {
next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
*
* @memberOf VirtualTimeScheduler#
* @param {Scheduler} scheduler Scheduler to execute the action on.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) {
return this.scheduleAbsoluteWithState(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
*
* @memberOf VirtualTimeScheduler#
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) {
var self = this,
run = function (scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
},
si = new ScheduledItem(self, state, run, dueTime, self.comparer);
self.queue.enqueue(si);
return si.disposable;
}
return VirtualTimeScheduler;
}(Scheduler));
/** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
Rx.HistoricalScheduler = (function (_super) {
inherits(HistoricalScheduler, _super);
/**
* Creates a new historical scheduler with the specified initial clock value.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function HistoricalScheduler(initialClock, comparer) {
var clock = initialClock == null ? 0 : initialClock;
var cmp = comparer || defaultSubComparer;
_super.call(this, clock, cmp);
}
var HistoricalSchedulerProto = HistoricalScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
*
* @memberOf HistoricalScheduler
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
HistoricalSchedulerProto.add = function (absolute, relative) {
return absolute + relative;
};
/**
* @private
* @memberOf HistoricalScheduler
*/
HistoricalSchedulerProto.toDateTimeOffset = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
*
* @memberOf HistoricalScheduler
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
HistoricalSchedulerProto.toRelative = function (timeSpan) {
return timeSpan;
};
return HistoricalScheduler;
}(Rx.VirtualTimeScheduler));
var scheduleMethod, clearMethod = noop;
(function () {
function postMessageSupported () {
// Ensure not in a worker
if (!window.postMessage || window.importScripts) { return false; }
var isAsync = false,
oldHandler = window.onmessage;
// Test for async
window.onmessage = function () { isAsync = true; };
window.postMessage('','*');
window.onmessage = oldHandler;
return isAsync;
}
if (typeof window.process !== 'undefined' && Object.prototype.toString.call(window.process) === '[object process]') {
scheduleMethod = window.process.nextTick;
} else if (typeof window.setImmediate === 'function') {
scheduleMethod = window.setImmediate;
clearMethod = window.clearImmediate;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (window.addEventListener) {
window.addEventListener('message', onGlobalPostMessage, false);
} else {
window.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
window.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!window.MessageChannel) {
var channel = new window.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in window && 'onreadystatechange' in window.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = window.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
window.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return window.setTimeout(action, 0); };
clearMethod = window.clearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*
* @memberOf Scheduler
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = window.setTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
window.clearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/** @private */
var CatchScheduler = (function (_super) {
function localNow() {
return this._scheduler.now();
}
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, _super);
/** @private */
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
_super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
/** @private */
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
/** @private */
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
/** @private */
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (!this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
/** @private */
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
var NotificationPrototype = Notification.prototype;
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) {
if (arguments.length === 1 && typeof observerOrOnNext === 'object') {
return this._acceptObservable(observerOrOnNext);
}
return this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notification
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
NotificationPrototype.toObservable = function (scheduler) {
var notification = this;
scheduler = scheduler || immediateScheduler;
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
if (notification.kind === 'N') {
observer.onCompleted();
}
});
});
};
NotificationPrototype.equals = function (other) {
var otherString = other == null ? '' : other.toString();
return this.toString() === otherString;
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
*
* @static
* @memberOf Notification
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) {
return onNext(this.value);
}
function _acceptObservable(observer) {
return observer.onNext(this.value);
}
function toString () {
return 'OnNext(' + this.value + ')';
}
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept.bind(notification);
notification._acceptObservable = _acceptObservable.bind(notification);
notification.toString = toString.bind(notification);
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
*
* @static s
* @memberOf Notification
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) {
return onError(this.exception);
}
function _acceptObservable(observer) {
return observer.onError(this.exception);
}
function toString () {
return 'OnError(' + this.exception + ')';
}
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept.bind(notification);
notification._acceptObservable = _acceptObservable.bind(notification);
notification.toString = toString.bind(notification);
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
*
* @static
* @memberOf Notification
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) {
return onCompleted();
}
function _acceptObservable(observer) {
return observer.onCompleted();
}
function toString () {
return 'OnCompleted()';
}
return function () {
var notification = new Notification('C');
notification._accept = _accept.bind(notification);
notification._acceptObservable = _acceptObservable.bind(notification);
notification.toString = toString.bind(notification);
return notification;
};
}());
/**
* @constructor
* @private
*/
var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent, dispose) {
this.moveNext = moveNext;
this.getCurrent = getCurrent;
this.dispose = dispose;
};
/**
* @static
* @memberOf Enumerator
* @private
*/
var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent, dispose) {
var done = false;
dispose || (dispose = noop);
return new Enumerator(function () {
if (done) {
return false;
}
var result = moveNext();
if (!result) {
done = true;
dispose();
}
return result;
}, function () { return getCurrent(); }, function () {
if (!done) {
dispose();
done = true;
}
});
};
/** @private */
var Enumerable = Rx.Internals.Enumerable = (function () {
/**
* @constructor
* @private
*/
function Enumerable(getEnumerator) {
this.getEnumerator = getEnumerator;
}
/**
* @private
* @memberOf Enumerable#
*/
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e = sources.getEnumerator(), isDisposed = false, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, ex, hasNext = false;
if (!isDisposed) {
try {
hasNext = e.moveNext();
if (hasNext) {
current = e.getCurrent();
} else {
e.dispose();
}
} catch (exception) {
ex = exception;
e.dispose();
}
} else {
return;
}
if (ex) {
observer.onError(ex);
return;
}
if (!hasNext) {
observer.onCompleted();
return;
}
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
e.dispose();
}));
});
};
/**
* @private
* @memberOf Enumerable#
*/
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e = sources.getEnumerator(), isDisposed = false, lastException;
var subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, ex, hasNext;
hasNext = false;
if (!isDisposed) {
try {
hasNext = e.moveNext();
if (hasNext) {
current = e.getCurrent();
}
} catch (exception) {
ex = exception;
}
} else {
return;
}
if (ex) {
observer.onError(ex);
return;
}
if (!hasNext) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
return Enumerable;
}());
/**
* @static
* @private
* @memberOf Enumerable
*/
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount === undefined) {
repeatCount = -1;
}
return new Enumerable(function () {
var current, left = repeatCount;
return enumeratorCreate(function () {
if (left === 0) {
return false;
}
if (left > 0) {
left--;
}
current = value;
return true;
}, function () { return current; });
});
};
/**
* @static
* @private
* @memberOf Enumerable
*/
var enumerableFor = Enumerable.forEach = function (source, selector) {
selector || (selector = identity);
return new Enumerable(function () {
var current, index = -1;
return enumeratorCreate(
function () {
if (++index < source.length) {
current = selector(source[index], index);
return true;
}
return false;
},
function () { return current; }
);
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
*
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
*
* @static
* @memberOf Observer
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler) {
return new AnonymousObserver(function (x) {
return handler(notificationCreateOnNext(x));
}, function (exception) {
return handler(notificationCreateOnError(exception));
}, function () {
return handler(notificationCreateOnCompleted());
});
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.Internals.AbstractObserver = (function (_super) {
inherits(AbstractObserver, _super);
/**
* Creates a new observer in a non-stopped state.
*
* @constructor
*/
function AbstractObserver() {
this.isStopped = false;
_super.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
*
* @memberOf AbstractObserver
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) {
this.next(value);
}
};
/**
* Notifies the observer that an exception has occurred.
*
* @memberOf AbstractObserver
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function () {
if (!this.isStopped) {
this.isStopped = true;
this.error(true);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
inherits(AnonymousObserver, _super);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
*
* @constructor
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
*
* @memberOf AnonymousObserver
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
*
* @memberOf AnonymousObserver
* @param {Any{ error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*
* @memberOf AnonymousObserver
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (_super) {
inherits(CheckedObserver, _super);
function CheckedObserver(observer) {
_super.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
try {
this._observer.onNext(value);
} catch (e) {
throw e;
} finally {
this._state = 0;
}
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
try {
this._observer.onError(err);
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
try {
this._observer.onCompleted();
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
/** @private */
var ScheduledObserver = Rx.Internals.ScheduledObserver = (function (_super) {
inherits(ScheduledObserver, _super);
function ScheduledObserver(scheduler, observer) {
_super.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
/** @private */
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
/** @private */
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
/** @private */
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
/** @private */
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
/** @private */
ScheduledObserver.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/** @private */
var ObserveOnObserver = (function (_super) {
inherits(ObserveOnObserver, _super);
/** @private */
function ObserveOnObserver() {
_super.apply(this, arguments);
}
/** @private */
ObserveOnObserver.prototype.next = function (value) {
_super.prototype.next.call(this, value);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.error = function (e) {
_super.prototype.error.call(this, e);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.completed = function () {
_super.prototype.completed.call(this);
this.ensureActive();
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
/**
* @constructor
* @private
*/
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
observableProto.finalValue = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var hasValue = false, value;
return source.subscribe(function (x) {
hasValue = true;
value = x;
}, observer.onError.bind(observer), function () {
if (!hasValue) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
};
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber;
if (typeof observerOrOnNext === 'object') {
subscriber = observerOrOnNext;
} else {
subscriber = observerCreate(observerOrOnNext, onError, onCompleted);
}
return this._subscribe(subscriber);
};
/**
* Creates a list from an observable sequence.
*
* @memberOf Observable
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
function accumulator(list, i) {
var newList = list.slice(0);
newList.push(i);
return newList;
}
return this.scan([], accumulator).startWith([]).finalValue();
}
return Observable;
})();
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* 1 - res = Rx.Observable.start(function () { console.log('hello'); });
* 2 - res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* 2 - res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
*
* @param {Function} func Function to run asynchronously.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*
* Remarks
* * The function is called immediately, not during the subscription of the resulting sequence.
* * Multiple subscriptions to the resulting sequence can observe the function's result.
*/
Observable.start = function (func, scheduler, context) {
return observableToAsync(func, scheduler)();
};
/**
* Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
*
* @example
* 1 - res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3);
* 2 - res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3);
* 2 - res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello');
*
* @param function Function to convert to an asynchronous function.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Function} Asynchronous function.
*/
var observableToAsync = Observable.toAsync = function (func, scheduler, context) {
scheduler || (scheduler = timeoutScheduler);
return function () {
var args = slice.call(arguments, 0), subject = new AsyncSubject();
scheduler.schedule(function () {
var result;
try {
result = func.apply(context, args);
} catch (e) {
subject.onError(e);
return;
}
subject.onNext(result);
subject.onCompleted();
});
return subject.asObservable();
};
};
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
});
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* 1 - res = Rx.Observable.create(function (observer) { return function () { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = function (subscribe) {
return new AnonymousObservable(function (o) {
return disposableCreate(subscribe(o));
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* 1 - res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* @static
* @memberOf Observable
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* 1 - res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @static
* @memberOf Observable
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* 1 - res = Rx.Observable.empty();
* 2 - res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* 1 - res = Rx.Observable.fromArray([1,2,3]);
* 2 - res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0;
return scheduler.scheduleRecursive(function (self) {
if (count < array.length) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* 1 - res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* 2 - res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
*
* @static
* @memberOf Observable
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* 1 - res = Rx.Observable.range(0, 10);
* 2 - res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* 1 - res = Rx.Observable.repeat(42);
* 2 - res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
if (repeatCount == undefined) {
repeatCount = -1;
}
return observableReturn(value, scheduler).repeat(repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
*
* @example
* 1 - res = Rx.Observable.returnValue(42);
* 2 - res = Rx.Observable.returnValue(42, Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable.returnValue = function (value, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single OnError message.
*
* @example
* 1 - res = Rx.Observable.throwException(new Error('Error'));
* 2 - res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout);
* @static
* @memberOf Observable
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable.throwException = function (exception, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
*
* @example
* 1 - res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; });
* @static
* @memberOf Observable
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
if (resource) {
disposable = resource;
}
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence that reacts first.
*
* @memberOf Observable#
* @param {Observable} rightSource Second observable sequence.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence that reacts first.
*
* @example
* E.g. winner = Rx.Observable.amb(xs, ys, zs);
* @static
* @memberOf Observable
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(),
items = argsOrArray(arguments, 0);
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @memberOf Observable#
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto.catchException = function (handlerOrSecond) {
if (typeof handlerOrSecond === 'function') {
return observableCatchHandler(this, handlerOrSecond);
}
return observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @static
* @memberOf Observable
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @memberOf Observable#
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @static
* @memberOf Observable
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(function (x) { return x; }))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(function (x) { return x; })) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(args[i].subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @memberOf Observable#
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @static
* @memberOf Observable
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
*
* @memberOf Observable#
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @memberOf Observable#
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') {
return observableMerge(this, maxConcurrentOrOther);
}
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0,
group = new CompositeDisposable(),
isStopped = false,
q = [],
subscribe = function (xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
var s;
group.remove(subscription);
if (q.length > 0) {
s = q.shift();
subscribe(s);
} else {
activeCount--;
if (isStopped && activeCount === 0) {
observer.onCompleted();
}
}
}));
};
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
if (activeCount === 0) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
*
* @static
* @memberOf Observable
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
*
* @memberOf Observable#
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(function (x) {
observer.onNext(x);
}, observer.onError.bind(observer), function () {
group.remove(innerSubscription);
if (isStopped && group.length === 1) {
observer.onCompleted();
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (group.length === 1) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @memberOf Observable
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) {
throw new Error('Second observable is required');
}
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @static
* @memberOf Observable
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () {
self();
}, function () {
self();
}));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
*
* @memberOf Observable#
* @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
if (isOpen) {
observer.onNext(left);
}
}, observer.onError.bind(observer), function () {
if (isOpen) {
observer.onCompleted();
}
}));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
*
* @memberOf Observable#
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
d.setDisposable(innerSource.subscribe(function (x) {
if (latest === id) {
observer.onNext(x);
}
}, function (e) {
if (latest === id) {
observer.onError(e);
}
}, function () {
if (latest === id) {
hasLatest = false;
if (isStopped) {
observer.onCompleted();
}
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (!hasLatest) {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
*
* @memberOf Observable#
* @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @memberOf Observable#
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
var next = function (i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(function (x) { return x; })) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
*
* @static
* @memberOf Observable
* @param {Array} sources Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function (sources, resultSelector) {
var first = sources[0],
rest = sources.slice(1);
rest.push(resultSelector);
return first.zip.apply(first, rest);
};
/**
* Hides the identity of an observable sequence.
*
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(observer);
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* 1 - xs.bufferWithCount(10);
* 2 - xs.bufferWithCount(10, 1);
*
* @memberOf Observable#
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (skip === undefined) {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
*
* @memberOf Observable#
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* 1 - var obs = observable.distinctUntilChanged();
* 2 - var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* 3 - var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @memberOf Observable#
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
*
* @example
* 1 - observable.doAction(observer);
* 2 - observable.doAction(onNext);
* 3 - observable.doAction(onNext, onError);
* 4 - observable.doAction(onNext, onError, onCompleted);
*
* @memberOf Observable#
* @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (exception) {
if (!onError) {
observer.onError(exception);
} else {
try {
onError(exception);
} catch (e) {
observer.onError(e);
}
observer.onError(exception);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* 1 - obs = observable.finallyAction(function () { console.log('sequence ended'; });
*
* @memberOf Observable#
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = source.subscribe(observer);
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
*
* @memberOf Observable#
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
*
* @memberOf Observable#
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (exception) {
observer.onNext(notificationCreateOnError(exception));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* 1 - repeated = source.repeat();
* 2 - repeated = source.repeat(42);
*
* @memberOf Observable#
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
*
* @example
* 1 - retried = retry.repeat();
* 2 - retried = retry.repeat(42);
*
* @memberOf Observable#
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
*
* 1 - scanned = source.scan(function (acc, x) { return acc + x; });
* 2 - scanned = source.scan(0, function (acc, x) { return acc + x; });
*
* @memberOf Observable#
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var seed, hasSeed = false, accumulator;
if (arguments.length === 2) {
seed = arguments[0];
accumulator = arguments[1];
hasSeed = true;
} else {
accumulator = arguments[0];
}
var source = this;
return observableDefer(function () {
var hasAccumulation = false, accumulation;
return source.select(function (x) {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
return accumulation;
});
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
*
* @memberOf Observable#
* @description
* This operator accumulates a queue with a length enough to store the first <paramref name="count"/> elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
observer.onNext(q.shift());
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
*
* 1 - source.startWith(1, 2, 3);
* 2 - source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
*
* @memberOf Observable#
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (arguments.length > 0 && arguments[0] != null && arguments[0].now !== undefined) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue.
*
* @example
* 1 - obs = source.takeLast(5);
* 2 - obs = source.takeLast(5, Rx.Scheduler.timeout);
*
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
*
* @memberOf Observable#
* @param {Number} count Number of elements to take from the end of the source sequence.
* @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count, scheduler) {
return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); });
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
*
* @memberOf Observable#
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
q.shift();
}
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* 1 - xs.windowWithCount(10);
* 2 - xs.windowWithCount(10, 1);
*
* @memberOf Observable#
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
if (count <= 0) {
throw new Error(argumentOutOfRange);
}
if (skip == null) {
skip = count;
}
if (skip <= 0) {
throw new Error(argumentOutOfRange);
}
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [],
createWindow = function () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
};
createWindow();
m.setDisposable(source.subscribe(function (x) {
var s;
for (var i = 0, len = q.length; i < len; i++) {
q[i].onNext(x);
}
var c = n - count + 1;
if (c >= 0 && c % skip === 0) {
s = q.shift();
s.onCompleted();
}
n++;
if (n % skip === 0) {
createWindow();
}
}, function (exception) {
while (q.length > 0) {
q.shift().onError(exception);
}
observer.onError(exception);
}, function () {
while (q.length > 0) {
q.shift().onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* 1 - obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
if (defaultValue === undefined) {
defaultValue = null;
}
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
}, observer.onError.bind(observer), function () {
if (!found) {
observer.onNext(defaultValue);
}
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* 1 - obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); });
*
* @memberOf Observable#
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, keySerializer) {
var source = this;
keySelector || (keySelector = identity);
keySerializer || (keySerializer = defaultKeySerializer);
return new AnonymousObservable(function (observer) {
var hashSet = {};
return source.subscribe(function (x) {
var key, serializedKey, otherKey, hasMatch = false;
try {
key = keySelector(x);
serializedKey = keySerializer(key);
} catch (exception) {
observer.onError(exception);
return;
}
for (otherKey in hashSet) {
if (serializedKey === otherKey) {
hasMatch = true;
break;
}
}
if (!hasMatch) {
hashSet[serializedKey] = null;
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* 1 - observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
*
* @memberOf Observable#
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector, keySerializer) {
return this.groupByUntil(keySelector, elementSelector, function () {
return observableNever();
}, keySerializer);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function.
* A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
* key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
*
* @example
* 1 - observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
*
* @memberOf Observable#
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} durationSelector A function to signal the expiration of a group.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable}
* A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
* If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
*
*/
observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) {
var source = this;
elementSelector || (elementSelector = identity);
keySerializer || (keySerializer = defaultKeySerializer);
return new AnonymousObservable(function (observer) {
var map = {},
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var duration, durationGroup, element, expire, fireNewMapEntry, group, key, serializedKey, md, writer, w;
try {
key = keySelector(x);
serializedKey = keySerializer(key);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
fireNewMapEntry = false;
try {
writer = map[serializedKey];
if (!writer) {
writer = new Subject();
map[serializedKey] = writer;
fireNewMapEntry = true;
}
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
if (fireNewMapEntry) {
group = new GroupedObservable(key, writer, refCountDisposable);
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
observer.onNext(group);
md = new SingleAssignmentDisposable();
groupDisposable.add(md);
expire = function () {
if (serializedKey in map) {
delete map[serializedKey];
writer.onCompleted();
}
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(noop, function (exn) {
for (w in map) {
map[w].onError(exn);
}
observer.onError(exn);
}, function () {
expire();
}));
}
try {
element = elementSelector(x);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
for (var w in map) {
map[w].onError(ex);
}
observer.onError(ex);
}, function () {
for (var w in map) {
map[w].onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
*
* @example
* source.select(function (value, index) { return value * value + index; });
*
* @memberOf Observable#
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = function (selector, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var result;
try {
result = selector.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
observableProto.map = observableProto.select;
function selectMany(selector) {
return this.select(selector).mergeObservable();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* 1 - source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* 1 - source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* 1 - source.selectMany(Rx.Observable.fromArray([1,2,3]));
*
* @memberOf Observable#
* @param selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) {
if (resultSelector) {
return this.selectMany(function (x) {
return selector(x).select(function (y) {
return resultSelector(x, y);
});
});
}
if (typeof selector === 'function') {
return selectMany.call(this, selector);
}
return selectMany.call(this, function () {
return selector;
});
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
*
* @memberOf Observable#
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* 1 - source.skipWhile(function (value) { return value < 10; });
* 1 - source.skipWhile(function (value, index) { return value < 10 || index < 10; });
*
* @memberOf Observable#
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate(x, i++);
} catch (e) {
observer.onError(e);
return;
}
}
if (running) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* 1 - source.take(5);
* 2 - source.take(0, Rx.Scheduler.timeout);
*
* @memberOf Observable#
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
if (count === 0) {
return observableEmpty(scheduler);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining > 0) {
remaining--;
observer.onNext(x);
if (remaining === 0) {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
*
* @example
* 1 - source.takeWhile(function (value) { return value < 10; });
* 1 - source.takeWhile(function (value, index) { return value < 10 || index < 10; });
*
* @memberOf Observable#
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate(x, i++);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* 1 - source.where(function (value) { return value < 10; });
* 1 - source.where(function (value, index) { return value < 10 || index < 10; });
*
* @memberOf Observable#
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
observableProto.filter = observableProto.where;
/** @private */
var AnonymousObservable = Rx.Internals.AnonymousObservable = (function (_super) {
inherits(AnonymousObservable, _super);
/**
* @private
* @constructor
*/
function AnonymousObservable(subscribe) {
function s(observer) {
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(function () {
try {
autoDetachObserver.disposable(subscribe(autoDetachObserver));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
});
} else {
try {
autoDetachObserver.disposable(subscribe(autoDetachObserver));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
}
return autoDetachObserver;
}
_super.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
/**
* @private
* @constructor
*/
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype
/**
* @private
* @memberOf AutoDetachObserver#
*/
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
/**
* @private
* @memberOf AutoDetachObserver#
*/
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
/**
* @private
* @memberOf AutoDetachObserver#
*/
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
/**
* @private
* @memberOf AutoDetachObserver#
*/
AutoDetachObserverPrototype.disposable = function (value) {
return this.m.disposable(value);
};
/**
* @private
* @memberOf AutoDetachObserver#
*/
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var GroupedObservable = (function (_super) {
inherits(GroupedObservable, _super);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
/**
* @constructor
* @private
*/
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
_super.call(this, subscribe);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new AnonymousObservable(function (observer) {
return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
});
}
return GroupedObservable;
}(Observable));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
*
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
*
* @memberOf ReplaySubject#
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*
* @memberOf ReplaySubject#
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
*
* @memberOf ReplaySubject#
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
*
* @memberOf ReplaySubject#
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*
* @memberOf ReplaySubject#
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
*
* @static
* @memberOf Subject
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
var hv = this.hasValue;
var v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, _super);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
*
* @constructor
*/
function AsyncSubject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.value = null,
this.hasValue = false,
this.observers = [],
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
*
* @memberOf AsyncSubject#
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*
* @memberOf AsyncSubject#
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
var v = this.value;
var hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
*
* @memberOf AsyncSubject#
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
*
* @memberOf AsyncSubject#
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
this.hasValue = true;
}
},
/**
* Unsubscribe all observers and release resources.
*
* @memberOf AsyncSubject#
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
/** @private */
var AnonymousSubject = (function (_super) {
inherits(AnonymousSubject, _super);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
/**
* @private
* @constructor
*/
function AnonymousSubject(observer, observable) {
_super.call(this, subscribe);
this.observer = observer;
this.observable = observable;
}
addProperties(AnonymousSubject.prototype, Observer, {
/**
* @private
* @memberOf AnonymousSubject#
*/
onCompleted: function () {
this.observer.onCompleted();
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onError: function (exception) {
this.observer.onError(exception);
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
// Check for AMD
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
window.Rx = Rx;
return define(function () {
return Rx;
});
} else if (freeExports) {
if (typeof module == 'object' && module && module.exports == freeExports) {
module.exports = Rx;
} else {
freeExports = Rx;
}
} else {
window.Rx = Rx;
}
}(this)); |
src/RadioButton/RadioButtonGroup.spec.js | verdan/material-ui | /* eslint-env mocha */
import React from 'react';
import {assert} from 'chai';
import {shallow} from 'enzyme';
import RadioButtonGroup from './RadioButtonGroup';
import getMuiTheme from '../styles/getMuiTheme';
describe('<RadioButtonGroup />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
describe('initial state', () => {
it('should accept string valueSelected prop and set to state', () => {
const wrapper = shallowWithContext(<RadioButtonGroup name="testGroup" valueSelected={'value'} />);
assert.strictEqual(wrapper.state('selected'), 'value');
});
it('should accept truthy valueSelected prop and set to state', () => {
const wrapper = shallowWithContext(<RadioButtonGroup name="testGroup" valueSelected={true} />);
assert.strictEqual(wrapper.state('selected'), true);
});
it('should accept falsy valueSelected prop and set to state', () => {
const wrapper = shallowWithContext(<RadioButtonGroup name="testGroup" valueSelected={false} />);
assert.strictEqual(wrapper.state('selected'), false);
});
it('should accept string defaultSelected prop and set to state', () => {
const wrapper = shallowWithContext(<RadioButtonGroup name="testGroup" defaultSelected={'value'} />);
assert.strictEqual(wrapper.state('selected'), 'value');
});
it('should accept truthy defaultSelected prop and set to state', () => {
const wrapper = shallowWithContext(<RadioButtonGroup name="testGroup" defaultSelected={true} />);
assert.strictEqual(wrapper.state('selected'), true);
});
it('should accept falsy defaultSelected prop and set to state', () => {
const wrapper = shallowWithContext(<RadioButtonGroup name="testGroup" defaultSelected={false} />);
assert.strictEqual(wrapper.state('selected'), false);
});
});
});
|
src/components/social/container.js | adrienlozano/stephaniewebsite | import React from 'react';
import withSettings from '~/enhancers/with-settings';
const IconsContainer = ({settings, component : Component}) => (<Component icons={ settings.map(x => x.social) }></Component>)
export default withSettings()(IconsContainer); |
src/components/NotFoundPage.js | oded-soffrin/gkm_viewer | import React from 'react';
import { Link } from 'react-router';
const NotFoundPage = () => {
return (
<div>
<h4>
404 Page Not Found
</h4>
<Link to="/"> Go back to homepage </Link>
</div>
);
};
export default NotFoundPage;
|
ajax/libs/video.js/5.0.0-2/video.js | voronianski/cdnjs | /**
* @license
* Video.js 5.0.0-2 <http://videojs.com/>
* Copyright Brightcove, Inc. <https://www.brightcove.com/>
* Available under Apache License Version 2.0
* <https://github.com/videojs/video.js/blob/master/LICENSE>
*
* Includes vtt.js <https://github.com/mozilla/vtt.js>
* Available under Apache License Version 2.0
* <https://github.com/mozilla/vtt.js/blob/master/LICENSE>
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.videojs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
(function (global){
var topLevel = typeof global !== 'undefined' ? global :
typeof window !== 'undefined' ? window : {}
var minDoc = _dereq_('min-document');
if (typeof document !== 'undefined') {
module.exports = document;
} else {
var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
if (!doccy) {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
}
module.exports = doccy;
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"min-document":3}],2:[function(_dereq_,module,exports){
(function (global){
if (typeof window !== "undefined") {
module.exports = window;
} else if (typeof global !== "undefined") {
module.exports = global;
} else if (typeof self !== "undefined"){
module.exports = self;
} else {
module.exports = {};
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],3:[function(_dereq_,module,exports){
},{}],4:[function(_dereq_,module,exports){
module.exports = SafeParseTuple
function SafeParseTuple(obj, reviver) {
var json
var error = null
try {
json = JSON.parse(obj, reviver)
} catch (err) {
error = err
}
return [error, json]
}
},{}],5:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Button2 = _dereq_('./button');
var _Button3 = _interopRequireWildcard(_Button2);
/* Big Play Button
================================================================================ */
/**
* Initial play button. Shows before the video has played. The hiding of the
* big play button is done via CSS and player states.
* @param {Player|Object} player
* @param {Object=} options
* @class
* @constructor
*/
var BigPlayButton = (function (_Button) {
function BigPlayButton() {
_classCallCheck(this, BigPlayButton);
if (_Button != null) {
_Button.apply(this, arguments);
}
}
_inherits(BigPlayButton, _Button);
_createClass(BigPlayButton, [{
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(BigPlayButton.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-big-play-button',
innerHTML: '<span aria-hidden="true"></span>',
'aria-label': 'play video'
});
}
}, {
key: 'handleClick',
value: function handleClick() {
this.player_.play();
}
}]);
return BigPlayButton;
})(_Button3['default']);
_Button3['default'].registerComponent('BigPlayButton', BigPlayButton);
exports['default'] = BigPlayButton;
module.exports = exports['default'];
},{"./button":6}],6:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('./component');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('./lib');
var Lib = _interopRequireWildcard(_import);
var _import2 = _dereq_('./events');
var Events = _interopRequireWildcard(_import2);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
/* Button - Base class for all buttons
================================================================================ */
/**
* Base class for all buttons
* @param {Player|Object} player
* @param {Object=} options
* @class
* @constructor
*/
var Button = (function (_Component) {
function Button(player, options) {
_classCallCheck(this, Button);
_get(Object.getPrototypeOf(Button.prototype), 'constructor', this).call(this, player, options);
this.emitTapEvents();
this.on('tap', this.handleClick);
this.on('click', this.handleClick);
this.on('focus', this.handleFocus);
this.on('blur', this.handleBlur);
}
_inherits(Button, _Component);
_createClass(Button, [{
key: 'createEl',
value: function createEl(type, props) {
// Add standard Aria and Tabindex info
props = Lib.obj.merge({
className: this.buildCSSClass(),
role: 'button',
'aria-live': 'polite', // let the screen reader user know that the text of the button may change
tabIndex: 0
}, props);
var el = _get(Object.getPrototypeOf(Button.prototype), 'createEl', this).call(this, type, props);
// if innerHTML hasn't been overridden (bigPlayButton), add content elements
if (!props.innerHTML) {
this.contentEl_ = Lib.createEl('div', {
className: 'vjs-control-content'
});
this.controlText_ = Lib.createEl('span', {
className: 'vjs-control-text',
innerHTML: this.localize(this.buttonText) || 'Need Text'
});
this.contentEl_.appendChild(this.controlText_);
el.appendChild(this.contentEl_);
}
return el;
}
}, {
key: 'buildCSSClass',
value: function buildCSSClass() {
return 'vjs-control vjs-button ' + _get(Object.getPrototypeOf(Button.prototype), 'buildCSSClass', this).call(this);
}
}, {
key: 'handleClick',
// Click - Override with specific functionality for button
value: function handleClick() {}
}, {
key: 'handleFocus',
// Focus - Add keyboard functionality to element
value: function handleFocus() {
Events.on(_document2['default'], 'keydown', Lib.bind(this, this.handleKeyPress));
}
}, {
key: 'handleKeyPress',
// KeyPress (document level) - Trigger click when keys are pressed
value: function handleKeyPress(event) {
// Check for space bar (32) or enter (13) keys
if (event.which == 32 || event.which == 13) {
event.preventDefault();
this.handleClick();
}
}
}, {
key: 'handleBlur',
// Blur - Remove keyboard triggers
value: function handleBlur() {
Events.off(_document2['default'], 'keydown', Lib.bind(this, this.handleKeyPress));
}
}]);
return Button;
})(_Component3['default']);
_Component3['default'].registerComponent('Button', Button);
exports['default'] = Button;
module.exports = exports['default'];
},{"./component":7,"./events":43,"./lib":46,"global/document":1}],7:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
Object.defineProperty(exports, '__esModule', {
value: true
});
/**
* @fileoverview Player Component - Base class for all UI objects
*
*/
var _import = _dereq_('./lib.js');
var Lib = _interopRequireWildcard(_import);
var _import2 = _dereq_('./util.js');
var VjsUtil = _interopRequireWildcard(_import2);
var _import3 = _dereq_('./events.js');
var Events = _interopRequireWildcard(_import3);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
/**
* Base UI Component class
*
* Components are embeddable UI objects that are represented by both a
* javascript object and an element in the DOM. They can be children of other
* components, and can have many children themselves.
*
* // adding a button to the player
* var button = player.addChild('button');
* button.el(); // -> button element
*
* <div class="video-js">
* <div class="vjs-button">Button</div>
* </div>
*
* Components are also event emitters.
*
* button.on('click', function(){
* console.log('Button Clicked!');
* });
*
* button.trigger('customevent');
*
* @param {Object} player Main Player
* @param {Object=} options
* @class
* @constructor
*/
var Component = (function () {
function Component(player, options, ready) {
_classCallCheck(this, Component);
// The component might be the player itself and we can't pass `this` to super
if (!player && this.play) {
this.player_ = player = this;
} else {
this.player_ = player;
}
// Make a copy of prototype.options_ to protect against overriding global defaults
this.options_ = Lib.obj.copy(this.options_);
// Updated options with supplied options
options = this.options(options);
// Get ID from options or options element if one is supplied
this.id_ = options.id || options.el && options.el.id;
// If there was no ID from the options, generate one
if (!this.id_) {
// Don't require the player ID function in the case of mock players
var id = player.id && player.id() || 'no_player';
this.id_ = '' + id + '_component_' + Lib.guid++;
}
this.name_ = options.name || null;
// Create element if one wasn't provided in options
if (options.el) {
this.el_ = options.el;
} else if (options.createEl !== false) {
this.el_ = this.createEl();
}
this.children_ = [];
this.childIndex_ = {};
this.childNameIndex_ = {};
// Add any child components in options
if (options.initChildren !== false) {
this.initChildren();
}
this.ready(ready);
// Don't want to trigger ready here or it will before init is actually
// finished for all children that run this constructor
if (options.reportTouchActivity !== false) {
this.enableTouchActivity();
}
}
_createClass(Component, [{
key: 'init',
// Temp for ES6 class transition, remove before 5.0
value: function init() {
// console.log('init called on Component');
Component.apply(this, arguments);
}
}, {
key: 'dispose',
/**
* Dispose of the component and all child components
*/
value: function dispose() {
this.trigger({ type: 'dispose', bubbles: false });
// Dispose all children.
if (this.children_) {
for (var i = this.children_.length - 1; i >= 0; i--) {
if (this.children_[i].dispose) {
this.children_[i].dispose();
}
}
}
// Delete child references
this.children_ = null;
this.childIndex_ = null;
this.childNameIndex_ = null;
// Remove all event listeners.
this.off();
// Remove element from DOM
if (this.el_.parentNode) {
this.el_.parentNode.removeChild(this.el_);
}
Lib.removeData(this.el_);
this.el_ = null;
}
}, {
key: 'player',
/**
* Return the component's player
*
* @return {Player}
*/
value: function player() {
return this.player_;
}
}, {
key: 'options',
/**
* Deep merge of options objects
*
* Whenever a property is an object on both options objects
* the two properties will be merged using Lib.obj.deepMerge.
*
* This is used for merging options for child components. We
* want it to be easy to override individual options on a child
* component without having to rewrite all the other default options.
*
* Parent.prototype.options_ = {
* children: {
* 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' },
* 'childTwo': {},
* 'childThree': {}
* }
* }
* newOptions = {
* children: {
* 'childOne': { 'foo': 'baz', 'abc': '123' }
* 'childTwo': null,
* 'childFour': {}
* }
* }
*
* this.options(newOptions);
*
* RESULT
*
* {
* children: {
* 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' },
* 'childTwo': null, // Disabled. Won't be initialized.
* 'childThree': {},
* 'childFour': {}
* }
* }
*
* @param {Object} obj Object of new option values
* @return {Object} A NEW object of this.options_ and obj merged
*/
value: function options(obj) {
if (obj === undefined) {
return this.options_;
}return this.options_ = VjsUtil.mergeOptions(this.options_, obj);
}
}, {
key: 'el',
/**
* Get the component's DOM element
*
* var domEl = myComponent.el();
*
* @return {Element}
*/
value: function el() {
return this.el_;
}
}, {
key: 'createEl',
/**
* Create the component's DOM element
*
* @param {String=} tagName Element's node type. e.g. 'div'
* @param {Object=} attributes An object of element attributes that should be set on the element
* @return {Element}
*/
value: function createEl(tagName, attributes) {
return Lib.createEl(tagName, attributes);
}
}, {
key: 'localize',
value: function localize(string) {
var lang = this.player_.language();
var languages = this.player_.languages();
if (languages && languages[lang] && languages[lang][string]) {
return languages[lang][string];
}
return string;
}
}, {
key: 'contentEl',
/**
* Return the component's DOM element where children are inserted.
* Will either be the same as el() or a new element defined in createEl().
*
* @return {Element}
*/
value: function contentEl() {
return this.contentEl_ || this.el_;
}
}, {
key: 'id',
/**
* Get the component's ID
*
* var id = myComponent.id();
*
* @return {String}
*/
value: function id() {
return this.id_;
}
}, {
key: 'name',
/**
* Get the component's name. The name is often used to reference the component.
*
* var name = myComponent.name();
*
* @return {String}
*/
value: function name() {
return this.name_;
}
}, {
key: 'children',
/**
* Get an array of all child components
*
* var kids = myComponent.children();
*
* @return {Array} The children
*/
value: function children() {
return this.children_;
}
}, {
key: 'getChildById',
/**
* Returns a child component with the provided ID
*
* @return {Component}
*/
value: function getChildById(id) {
return this.childIndex_[id];
}
}, {
key: 'getChild',
/**
* Returns a child component with the provided name
*
* @return {Component}
*/
value: function getChild(name) {
return this.childNameIndex_[name];
}
}, {
key: 'addChild',
/**
* Adds a child component inside this component
*
* myComponent.el();
* // -> <div class='my-component'></div>
* myComponent.children();
* // [empty array]
*
* var myButton = myComponent.addChild('MyButton');
* // -> <div class='my-component'><div class="my-button">myButton<div></div>
* // -> myButton === myComonent.children()[0];
*
* Pass in options for child constructors and options for children of the child
*
* var myButton = myComponent.addChild('MyButton', {
* text: 'Press Me',
* children: {
* buttonChildExample: {
* buttonChildOption: true
* }
* }
* });
*
* @param {String|Component} child The class name or instance of a child to add
* @param {Object=} options Options, including options to be passed to children of the child.
* @return {Component} The child component (created by this process if a string was used)
* @suppress {accessControls|checkRegExp|checkTypes|checkVars|const|constantProperty|deprecated|duplicate|es5Strict|fileoverviewTags|globalThis|invalidCasts|missingProperties|nonStandardJsDocs|strictModuleDepCheck|undefinedNames|undefinedVars|unknownDefines|uselessCode|visibility}
*/
value: function addChild(child) {
var options = arguments[1] === undefined ? {} : arguments[1];
var component = undefined;
var componentName = undefined;
// If child is a string, create nt with options
if (typeof child === 'string') {
componentName = child;
// Options can also be specified as a boolean, so convert to an empty object if false.
if (!options) {
options = {};
}
// Same as above, but true is deprecated so show a warning.
if (options === true) {
Lib.log.warn('Initializing a child component with `true` is deprecated. Children should be defined in an array when possible, but if necessary use an object instead of `true`.');
options = {};
}
// If no componentClass in options, assume componentClass is the name lowercased
// (e.g. playButton)
var componentClassName = options.componentClass || Lib.capitalize(componentName);
// Set name through options
options.name = componentName;
// Create a new object & element for this controls set
// If there's no .player_, this is a player
var componentClass = Component.getComponent(componentClassName);
component = new componentClass(this.player_ || this, options);
// child is a component instance
} else {
component = child;
}
this.children_.push(component);
if (typeof component.id === 'function') {
this.childIndex_[component.id()] = component;
}
// If a name wasn't used to create the component, check if we can use the
// name function of the component
componentName = componentName || component.name && component.name();
if (componentName) {
this.childNameIndex_[componentName] = component;
}
// Add the UI object's element to the container div (box)
// Having an element is not required
if (typeof component.el === 'function' && component.el()) {
this.contentEl().appendChild(component.el());
}
// Return so it can stored on parent object if desired.
return component;
}
}, {
key: 'removeChild',
/**
* Remove a child component from this component's list of children, and the
* child component's element from this component's element
*
* @param {Component} component Component to remove
*/
value: function removeChild(component) {
if (typeof component === 'string') {
component = this.getChild(component);
}
if (!component || !this.children_) {
return;
}var childFound = false;
for (var i = this.children_.length - 1; i >= 0; i--) {
if (this.children_[i] === component) {
childFound = true;
this.children_.splice(i, 1);
break;
}
}
if (!childFound) {
return;
}this.childIndex_[component.id()] = null;
this.childNameIndex_[component.name()] = null;
var compEl = component.el();
if (compEl && compEl.parentNode === this.contentEl()) {
this.contentEl().removeChild(component.el());
}
}
}, {
key: 'initChildren',
/**
* Add and initialize default child components from options
*
* // when an instance of MyComponent is created, all children in options
* // will be added to the instance by their name strings and options
* MyComponent.prototype.options_.children = {
* myChildComponent: {
* myChildOption: true
* }
* }
*
* // Or when creating the component
* var myComp = new MyComponent(player, {
* children: {
* myChildComponent: {
* myChildOption: true
* }
* }
* });
*
* The children option can also be an Array of child names or
* child options objects (that also include a 'name' key).
*
* var myComp = new MyComponent(player, {
* children: [
* 'button',
* {
* name: 'button',
* someOtherOption: true
* }
* ]
* });
*
*/
value: function initChildren() {
var _this = this;
var children = this.options_.children;
if (children) {
var i;
(function () {
var parent = _this;
var parentOptions = parent.options();
var handleAdd = function handleAdd(name, opts) {
// Allow options for children to be set at the parent options
// e.g. videojs(id, { controlBar: false });
// instead of videojs(id, { children: { controlBar: false });
if (parentOptions[name] !== undefined) {
opts = parentOptions[name];
}
// Allow for disabling default components
// e.g. options['children']['posterImage'] = false
if (opts === false) {
return;
} // Create and add the child component.
// Add a direct reference to the child by name on the parent instance.
// If two of the same component are used, different names should be supplied
// for each
parent[name] = parent.addChild(name, opts);
};
// Allow for an array of children details to passed in the options
if (Lib.obj.isArray(children)) {
for (i = 0; i < children.length; i++) {
var child = children[i];
var _name = undefined,
opts = undefined;
if (typeof child == 'string') {
// ['myComponent']
_name = child;
opts = {};
} else {
// [{ name: 'myComponent', otherOption: true }]
_name = child.name;
opts = child;
}
handleAdd(_name, opts);
}
} else {
Lib.obj.each(children, handleAdd);
}
})();
}
}
}, {
key: 'buildCSSClass',
/**
* Allows sub components to stack CSS class names
*
* @return {String} The constructed class name
*/
value: function buildCSSClass() {
// Child classes can include a function that does:
// return 'CLASS NAME' + this._super();
return '';
}
}, {
key: 'on',
/**
* Add an event listener to this component's element
*
* var myFunc = function(){
* var myComponent = this;
* // Do something when the event is fired
* };
*
* myComponent.on('eventType', myFunc);
*
* The context of myFunc will be myComponent unless previously bound.
*
* Alternatively, you can add a listener to another element or component.
*
* myComponent.on(otherElement, 'eventName', myFunc);
* myComponent.on(otherComponent, 'eventName', myFunc);
*
* The benefit of using this over `VjsEvents.on(otherElement, 'eventName', myFunc)`
* and `otherComponent.on('eventName', myFunc)` is that this way the listeners
* will be automatically cleaned up when either component is disposed.
* It will also bind myComponent as the context of myFunc.
*
* **NOTE**: When using this on elements in the page other than window
* and document (both permanent), if you remove the element from the DOM
* you need to call `myComponent.trigger(el, 'dispose')` on it to clean up
* references to it and allow the browser to garbage collect it.
*
* @param {String|Component} first The event type or other component
* @param {Function|String} second The event handler or event type
* @param {Function} third The event handler
* @return {Component} self
*/
value: function on(first, second, third) {
var _this2 = this;
if (typeof first === 'string' || Lib.obj.isArray(first)) {
Events.on(this.el_, first, Lib.bind(this, second));
// Targeting another component or element
} else {
(function () {
var target = first;
var type = second;
var fn = Lib.bind(_this2, third);
var thisComponent = _this2;
// When this component is disposed, remove the listener from the other component
var removeOnDispose = function removeOnDispose() {
thisComponent.off(target, type, fn);
};
// Use the same function ID so we can remove it later it using the ID
// of the original listener
removeOnDispose.guid = fn.guid;
_this2.on('dispose', removeOnDispose);
// If the other component is disposed first we need to clean the reference
// to the other component in this component's removeOnDispose listener
// Otherwise we create a memory leak.
var cleanRemover = function cleanRemover() {
thisComponent.off('dispose', removeOnDispose);
};
// Add the same function ID so we can easily remove it later
cleanRemover.guid = fn.guid;
// Check if this is a DOM node
if (first.nodeName) {
// Add the listener to the other element
Events.on(target, type, fn);
Events.on(target, 'dispose', cleanRemover);
// Should be a component
// Not using `instanceof Component` because it makes mock players difficult
} else if (typeof first.on === 'function') {
// Add the listener to the other component
target.on(type, fn);
target.on('dispose', cleanRemover);
}
})();
}
return this;
}
}, {
key: 'off',
/**
* Remove an event listener from this component's element
*
* myComponent.off('eventType', myFunc);
*
* If myFunc is excluded, ALL listeners for the event type will be removed.
* If eventType is excluded, ALL listeners will be removed from the component.
*
* Alternatively you can use `off` to remove listeners that were added to other
* elements or components using `myComponent.on(otherComponent...`.
* In this case both the event type and listener function are REQUIRED.
*
* myComponent.off(otherElement, 'eventType', myFunc);
* myComponent.off(otherComponent, 'eventType', myFunc);
*
* @param {String=|Component} first The event type or other component
* @param {Function=|String} second The listener function or event type
* @param {Function=} third The listener for other component
* @return {Component}
*/
value: function off(first, second, third) {
if (!first || typeof first === 'string' || Lib.obj.isArray(first)) {
Events.off(this.el_, first, second);
} else {
var target = first;
var type = second;
// Ensure there's at least a guid, even if the function hasn't been used
var fn = Lib.bind(this, third);
// Remove the dispose listener on this component,
// which was given the same guid as the event listener
this.off('dispose', fn);
if (first.nodeName) {
// Remove the listener
Events.off(target, type, fn);
// Remove the listener for cleaning the dispose listener
Events.off(target, 'dispose', fn);
} else {
target.off(type, fn);
target.off('dispose', fn);
}
}
return this;
}
}, {
key: 'one',
/**
* Add an event listener to be triggered only once and then removed
*
* myComponent.one('eventName', myFunc);
*
* Alternatively you can add a listener to another element or component
* that will be triggered only once.
*
* myComponent.one(otherElement, 'eventName', myFunc);
* myComponent.one(otherComponent, 'eventName', myFunc);
*
* @param {String|Component} first The event type or other component
* @param {Function|String} second The listener function or event type
* @param {Function=} third The listener function for other component
* @return {Component}
*/
value: function one(first, second, third) {
var _this3 = this;
if (typeof first === 'string' || Lib.obj.isArray(first)) {
Events.one(this.el_, first, Lib.bind(this, second));
} else {
(function () {
var target = first;
var type = second;
var fn = Lib.bind(_this3, third);
var thisComponent = _this3;
var newFunc = (function (_newFunc) {
function newFunc() {
return _newFunc.apply(this, arguments);
}
newFunc.toString = function () {
return newFunc.toString();
};
return newFunc;
})(function () {
thisComponent.off(target, type, newFunc);
fn.apply(this, arguments);
});
// Keep the same function ID so we can remove it later
newFunc.guid = fn.guid;
_this3.on(target, type, newFunc);
})();
}
return this;
}
}, {
key: 'trigger',
/**
* Trigger an event on an element
*
* myComponent.trigger('eventName');
* myComponent.trigger({'type':'eventName'});
*
* @param {Event|Object|String} event A string (the type) or an event object with a type attribute
* @return {Component} self
*/
value: function trigger(event) {
Events.trigger(this.el_, event);
return this;
}
}, {
key: 'ready',
/**
* Bind a listener to the component's ready state
*
* Different from event listeners in that if the ready event has already happened
* it will trigger the function immediately.
*
* @param {Function} fn Ready listener
* @return {Component}
*/
value: function ready(fn) {
if (fn) {
if (this.isReady_) {
fn.call(this);
} else {
this.readyQueue_ = this.readyQueue_ || [];
this.readyQueue_.push(fn);
}
}
return this;
}
}, {
key: 'triggerReady',
/**
* Trigger the ready listeners
*
* @return {Component}
*/
value: function triggerReady() {
this.isReady_ = true;
var readyQueue = this.readyQueue_;
if (readyQueue && readyQueue.length > 0) {
for (var i = 0, j = readyQueue.length; i < j; i++) {
readyQueue[i].call(this);
}
// Reset Ready Queue
this.readyQueue_ = [];
// Allow for using event listeners also, in case you want to do something everytime a source is ready.
this.trigger('ready');
}
}
}, {
key: 'hasClass',
/**
* Check if a component's element has a CSS class name
*
* @param {String} classToCheck Classname to check
* @return {Component}
*/
value: function hasClass(classToCheck) {
return Lib.hasClass(this.el_, classToCheck);
}
}, {
key: 'addClass',
/**
* Add a CSS class name to the component's element
*
* @param {String} classToAdd Classname to add
* @return {Component}
*/
value: function addClass(classToAdd) {
Lib.addClass(this.el_, classToAdd);
return this;
}
}, {
key: 'removeClass',
/**
* Remove a CSS class name from the component's element
*
* @param {String} classToRemove Classname to remove
* @return {Component}
*/
value: function removeClass(classToRemove) {
Lib.removeClass(this.el_, classToRemove);
return this;
}
}, {
key: 'show',
/**
* Show the component element if hidden
*
* @return {Component}
*/
value: function show() {
this.removeClass('vjs-hidden');
return this;
}
}, {
key: 'hide',
/**
* Hide the component element if currently showing
*
* @return {Component}
*/
value: function hide() {
this.addClass('vjs-hidden');
return this;
}
}, {
key: 'lockShowing',
/**
* Lock an item in its visible state
* To be used with fadeIn/fadeOut.
*
* @return {Component}
* @private
*/
value: function lockShowing() {
this.addClass('vjs-lock-showing');
return this;
}
}, {
key: 'unlockShowing',
/**
* Unlock an item to be hidden
* To be used with fadeIn/fadeOut.
*
* @return {Component}
* @private
*/
value: function unlockShowing() {
this.removeClass('vjs-lock-showing');
return this;
}
}, {
key: 'width',
/**
* Set or get the width of the component (CSS values)
*
* Setting the video tag dimension values only works with values in pixels.
* Percent values will not work.
* Some percents can be used, but width()/height() will return the number + %,
* not the actual computed width/height.
*
* @param {Number|String=} num Optional width number
* @param {Boolean} skipListeners Skip the 'resize' event trigger
* @return {Component} This component, when setting the width
* @return {Number|String} The width, when getting
*/
value: function width(num, skipListeners) {
return this.dimension('width', num, skipListeners);
}
}, {
key: 'height',
/**
* Get or set the height of the component (CSS values)
*
* Setting the video tag dimension values only works with values in pixels.
* Percent values will not work.
* Some percents can be used, but width()/height() will return the number + %,
* not the actual computed width/height.
*
* @param {Number|String=} num New component height
* @param {Boolean=} skipListeners Skip the resize event trigger
* @return {Component} This component, when setting the height
* @return {Number|String} The height, when getting
*/
value: function height(num, skipListeners) {
return this.dimension('height', num, skipListeners);
}
}, {
key: 'dimensions',
/**
* Set both width and height at the same time
*
* @param {Number|String} width
* @param {Number|String} height
* @return {Component} The component
*/
value: function dimensions(width, height) {
// Skip resize listeners on width for optimization
return this.width(width, true).height(height);
}
}, {
key: 'dimension',
/**
* Get or set width or height
*
* This is the shared code for the width() and height() methods.
* All for an integer, integer + 'px' or integer + '%';
*
* Known issue: Hidden elements officially have a width of 0. We're defaulting
* to the style.width value and falling back to computedStyle which has the
* hidden element issue. Info, but probably not an efficient fix:
* http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/
*
* @param {String} widthOrHeight 'width' or 'height'
* @param {Number|String=} num New dimension
* @param {Boolean=} skipListeners Skip resize event trigger
* @return {Component} The component if a dimension was set
* @return {Number|String} The dimension if nothing was set
* @private
*/
value: function dimension(widthOrHeight, num, skipListeners) {
if (num !== undefined) {
// Set to zero if null or literally NaN (NaN !== NaN)
if (num === null || num !== num) {
num = 0;
}
// Check if using css width/height (% or px) and adjust
if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {
this.el_.style[widthOrHeight] = num;
} else if (num === 'auto') {
this.el_.style[widthOrHeight] = '';
} else {
this.el_.style[widthOrHeight] = num + 'px';
}
// skipListeners allows us to avoid triggering the resize event when setting both width and height
if (!skipListeners) {
this.trigger('resize');
}
// Return component
return this;
}
// Not setting a value, so getting it
// Make sure element exists
if (!this.el_) {
return 0;
} // Get dimension value from style
var val = this.el_.style[widthOrHeight];
var pxIndex = val.indexOf('px');
if (pxIndex !== -1) {
// Return the pixel value with no 'px'
return parseInt(val.slice(0, pxIndex), 10);
// No px so using % or no style was set, so falling back to offsetWidth/height
// If component has display:none, offset will return 0
// TODO: handle display:none and no dimension style using px
} else {
return parseInt(this.el_['offset' + Lib.capitalize(widthOrHeight)], 10);
// ComputedStyle version.
// Only difference is if the element is hidden it will return
// the percent value (e.g. '100%'')
// instead of zero like offsetWidth returns.
// var val = Lib.getComputedStyleValue(this.el_, widthOrHeight);
// var pxIndex = val.indexOf('px');
// if (pxIndex !== -1) {
// return val.slice(0, pxIndex);
// } else {
// return val;
// }
}
}
}, {
key: 'emitTapEvents',
/**
* Emit 'tap' events when touch events are supported
*
* This is used to support toggling the controls through a tap on the video.
*
* We're requiring them to be enabled because otherwise every component would
* have this extra overhead unnecessarily, on mobile devices where extra
* overhead is especially bad.
* @private
*/
value: function emitTapEvents() {
// Track the start time so we can determine how long the touch lasted
var touchStart = 0;
var firstTouch = null;
// Maximum movement allowed during a touch event to still be considered a tap
// Other popular libs use anywhere from 2 (hammer.js) to 15, so 10 seems like a nice, round number.
var tapMovementThreshold = 10;
// The maximum length a touch can be while still being considered a tap
var touchTimeThreshold = 200;
var couldBeTap = undefined;
this.on('touchstart', function (event) {
// If more than one finger, don't consider treating this as a click
if (event.touches.length === 1) {
firstTouch = Lib.obj.copy(event.touches[0]);
// Record start time so we can detect a tap vs. "touch and hold"
touchStart = new Date().getTime();
// Reset couldBeTap tracking
couldBeTap = true;
}
});
this.on('touchmove', function (event) {
// If more than one finger, don't consider treating this as a click
if (event.touches.length > 1) {
couldBeTap = false;
} else if (firstTouch) {
// Some devices will throw touchmoves for all but the slightest of taps.
// So, if we moved only a small distance, this could still be a tap
var xdiff = event.touches[0].pageX - firstTouch.pageX;
var ydiff = event.touches[0].pageY - firstTouch.pageY;
var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
if (touchDistance > tapMovementThreshold) {
couldBeTap = false;
}
}
});
var noTap = function noTap() {
couldBeTap = false;
};
// TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
this.on('touchleave', noTap);
this.on('touchcancel', noTap);
// When the touch ends, measure how long it took and trigger the appropriate
// event
this.on('touchend', function (event) {
firstTouch = null;
// Proceed only if the touchmove/leave/cancel event didn't happen
if (couldBeTap === true) {
// Measure how long the touch lasted
var touchTime = new Date().getTime() - touchStart;
// Make sure the touch was less than the threshold to be considered a tap
if (touchTime < touchTimeThreshold) {
event.preventDefault(); // Don't let browser turn this into a click
this.trigger('tap');
// It may be good to copy the touchend event object and change the
// type to tap, if the other event properties aren't exact after
// Lib.fixEvent runs (e.g. event.target)
}
}
});
}
}, {
key: 'enableTouchActivity',
/**
* Report user touch activity when touch events occur
*
* User activity is used to determine when controls should show/hide. It's
* relatively simple when it comes to mouse events, because any mouse event
* should show the controls. So we capture mouse events that bubble up to the
* player and report activity when that happens.
*
* With touch events it isn't as easy. We can't rely on touch events at the
* player level, because a tap (touchstart + touchend) on the video itself on
* mobile devices is meant to turn controls off (and on). User activity is
* checked asynchronously, so what could happen is a tap event on the video
* turns the controls off, then the touchend event bubbles up to the player,
* which if it reported user activity, would turn the controls right back on.
* (We also don't want to completely block touch events from bubbling up)
*
* Also a touchmove, touch+hold, and anything other than a tap is not supposed
* to turn the controls back on on a mobile device.
*
* Here we're setting the default component behavior to report user activity
* whenever touch events happen, and this can be turned off by components that
* want touch events to act differently.
*/
value: function enableTouchActivity() {
// Don't continue if the root player doesn't support reporting user activity
if (!this.player().reportUserActivity) {
return;
}
// listener for reporting that the user is active
var report = Lib.bind(this.player(), this.player().reportUserActivity);
var touchHolding = undefined;
this.on('touchstart', function () {
report();
// For as long as the they are touching the device or have their mouse down,
// we consider them active even if they're not moving their finger or mouse.
// So we want to continue to update that they are active
this.clearInterval(touchHolding);
// report at the same interval as activityCheck
touchHolding = this.setInterval(report, 250);
});
var touchEnd = function touchEnd(event) {
report();
// stop the interval that maintains activity if the touch is holding
this.clearInterval(touchHolding);
};
this.on('touchmove', report);
this.on('touchend', touchEnd);
this.on('touchcancel', touchEnd);
}
}, {
key: 'setTimeout',
/**
* Creates timeout and sets up disposal automatically.
* @param {Function} fn The function to run after the timeout.
* @param {Number} timeout Number of ms to delay before executing specified function.
* @return {Number} Returns the timeout ID
*/
value: (function (_setTimeout) {
function setTimeout(_x, _x2) {
return _setTimeout.apply(this, arguments);
}
setTimeout.toString = function () {
return setTimeout.toString();
};
return setTimeout;
})(function (fn, timeout) {
fn = Lib.bind(this, fn);
// window.setTimeout would be preferable here, but due to some bizarre issue with Sinon and/or Phantomjs, we can't.
var timeoutId = setTimeout(fn, timeout);
var disposeFn = function disposeFn() {
this.clearTimeout(timeoutId);
};
disposeFn.guid = 'vjs-timeout-' + timeoutId;
this.on('dispose', disposeFn);
return timeoutId;
})
}, {
key: 'clearTimeout',
/**
* Clears a timeout and removes the associated dispose listener
* @param {Number} timeoutId The id of the timeout to clear
* @return {Number} Returns the timeout ID
*/
value: (function (_clearTimeout) {
function clearTimeout(_x3) {
return _clearTimeout.apply(this, arguments);
}
clearTimeout.toString = function () {
return clearTimeout.toString();
};
return clearTimeout;
})(function (timeoutId) {
clearTimeout(timeoutId);
var disposeFn = function disposeFn() {};
disposeFn.guid = 'vjs-timeout-' + timeoutId;
this.off('dispose', disposeFn);
return timeoutId;
})
}, {
key: 'setInterval',
/**
* Creates an interval and sets up disposal automatically.
* @param {Function} fn The function to run every N seconds.
* @param {Number} interval Number of ms to delay before executing specified function.
* @return {Number} Returns the interval ID
*/
value: (function (_setInterval) {
function setInterval(_x4, _x5) {
return _setInterval.apply(this, arguments);
}
setInterval.toString = function () {
return setInterval.toString();
};
return setInterval;
})(function (fn, interval) {
fn = Lib.bind(this, fn);
var intervalId = setInterval(fn, interval);
var disposeFn = function disposeFn() {
this.clearInterval(intervalId);
};
disposeFn.guid = 'vjs-interval-' + intervalId;
this.on('dispose', disposeFn);
return intervalId;
})
}, {
key: 'clearInterval',
/**
* Clears an interval and removes the associated dispose listener
* @param {Number} intervalId The id of the interval to clear
* @return {Number} Returns the interval ID
*/
value: (function (_clearInterval) {
function clearInterval(_x6) {
return _clearInterval.apply(this, arguments);
}
clearInterval.toString = function () {
return clearInterval.toString();
};
return clearInterval;
})(function (intervalId) {
clearInterval(intervalId);
var disposeFn = function disposeFn() {};
disposeFn.guid = 'vjs-interval-' + intervalId;
this.off('dispose', disposeFn);
return intervalId;
})
}], [{
key: 'registerComponent',
value: function registerComponent(name, comp) {
if (!Component.components_) {
Component.components_ = {};
}
Component.components_[name] = comp;
return comp;
}
}, {
key: 'getComponent',
value: function getComponent(name) {
if (Component.components_ && Component.components_[name]) {
return Component.components_[name];
}
if (_window2['default'] && _window2['default'].videojs && _window2['default'].videojs[name]) {
Lib.log.warn('The ' + name + ' component was added to the videojs object when it should be registered using videojs.registerComponent(name, component)');
return _window2['default'].videojs[name];
}
}
}, {
key: 'extend',
value: function extend(props) {
props = props || {};
// Set up the constructor using the supplied init method
// or using the init of the parent object
// Make sure to check the unobfuscated version for external libs
var init = props.init || props.init || this.prototype.init || this.prototype.init || function () {};
// In Resig's simple class inheritance (previously used) the constructor
// is a function that calls `this.init.apply(arguments)`
// However that would prevent us from using `ParentObject.call(this);`
// in a Child constructor because the `this` in `this.init`
// would still refer to the Child and cause an infinite loop.
// We would instead have to do
// `ParentObject.prototype.init.apply(this, arguments);`
// Bleh. We're not creating a _super() function, so it's good to keep
// the parent constructor reference simple.
var subObj = function subObj() {
init.apply(this, arguments);
};
// Inherit from this object's prototype
subObj.prototype = Lib.obj.create(this.prototype);
// Reset the constructor property for subObj otherwise
// instances of subObj would have the constructor of the parent Object
subObj.prototype.constructor = subObj;
// Make the class extendable
subObj.extend = Component.extend;
// Make a function for creating instances
// subObj.create = CoreObject.create;
// Extend subObj's prototype with functions and other properties from props
for (var name in props) {
if (props.hasOwnProperty(name)) {
subObj.prototype[name] = props[name];
}
}
return subObj;
}
}]);
return Component;
})();
Component.registerComponent('Component', Component);
exports['default'] = Component;
module.exports = exports['default'];
},{"./events.js":43,"./lib.js":46,"./util.js":70,"global/window":2}],8:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('../lib.js');
var Lib = _interopRequireWildcard(_import);
// Required children
var _PlayToggle = _dereq_('./play-toggle.js');
var _PlayToggle2 = _interopRequireWildcard(_PlayToggle);
var _CurrentTimeDisplay = _dereq_('./time-controls/current-time-display.js');
var _CurrentTimeDisplay2 = _interopRequireWildcard(_CurrentTimeDisplay);
var _DurationDisplay = _dereq_('./time-controls/duration-display.js');
var _DurationDisplay2 = _interopRequireWildcard(_DurationDisplay);
var _TimeDivider = _dereq_('./time-controls/time-divider.js');
var _TimeDivider2 = _interopRequireWildcard(_TimeDivider);
var _RemainingTimeDisplay = _dereq_('./time-controls/remaining-time-display.js');
var _RemainingTimeDisplay2 = _interopRequireWildcard(_RemainingTimeDisplay);
var _LiveDisplay = _dereq_('./live-display.js');
var _LiveDisplay2 = _interopRequireWildcard(_LiveDisplay);
var _ProgressControl = _dereq_('./progress-control/progress-control.js');
var _ProgressControl2 = _interopRequireWildcard(_ProgressControl);
var _FullscreenToggle = _dereq_('./fullscreen-toggle.js');
var _FullscreenToggle2 = _interopRequireWildcard(_FullscreenToggle);
var _VolumeControl = _dereq_('./volume-control/volume-control.js');
var _VolumeControl2 = _interopRequireWildcard(_VolumeControl);
var _VolumeMenuButton = _dereq_('./volume-menu-button.js');
var _VolumeMenuButton2 = _interopRequireWildcard(_VolumeMenuButton);
var _MuteToggle = _dereq_('./mute-toggle.js');
var _MuteToggle2 = _interopRequireWildcard(_MuteToggle);
var _ChaptersButton = _dereq_('./text-track-controls/chapters-button.js');
var _ChaptersButton2 = _interopRequireWildcard(_ChaptersButton);
var _SubtitlesButton = _dereq_('./text-track-controls/subtitles-button.js');
var _SubtitlesButton2 = _interopRequireWildcard(_SubtitlesButton);
var _CaptionsButton = _dereq_('./text-track-controls/captions-button.js');
var _CaptionsButton2 = _interopRequireWildcard(_CaptionsButton);
var _PlaybackRateMenuButton = _dereq_('./playback-rate-menu/playback-rate-menu-button.js');
var _PlaybackRateMenuButton2 = _interopRequireWildcard(_PlaybackRateMenuButton);
var _CustomControlSpacer = _dereq_('./spacer-controls/custom-control-spacer.js');
var _CustomControlSpacer2 = _interopRequireWildcard(_CustomControlSpacer);
/**
* Container of main controls
* @param {Player|Object} player
* @param {Object=} options
* @class
* @constructor
* @extends Component
*/
var ControlBar = (function (_Component) {
function ControlBar() {
_classCallCheck(this, ControlBar);
if (_Component != null) {
_Component.apply(this, arguments);
}
}
_inherits(ControlBar, _Component);
_createClass(ControlBar, [{
key: 'createEl',
value: function createEl() {
return Lib.createEl('div', {
className: 'vjs-control-bar'
});
}
}]);
return ControlBar;
})(_Component3['default']);
ControlBar.prototype.options_ = {
loadEvent: 'play',
children: ['playToggle', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'muteToggle', 'volumeControl', 'chaptersButton', 'subtitlesButton', 'captionsButton', 'volumeMenuButton', 'fullscreenToggle']
};
_Component3['default'].registerComponent('ControlBar', ControlBar);
exports['default'] = ControlBar;
module.exports = exports['default'];
},{"../component.js":7,"../lib.js":46,"./fullscreen-toggle.js":9,"./live-display.js":10,"./mute-toggle.js":11,"./play-toggle.js":12,"./playback-rate-menu/playback-rate-menu-button.js":13,"./progress-control/progress-control.js":17,"./spacer-controls/custom-control-spacer.js":20,"./text-track-controls/captions-button.js":23,"./text-track-controls/chapters-button.js":24,"./text-track-controls/subtitles-button.js":27,"./time-controls/current-time-display.js":30,"./time-controls/duration-display.js":31,"./time-controls/remaining-time-display.js":32,"./time-controls/time-divider.js":33,"./volume-control/volume-control.js":35,"./volume-menu-button.js":38}],9:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Button2 = _dereq_('../button');
var _Button3 = _interopRequireWildcard(_Button2);
/**
* Toggle fullscreen video
* @param {Player|Object} player
* @param {Object=} options
* @class
* @extends vjs.Button
*/
var FullscreenToggle = (function (_Button) {
function FullscreenToggle() {
_classCallCheck(this, FullscreenToggle);
if (_Button != null) {
_Button.apply(this, arguments);
}
}
_inherits(FullscreenToggle, _Button);
_createClass(FullscreenToggle, [{
key: 'buildCSSClass',
value: function buildCSSClass() {
return 'vjs-fullscreen-control ' + _get(Object.getPrototypeOf(FullscreenToggle.prototype), 'buildCSSClass', this).call(this);
}
}, {
key: 'handleClick',
value: function handleClick() {
if (!this.player_.isFullscreen()) {
this.player_.requestFullscreen();
this.controlText_.innerHTML = this.localize('Non-Fullscreen');
} else {
this.player_.exitFullscreen();
this.controlText_.innerHTML = this.localize('Fullscreen');
}
}
}]);
return FullscreenToggle;
})(_Button3['default']);
FullscreenToggle.prototype.buttonText = 'Fullscreen';
_Button3['default'].registerComponent('FullscreenToggle', FullscreenToggle);
exports['default'] = FullscreenToggle;
module.exports = exports['default'];
},{"../button":6}],10:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../component');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('../lib');
var Lib = _interopRequireWildcard(_import);
/**
* Displays the live indicator
* TODO - Future make it click to snap to live
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var LiveDisplay = (function (_Component) {
function LiveDisplay() {
_classCallCheck(this, LiveDisplay);
if (_Component != null) {
_Component.apply(this, arguments);
}
}
_inherits(LiveDisplay, _Component);
_createClass(LiveDisplay, [{
key: 'createEl',
value: function createEl() {
var el = _get(Object.getPrototypeOf(LiveDisplay.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-live-control vjs-control'
});
this.contentEl_ = Lib.createEl('div', {
className: 'vjs-live-display',
innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE'),
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
}
}]);
return LiveDisplay;
})(_Component3['default']);
_Component3['default'].registerComponent('LiveDisplay', LiveDisplay);
exports['default'] = LiveDisplay;
module.exports = exports['default'];
},{"../component":7,"../lib":46}],11:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Button2 = _dereq_('../button');
var _Button3 = _interopRequireWildcard(_Button2);
var _Component = _dereq_('../component');
var _Component2 = _interopRequireWildcard(_Component);
var _import = _dereq_('../lib');
var Lib = _interopRequireWildcard(_import);
/**
* A button component for muting the audio
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var MuteToggle = (function (_Button) {
function MuteToggle(player, options) {
_classCallCheck(this, MuteToggle);
_get(Object.getPrototypeOf(MuteToggle.prototype), 'constructor', this).call(this, player, options);
this.on(player, 'volumechange', this.update);
// hide mute toggle if the current tech doesn't support volume control
if (player.tech && player.tech.featuresVolumeControl === false) {
this.addClass('vjs-hidden');
}
this.on(player, 'loadstart', function () {
if (player.tech.featuresVolumeControl === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
});
}
_inherits(MuteToggle, _Button);
_createClass(MuteToggle, [{
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(MuteToggle.prototype), 'createEl', this).call(this, 'div', {
className: this.buildCSSClass(),
innerHTML: '<div><span class="vjs-control-text">' + this.localize('Mute') + '</span></div>'
});
}
}, {
key: 'buildCSSClass',
value: function buildCSSClass() {
return 'vjs-mute-control ' + _get(Object.getPrototypeOf(MuteToggle.prototype), 'buildCSSClass', this).call(this);
}
}, {
key: 'handleClick',
value: function handleClick() {
this.player_.muted(this.player_.muted() ? false : true);
}
}, {
key: 'update',
value: function update() {
var vol = this.player_.volume(),
level = 3;
if (vol === 0 || this.player_.muted()) {
level = 0;
} else if (vol < 0.33) {
level = 1;
} else if (vol < 0.67) {
level = 2;
}
// Don't rewrite the button text if the actual text doesn't change.
// This causes unnecessary and confusing information for screen reader users.
// This check is needed because this function gets called every time the volume level is changed.
var toMute = this.player_.muted() ? 'Unmute' : 'Mute';
var localizedMute = this.localize(toMute);
if (this.el_.children[0].children[0].innerHTML !== localizedMute) {
this.el_.children[0].children[0].innerHTML = localizedMute;
}
/* TODO improve muted icon classes */
for (var i = 0; i < 4; i++) {
Lib.removeClass(this.el_, 'vjs-vol-' + i);
}
Lib.addClass(this.el_, 'vjs-vol-' + level);
}
}]);
return MuteToggle;
})(_Button3['default']);
_Component2['default'].registerComponent('MuteToggle', MuteToggle);
exports['default'] = MuteToggle;
module.exports = exports['default'];
},{"../button":6,"../component":7,"../lib":46}],12:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Button2 = _dereq_('../button');
var _Button3 = _interopRequireWildcard(_Button2);
var _import = _dereq_('../lib');
var Lib = _interopRequireWildcard(_import);
/**
* Button to toggle between play and pause
* @param {Player|Object} player
* @param {Object=} options
* @class
* @constructor
*/
var PlayToggle = (function (_Button) {
function PlayToggle(player, options) {
_classCallCheck(this, PlayToggle);
_get(Object.getPrototypeOf(PlayToggle.prototype), 'constructor', this).call(this, player, options);
this.on(player, 'play', this.handlePlay);
this.on(player, 'pause', this.handlePause);
}
_inherits(PlayToggle, _Button);
_createClass(PlayToggle, [{
key: 'buildCSSClass',
value: function buildCSSClass() {
return 'vjs-play-control ' + _get(Object.getPrototypeOf(PlayToggle.prototype), 'buildCSSClass', this).call(this);
}
}, {
key: 'handleClick',
// handleClick - Toggle between play and pause
value: function handleClick() {
if (this.player_.paused()) {
this.player_.play();
} else {
this.player_.pause();
}
}
}, {
key: 'handlePlay',
// handlePlay - Add the vjs-playing class to the element so it can change appearance
value: function handlePlay() {
this.removeClass('vjs-paused');
this.addClass('vjs-playing');
this.el_.children[0].children[0].innerHTML = this.localize('Pause'); // change the button text to "Pause"
}
}, {
key: 'handlePause',
// handlePause - Add the vjs-paused class to the element so it can change appearance
value: function handlePause() {
this.removeClass('vjs-playing');
this.addClass('vjs-paused');
this.el_.children[0].children[0].innerHTML = this.localize('Play'); // change the button text to "Play"
}
}]);
return PlayToggle;
})(_Button3['default']);
PlayToggle.prototype.buttonText = 'Play';
_Button3['default'].registerComponent('PlayToggle', PlayToggle);
exports['default'] = PlayToggle;
module.exports = exports['default'];
},{"../button":6,"../lib":46}],13:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _MenuButton2 = _dereq_('../../menu/menu-button.js');
var _MenuButton3 = _interopRequireWildcard(_MenuButton2);
var _Menu = _dereq_('../../menu/menu.js');
var _Menu2 = _interopRequireWildcard(_Menu);
var _PlaybackRateMenuItem = _dereq_('./playback-rate-menu-item.js');
var _PlaybackRateMenuItem2 = _interopRequireWildcard(_PlaybackRateMenuItem);
var _import = _dereq_('../../lib.js');
var Lib = _interopRequireWildcard(_import);
/**
* The component for controlling the playback rate
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var PlaybackRateMenuButton = (function (_MenuButton) {
function PlaybackRateMenuButton(player, options) {
_classCallCheck(this, PlaybackRateMenuButton);
_get(Object.getPrototypeOf(PlaybackRateMenuButton.prototype), 'constructor', this).call(this, player, options);
this.updateVisibility();
this.updateLabel();
this.on(player, 'loadstart', this.updateVisibility);
this.on(player, 'ratechange', this.updateLabel);
}
_inherits(PlaybackRateMenuButton, _MenuButton);
_createClass(PlaybackRateMenuButton, [{
key: 'createEl',
value: function createEl() {
var el = _get(Object.getPrototypeOf(PlaybackRateMenuButton.prototype), 'createEl', this).call(this);
this.labelEl_ = Lib.createEl('div', {
className: 'vjs-playback-rate-value',
innerHTML: 1
});
el.appendChild(this.labelEl_);
return el;
}
}, {
key: 'createMenu',
// Menu creation
value: function createMenu() {
var menu = new _Menu2['default'](this.player());
var rates = this.player().options().playbackRates;
if (rates) {
for (var i = rates.length - 1; i >= 0; i--) {
menu.addChild(new _PlaybackRateMenuItem2['default'](this.player(), { rate: rates[i] + 'x' }));
}
}
return menu;
}
}, {
key: 'updateARIAAttributes',
value: function updateARIAAttributes() {
// Current playback rate
this.el().setAttribute('aria-valuenow', this.player().playbackRate());
}
}, {
key: 'handleClick',
value: function handleClick() {
// select next rate option
var currentRate = this.player().playbackRate();
var rates = this.player().options().playbackRates;
// this will select first one if the last one currently selected
var newRate = rates[0];
for (var i = 0; i < rates.length; i++) {
if (rates[i] > currentRate) {
newRate = rates[i];
break;
}
}
this.player().playbackRate(newRate);
}
}, {
key: 'playbackRateSupported',
value: function playbackRateSupported() {
return this.player().tech && this.player().tech.featuresPlaybackRate && this.player().options().playbackRates && this.player().options().playbackRates.length > 0;
}
}, {
key: 'updateVisibility',
/**
* Hide playback rate controls when they're no playback rate options to select
*/
value: function updateVisibility() {
if (this.playbackRateSupported()) {
this.removeClass('vjs-hidden');
} else {
this.addClass('vjs-hidden');
}
}
}, {
key: 'updateLabel',
/**
* Update button label when rate changed
*/
value: function updateLabel() {
if (this.playbackRateSupported()) {
this.labelEl_.innerHTML = this.player().playbackRate() + 'x';
}
}
}]);
return PlaybackRateMenuButton;
})(_MenuButton3['default']);
PlaybackRateMenuButton.prototype.buttonText = 'Playback Rate';
PlaybackRateMenuButton.prototype.className = 'vjs-playback-rate';
_MenuButton3['default'].registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
exports['default'] = PlaybackRateMenuButton;
module.exports = exports['default'];
},{"../../lib.js":46,"../../menu/menu-button.js":49,"../../menu/menu.js":51,"./playback-rate-menu-item.js":14}],14:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _MenuItem2 = _dereq_('../../menu/menu-item.js');
var _MenuItem3 = _interopRequireWildcard(_MenuItem2);
/**
* The specific menu item type for selecting a playback rate
*
* @constructor
*/
var PlaybackRateMenuItem = (function (_MenuItem) {
function PlaybackRateMenuItem(player, options) {
_classCallCheck(this, PlaybackRateMenuItem);
var label = options.rate;
var rate = parseFloat(label, 10);
// Modify options for parent MenuItem class's init.
options.label = label;
options.selected = rate === 1;
_get(Object.getPrototypeOf(PlaybackRateMenuItem.prototype), 'constructor', this).call(this, player, options);
this.label = label;
this.rate = rate;
this.on(player, 'ratechange', this.update);
}
_inherits(PlaybackRateMenuItem, _MenuItem);
_createClass(PlaybackRateMenuItem, [{
key: 'handleClick',
value: function handleClick() {
_get(Object.getPrototypeOf(PlaybackRateMenuItem.prototype), 'handleClick', this).call(this);
this.player().playbackRate(this.rate);
}
}, {
key: 'update',
value: function update() {
this.selected(this.player().playbackRate() == this.rate);
}
}]);
return PlaybackRateMenuItem;
})(_MenuItem3['default']);
PlaybackRateMenuItem.prototype.contentElType = 'button';
_MenuItem3['default'].registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
exports['default'] = PlaybackRateMenuItem;
module.exports = exports['default'];
},{"../../menu/menu-item.js":50}],15:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('../../lib.js');
var Lib = _interopRequireWildcard(_import);
/**
* Shows load progress
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var LoadProgressBar = (function (_Component) {
function LoadProgressBar(player, options) {
_classCallCheck(this, LoadProgressBar);
_get(Object.getPrototypeOf(LoadProgressBar.prototype), 'constructor', this).call(this, player, options);
this.on(player, 'progress', this.update);
}
_inherits(LoadProgressBar, _Component);
_createClass(LoadProgressBar, [{
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(LoadProgressBar.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-load-progress',
innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>'
});
}
}, {
key: 'update',
value: function update() {
var buffered = this.player_.buffered();
var duration = this.player_.duration();
var bufferedEnd = this.player_.bufferedEnd();
var children = this.el_.children;
// get the percent width of a time compared to the total end
var percentify = function percentify(time, end) {
var percent = time / end || 0; // no NaN
return percent * 100 + '%';
};
// update the width of the progress bar
this.el_.style.width = percentify(bufferedEnd, duration);
// add child elements to represent the individual buffered time ranges
for (var i = 0; i < buffered.length; i++) {
var start = buffered.start(i);
var end = buffered.end(i);
var part = children[i];
if (!part) {
part = this.el_.appendChild(Lib.createEl());
}
// set the percent based on the width of the progress bar (bufferedEnd)
part.style.left = percentify(start, bufferedEnd);
part.style.width = percentify(end - start, bufferedEnd);
}
// remove unused buffered range elements
for (var i = children.length; i > buffered.length; i--) {
this.el_.removeChild(children[i - 1]);
}
}
}]);
return LoadProgressBar;
})(_Component3['default']);
_Component3['default'].registerComponent('LoadProgressBar', LoadProgressBar);
exports['default'] = LoadProgressBar;
module.exports = exports['default'];
},{"../../component.js":7,"../../lib.js":46}],16:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
/**
* Shows play progress
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var PlayProgressBar = (function (_Component) {
function PlayProgressBar() {
_classCallCheck(this, PlayProgressBar);
if (_Component != null) {
_Component.apply(this, arguments);
}
}
_inherits(PlayProgressBar, _Component);
_createClass(PlayProgressBar, [{
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(PlayProgressBar.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-play-progress',
innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>'
});
}
}]);
return PlayProgressBar;
})(_Component3['default']);
_Component3['default'].registerComponent('PlayProgressBar', PlayProgressBar);
exports['default'] = PlayProgressBar;
module.exports = exports['default'];
},{"../../component.js":7}],17:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
var _SeekBar = _dereq_('./seek-bar.js');
var _SeekBar2 = _interopRequireWildcard(_SeekBar);
/**
* The Progress Control component contains the seek bar, load progress,
* and play progress
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var ProgressControl = (function (_Component) {
function ProgressControl() {
_classCallCheck(this, ProgressControl);
if (_Component != null) {
_Component.apply(this, arguments);
}
}
_inherits(ProgressControl, _Component);
_createClass(ProgressControl, [{
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(ProgressControl.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-progress-control vjs-control'
});
}
}]);
return ProgressControl;
})(_Component3['default']);
ProgressControl.prototype.options_ = {
children: {
seekBar: {}
}
};
_Component3['default'].registerComponent('ProgressControl', ProgressControl);
exports['default'] = ProgressControl;
module.exports = exports['default'];
},{"../../component.js":7,"./seek-bar.js":18}],18:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Slider2 = _dereq_('../../slider/slider.js');
var _Slider3 = _interopRequireWildcard(_Slider2);
var _LoadProgressBar = _dereq_('./load-progress-bar.js');
var _LoadProgressBar2 = _interopRequireWildcard(_LoadProgressBar);
var _PlayProgressBar = _dereq_('./play-progress-bar.js');
var _PlayProgressBar2 = _interopRequireWildcard(_PlayProgressBar);
var _SeekHandle = _dereq_('./seek-handle.js');
var _SeekHandle2 = _interopRequireWildcard(_SeekHandle);
var _import = _dereq_('../../lib.js');
var Lib = _interopRequireWildcard(_import);
/**
* Seek Bar and holder for the progress bars
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var SeekBar = (function (_Slider) {
function SeekBar(player, options) {
_classCallCheck(this, SeekBar);
_get(Object.getPrototypeOf(SeekBar.prototype), 'constructor', this).call(this, player, options);
this.on(player, 'timeupdate', this.updateARIAAttributes);
player.ready(Lib.bind(this, this.updateARIAAttributes));
}
_inherits(SeekBar, _Slider);
_createClass(SeekBar, [{
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(SeekBar.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-progress-holder',
'aria-label': 'video progress bar'
});
}
}, {
key: 'updateARIAAttributes',
value: function updateARIAAttributes() {
// Allows for smooth scrubbing, when player can't keep up.
var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
this.el_.setAttribute('aria-valuenow', Lib.round(this.getPercent() * 100, 2)); // machine readable value of progress bar (percentage complete)
this.el_.setAttribute('aria-valuetext', Lib.formatTime(time, this.player_.duration())); // human readable value of progress bar (time complete)
}
}, {
key: 'getPercent',
value: function getPercent() {
return this.player_.currentTime() / this.player_.duration();
}
}, {
key: 'handleMouseDown',
value: function handleMouseDown(event) {
_get(Object.getPrototypeOf(SeekBar.prototype), 'handleMouseDown', this).call(this, event);
this.player_.scrubbing(true);
this.videoWasPlaying = !this.player_.paused();
this.player_.pause();
}
}, {
key: 'handleMouseMove',
value: function handleMouseMove(event) {
var newTime = this.calculateDistance(event) * this.player_.duration();
// Don't let video end while scrubbing.
if (newTime == this.player_.duration()) {
newTime = newTime - 0.1;
}
// Set new time (tell player to seek to new time)
this.player_.currentTime(newTime);
}
}, {
key: 'handleMouseUp',
value: function handleMouseUp(event) {
_get(Object.getPrototypeOf(SeekBar.prototype), 'handleMouseUp', this).call(this, event);
this.player_.scrubbing(false);
if (this.videoWasPlaying) {
this.player_.play();
}
}
}, {
key: 'stepForward',
value: function stepForward() {
this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users
}
}, {
key: 'stepBack',
value: function stepBack() {
this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users
}
}]);
return SeekBar;
})(_Slider3['default']);
SeekBar.prototype.options_ = {
children: {
loadProgressBar: {},
playProgressBar: {},
seekHandle: {}
},
barName: 'playProgressBar',
handleName: 'seekHandle'
};
SeekBar.prototype.playerEvent = 'timeupdate';
_Slider3['default'].registerComponent('SeekBar', SeekBar);
exports['default'] = SeekBar;
module.exports = exports['default'];
},{"../../lib.js":46,"../../slider/slider.js":58,"./load-progress-bar.js":15,"./play-progress-bar.js":16,"./seek-handle.js":19}],19:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _SliderHandle2 = _dereq_('../../slider/slider-handle.js');
var _SliderHandle3 = _interopRequireWildcard(_SliderHandle2);
var _import = _dereq_('../../lib.js');
var Lib = _interopRequireWildcard(_import);
/**
* The Seek Handle shows the current position of the playhead during playback,
* and can be dragged to adjust the playhead.
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var SeekHandle = (function (_SliderHandle) {
function SeekHandle(player, options) {
_classCallCheck(this, SeekHandle);
_get(Object.getPrototypeOf(SeekHandle.prototype), 'constructor', this).call(this, player, options);
this.on(player, 'timeupdate', this.updateContent);
}
_inherits(SeekHandle, _SliderHandle);
_createClass(SeekHandle, [{
key: 'createEl',
/** @inheritDoc */
value: function createEl() {
return _get(Object.getPrototypeOf(SeekHandle.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-seek-handle',
'aria-live': 'off'
});
}
}, {
key: 'updateContent',
value: function updateContent() {
var time = this.player_.scrubbing ? this.player_.getCache().currentTime : this.player_.currentTime();
this.el_.innerHTML = '<span class="vjs-control-text">' + Lib.formatTime(time, this.player_.duration()) + '</span>';
}
}]);
return SeekHandle;
})(_SliderHandle3['default']);
/**
* The default value for the handle content, which may be read by screen readers
*
* @type {String}
* @private
*/
SeekHandle.prototype.defaultValue = '00:00';
_SliderHandle3['default'].registerComponent('SeekHandle', SeekHandle);
exports['default'] = SeekHandle;
module.exports = exports['default'];
},{"../../lib.js":46,"../../slider/slider-handle.js":57}],20:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Spacer2 = _dereq_('./spacer.js');
var _Spacer3 = _interopRequireWildcard(_Spacer2);
/**
* Spacer specifically meant to be used as an insertion point for new plugins, etc.
*
* @param {Player|Object} player
* @param {Obect=} options
*/
var CustomControlSpacer = (function (_Spacer) {
function CustomControlSpacer() {
_classCallCheck(this, CustomControlSpacer);
if (_Spacer != null) {
_Spacer.apply(this, arguments);
}
}
_inherits(CustomControlSpacer, _Spacer);
_createClass(CustomControlSpacer, [{
key: 'buildCSSClass',
value: function buildCSSClass() {
return 'vjs-custom-control-spacer ' + _get(Object.getPrototypeOf(CustomControlSpacer.prototype), 'buildCSSClass', this).call(this);
}
}, {
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(CustomControlSpacer.prototype), 'createEl', this).call(this, {
className: this.buildCSSClass()
});
}
}]);
return CustomControlSpacer;
})(_Spacer3['default']);
_Spacer3['default'].registerComponent('CustomControlSpacer', CustomControlSpacer);
exports['default'] = CustomControlSpacer;
module.exports = exports['default'];
},{"./spacer.js":21}],21:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
/**
* Just an empty spacer element that can be used as an append point for plugins, etc.
* Also can be used to create space between elements when necessary.
*
* @param {Player|Object} player
* @param {Object=} options
*/
var Spacer = (function (_Component) {
function Spacer() {
_classCallCheck(this, Spacer);
if (_Component != null) {
_Component.apply(this, arguments);
}
}
_inherits(Spacer, _Component);
_createClass(Spacer, [{
key: 'buildCSSClass',
value: function buildCSSClass() {
return 'vjs-spacer ' + _get(Object.getPrototypeOf(Spacer.prototype), 'buildCSSClass', this).call(this);
}
}, {
key: 'createEl',
value: function createEl(props) {
return _get(Object.getPrototypeOf(Spacer.prototype), 'createEl', this).call(this, 'div', {
className: this.buildCSSClass()
});
}
}]);
return Spacer;
})(_Component3['default']);
_Component3['default'].registerComponent('Spacer', Spacer);
exports['default'] = Spacer;
module.exports = exports['default'];
},{"../../component.js":7}],22:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _TextTrackMenuItem2 = _dereq_('./text-track-menu-item.js');
var _TextTrackMenuItem3 = _interopRequireWildcard(_TextTrackMenuItem2);
var CaptionSettingsMenuItem = (function (_TextTrackMenuItem) {
function CaptionSettingsMenuItem(player, options) {
_classCallCheck(this, CaptionSettingsMenuItem);
options.track = {
kind: options.kind,
player: player,
label: options.kind + ' settings',
'default': false,
mode: 'disabled'
};
_get(Object.getPrototypeOf(CaptionSettingsMenuItem.prototype), 'constructor', this).call(this, player, options);
this.addClass('vjs-texttrack-settings');
}
_inherits(CaptionSettingsMenuItem, _TextTrackMenuItem);
_createClass(CaptionSettingsMenuItem, [{
key: 'handleClick',
value: function handleClick() {
this.player().getChild('textTrackSettings').show();
}
}]);
return CaptionSettingsMenuItem;
})(_TextTrackMenuItem3['default']);
_TextTrackMenuItem3['default'].registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
exports['default'] = CaptionSettingsMenuItem;
module.exports = exports['default'];
},{"./text-track-menu-item.js":29}],23:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _TextTrackButton2 = _dereq_('./text-track-button.js');
var _TextTrackButton3 = _interopRequireWildcard(_TextTrackButton2);
var _CaptionSettingsMenuItem = _dereq_('./caption-settings-menu-item.js');
var _CaptionSettingsMenuItem2 = _interopRequireWildcard(_CaptionSettingsMenuItem);
/**
* The button component for toggling and selecting captions
*
* @constructor
*/
var CaptionsButton = (function (_TextTrackButton) {
function CaptionsButton(player, options, ready) {
_classCallCheck(this, CaptionsButton);
_get(Object.getPrototypeOf(CaptionsButton.prototype), 'constructor', this).call(this, player, options, ready);
this.el_.setAttribute('aria-label', 'Captions Menu');
}
_inherits(CaptionsButton, _TextTrackButton);
_createClass(CaptionsButton, [{
key: 'update',
value: function update() {
var threshold = 2;
_get(Object.getPrototypeOf(CaptionsButton.prototype), 'update', this).call(this);
// if native, then threshold is 1 because no settings button
if (this.player().tech && this.player().tech.featuresNativeTextTracks) {
threshold = 1;
}
if (this.items && this.items.length > threshold) {
this.show();
} else {
this.hide();
}
}
}, {
key: 'createItems',
value: function createItems() {
var items = [];
if (!(this.player().tech && this.player().tech.featuresNativeTextTracks)) {
items.push(new _CaptionSettingsMenuItem2['default'](this.player_, { kind: this.kind_ }));
}
return _get(Object.getPrototypeOf(CaptionsButton.prototype), 'createItems', this).call(this, items);
}
}]);
return CaptionsButton;
})(_TextTrackButton3['default']);
CaptionsButton.prototype.kind_ = 'captions';
CaptionsButton.prototype.buttonText = 'Captions';
CaptionsButton.prototype.className = 'vjs-captions-button';
_TextTrackButton3['default'].registerComponent('CaptionsButton', CaptionsButton);
exports['default'] = CaptionsButton;
module.exports = exports['default'];
},{"./caption-settings-menu-item.js":22,"./text-track-button.js":28}],24:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _TextTrackButton2 = _dereq_('./text-track-button.js');
var _TextTrackButton3 = _interopRequireWildcard(_TextTrackButton2);
var _TextTrackMenuItem = _dereq_('./text-track-menu-item.js');
var _TextTrackMenuItem2 = _interopRequireWildcard(_TextTrackMenuItem);
var _ChaptersTrackMenuItem = _dereq_('./chapters-track-menu-item.js');
var _ChaptersTrackMenuItem2 = _interopRequireWildcard(_ChaptersTrackMenuItem);
var _Menu = _dereq_('../../menu/menu.js');
var _Menu2 = _interopRequireWildcard(_Menu);
var _import = _dereq_('../../lib.js');
var Lib = _interopRequireWildcard(_import);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
// Chapters act much differently than other text tracks
// Cues are navigation vs. other tracks of alternative languages
/**
* The button component for toggling and selecting chapters
*
* @constructor
*/
var ChaptersButton = (function (_TextTrackButton) {
function ChaptersButton(player, options, ready) {
_classCallCheck(this, ChaptersButton);
_get(Object.getPrototypeOf(ChaptersButton.prototype), 'constructor', this).call(this, player, options, ready);
this.el_.setAttribute('aria-label', 'Chapters Menu');
}
_inherits(ChaptersButton, _TextTrackButton);
_createClass(ChaptersButton, [{
key: 'createItems',
// Create a menu item for each text track
value: function createItems() {
var items = [];
var tracks = this.player_.textTracks();
if (!tracks) {
return items;
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
if (track.kind === this.kind_) {
items.push(new _TextTrackMenuItem2['default'](this.player_, {
track: track
}));
}
}
return items;
}
}, {
key: 'createMenu',
value: function createMenu() {
var tracks = this.player_.textTracks() || [];
var chaptersTrack = undefined;
var items = this.items = [];
for (var i = 0, l = tracks.length; i < l; i++) {
var track = tracks[i];
if (track.kind == this.kind_) {
if (!track.cues) {
track.mode = 'hidden';
/* jshint loopfunc:true */
// TODO see if we can figure out a better way of doing this https://github.com/videojs/video.js/issues/1864
_window2['default'].setTimeout(Lib.bind(this, function () {
this.createMenu();
}), 100);
/* jshint loopfunc:false */
} else {
chaptersTrack = track;
break;
}
}
}
var menu = this.menu;
if (menu === undefined) {
menu = new _Menu2['default'](this.player_);
menu.contentEl().appendChild(Lib.createEl('li', {
className: 'vjs-menu-title',
innerHTML: Lib.capitalize(this.kind_),
tabindex: -1
}));
}
if (chaptersTrack) {
var cues = chaptersTrack.cues,
cue = undefined;
for (var i = 0, l = cues.length; i < l; i++) {
cue = cues[i];
var mi = new _ChaptersTrackMenuItem2['default'](this.player_, {
track: chaptersTrack,
cue: cue
});
items.push(mi);
menu.addChild(mi);
}
this.addChild(menu);
}
if (this.items.length > 0) {
this.show();
}
return menu;
}
}]);
return ChaptersButton;
})(_TextTrackButton3['default']);
ChaptersButton.prototype.kind_ = 'chapters';
ChaptersButton.prototype.buttonText = 'Chapters';
ChaptersButton.prototype.className = 'vjs-chapters-button';
_TextTrackButton3['default'].registerComponent('ChaptersButton', ChaptersButton);
exports['default'] = ChaptersButton;
module.exports = exports['default'];
},{"../../lib.js":46,"../../menu/menu.js":51,"./chapters-track-menu-item.js":25,"./text-track-button.js":28,"./text-track-menu-item.js":29,"global/window":2}],25:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _MenuItem2 = _dereq_('../../menu/menu-item.js');
var _MenuItem3 = _interopRequireWildcard(_MenuItem2);
var _import = _dereq_('../../lib.js');
var Lib = _interopRequireWildcard(_import);
/**
* @constructor
*/
var ChaptersTrackMenuItem = (function (_MenuItem) {
function ChaptersTrackMenuItem(player, options) {
_classCallCheck(this, ChaptersTrackMenuItem);
var track = options.track;
var cue = options.cue;
var currentTime = player.currentTime();
// Modify options for parent MenuItem class's init.
options.label = cue.text;
options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
_get(Object.getPrototypeOf(ChaptersTrackMenuItem.prototype), 'constructor', this).call(this, player, options);
this.track = track;
this.cue = cue;
track.addEventListener('cuechange', Lib.bind(this, this.update));
}
_inherits(ChaptersTrackMenuItem, _MenuItem);
_createClass(ChaptersTrackMenuItem, [{
key: 'handleClick',
value: function handleClick() {
_get(Object.getPrototypeOf(ChaptersTrackMenuItem.prototype), 'handleClick', this).call(this);
this.player_.currentTime(this.cue.startTime);
this.update(this.cue.startTime);
}
}, {
key: 'update',
value: function update() {
var cue = this.cue;
var currentTime = this.player_.currentTime();
// vjs.log(currentTime, cue.startTime);
this.selected(cue.startTime <= currentTime && currentTime < cue.endTime);
}
}]);
return ChaptersTrackMenuItem;
})(_MenuItem3['default']);
_MenuItem3['default'].registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
exports['default'] = ChaptersTrackMenuItem;
module.exports = exports['default'];
},{"../../lib.js":46,"../../menu/menu-item.js":50}],26:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _TextTrackMenuItem2 = _dereq_('./text-track-menu-item.js');
var _TextTrackMenuItem3 = _interopRequireWildcard(_TextTrackMenuItem2);
/**
* A special menu item for turning of a specific type of text track
*
* @constructor
*/
var OffTextTrackMenuItem = (function (_TextTrackMenuItem) {
function OffTextTrackMenuItem(player, options) {
_classCallCheck(this, OffTextTrackMenuItem);
// Create pseudo track info
// Requires options['kind']
options.track = {
kind: options.kind,
player: player,
label: options.kind + ' off',
'default': false,
mode: 'disabled'
};
_get(Object.getPrototypeOf(OffTextTrackMenuItem.prototype), 'constructor', this).call(this, player, options);
this.selected(true);
}
_inherits(OffTextTrackMenuItem, _TextTrackMenuItem);
_createClass(OffTextTrackMenuItem, [{
key: 'handleTracksChange',
value: function handleTracksChange(event) {
var tracks = this.player().textTracks();
var selected = true;
for (var i = 0, l = tracks.length; i < l; i++) {
var track = tracks[i];
if (track.kind === this.track.kind && track.mode === 'showing') {
selected = false;
break;
}
}
this.selected(selected);
}
}]);
return OffTextTrackMenuItem;
})(_TextTrackMenuItem3['default']);
_TextTrackMenuItem3['default'].registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
exports['default'] = OffTextTrackMenuItem;
module.exports = exports['default'];
},{"./text-track-menu-item.js":29}],27:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _TextTrackButton2 = _dereq_('./text-track-button.js');
var _TextTrackButton3 = _interopRequireWildcard(_TextTrackButton2);
/**
* The button component for toggling and selecting subtitles
*
* @constructor
*/
var SubtitlesButton = (function (_TextTrackButton) {
function SubtitlesButton(player, options, ready) {
_classCallCheck(this, SubtitlesButton);
_get(Object.getPrototypeOf(SubtitlesButton.prototype), 'constructor', this).call(this, player, options, ready);
this.el_.setAttribute('aria-label', 'Subtitles Menu');
}
_inherits(SubtitlesButton, _TextTrackButton);
return SubtitlesButton;
})(_TextTrackButton3['default']);
SubtitlesButton.prototype.kind_ = 'subtitles';
SubtitlesButton.prototype.buttonText = 'Subtitles';
SubtitlesButton.prototype.className = 'vjs-subtitles-button';
_TextTrackButton3['default'].registerComponent('SubtitlesButton', SubtitlesButton);
exports['default'] = SubtitlesButton;
module.exports = exports['default'];
},{"./text-track-button.js":28}],28:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _MenuButton2 = _dereq_('../../menu/menu-button.js');
var _MenuButton3 = _interopRequireWildcard(_MenuButton2);
var _import = _dereq_('../../lib.js');
var Lib = _interopRequireWildcard(_import);
var _TextTrackMenuItem = _dereq_('./text-track-menu-item.js');
var _TextTrackMenuItem2 = _interopRequireWildcard(_TextTrackMenuItem);
var _OffTextTrackMenuItem = _dereq_('./off-text-track-menu-item.js');
var _OffTextTrackMenuItem2 = _interopRequireWildcard(_OffTextTrackMenuItem);
/**
* The base class for buttons that toggle specific text track types (e.g. subtitles)
*
* @constructor
*/
var TextTrackButton = (function (_MenuButton) {
function TextTrackButton(player, options) {
_classCallCheck(this, TextTrackButton);
_get(Object.getPrototypeOf(TextTrackButton.prototype), 'constructor', this).call(this, player, options);
var tracks = this.player_.textTracks();
if (this.items.length <= 1) {
this.hide();
}
if (!tracks) {
return;
}
var updateHandler = Lib.bind(this, this.update);
tracks.addEventListener('removetrack', updateHandler);
tracks.addEventListener('addtrack', updateHandler);
this.player_.on('dispose', function () {
tracks.removeEventListener('removetrack', updateHandler);
tracks.removeEventListener('addtrack', updateHandler);
});
}
_inherits(TextTrackButton, _MenuButton);
_createClass(TextTrackButton, [{
key: 'createItems',
// Create a menu item for each text track
value: function createItems() {
var items = arguments[0] === undefined ? [] : arguments[0];
// Add an OFF menu item to turn all tracks off
items.push(new _OffTextTrackMenuItem2['default'](this.player_, { kind: this.kind_ }));
var tracks = this.player_.textTracks();
if (!tracks) {
return items;
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
// only add tracks that are of the appropriate kind and have a label
if (track.kind === this.kind_) {
items.push(new _TextTrackMenuItem2['default'](this.player_, {
track: track
}));
}
}
return items;
}
}]);
return TextTrackButton;
})(_MenuButton3['default']);
_MenuButton3['default'].registerComponent('TextTrackButton', TextTrackButton);
exports['default'] = TextTrackButton;
module.exports = exports['default'];
},{"../../lib.js":46,"../../menu/menu-button.js":49,"./off-text-track-menu-item.js":26,"./text-track-menu-item.js":29}],29:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _MenuItem2 = _dereq_('../../menu/menu-item.js');
var _MenuItem3 = _interopRequireWildcard(_MenuItem2);
var _import = _dereq_('../../lib.js');
var Lib = _interopRequireWildcard(_import);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
/**
* The specific menu item type for selecting a language within a text track kind
*
* @constructor
*/
var TextTrackMenuItem = (function (_MenuItem) {
function TextTrackMenuItem(player, options) {
var _this = this;
_classCallCheck(this, TextTrackMenuItem);
var track = options.track;
var tracks = player.textTracks();
// Modify options for parent MenuItem class's init.
options.label = track.label || track.language || 'Unknown';
options.selected = track['default'] || track.mode === 'showing';
_get(Object.getPrototypeOf(TextTrackMenuItem.prototype), 'constructor', this).call(this, player, options);
this.track = track;
if (tracks) {
(function () {
var changeHandler = Lib.bind(_this, _this.handleTracksChange);
tracks.addEventListener('change', changeHandler);
_this.on('dispose', function () {
tracks.removeEventListener('change', changeHandler);
});
})();
}
// iOS7 doesn't dispatch change events to TextTrackLists when an
// associated track's mode changes. Without something like
// Object.observe() (also not present on iOS7), it's not
// possible to detect changes to the mode attribute and polyfill
// the change event. As a poor substitute, we manually dispatch
// change events whenever the controls modify the mode.
if (tracks && tracks.onchange === undefined) {
(function () {
var event = undefined;
_this.on(['tap', 'click'], function () {
if (typeof _window2['default'].Event !== 'object') {
// Android 2.3 throws an Illegal Constructor error for window.Event
try {
event = new _window2['default'].Event('change');
} catch (err) {}
}
if (!event) {
event = _document2['default'].createEvent('Event');
event.initEvent('change', true, true);
}
tracks.dispatchEvent(event);
});
})();
}
}
_inherits(TextTrackMenuItem, _MenuItem);
_createClass(TextTrackMenuItem, [{
key: 'handleClick',
value: function handleClick(event) {
var kind = this.track.kind;
var tracks = this.player_.textTracks();
_get(Object.getPrototypeOf(TextTrackMenuItem.prototype), 'handleClick', this).call(this, event);
if (!tracks) {
return;
}for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
if (track.kind !== kind) {
continue;
}
if (track === this.track) {
track.mode = 'showing';
} else {
track.mode = 'disabled';
}
}
}
}, {
key: 'handleTracksChange',
value: function handleTracksChange(event) {
this.selected(this.track.mode === 'showing');
}
}]);
return TextTrackMenuItem;
})(_MenuItem3['default']);
_MenuItem3['default'].registerComponent('TextTrackMenuItem', TextTrackMenuItem);
exports['default'] = TextTrackMenuItem;
module.exports = exports['default'];
},{"../../lib.js":46,"../../menu/menu-item.js":50,"global/document":1,"global/window":2}],30:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('../../lib.js');
var Lib = _interopRequireWildcard(_import);
/**
* Displays the current time
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var CurrentTimeDisplay = (function (_Component) {
function CurrentTimeDisplay(player, options) {
_classCallCheck(this, CurrentTimeDisplay);
_get(Object.getPrototypeOf(CurrentTimeDisplay.prototype), 'constructor', this).call(this, player, options);
this.on(player, 'timeupdate', this.updateContent);
}
_inherits(CurrentTimeDisplay, _Component);
_createClass(CurrentTimeDisplay, [{
key: 'createEl',
value: function createEl() {
var el = _get(Object.getPrototypeOf(CurrentTimeDisplay.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-current-time vjs-time-control vjs-control'
});
this.contentEl_ = Lib.createEl('div', {
className: 'vjs-current-time-display',
innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00', // label the current time for screen reader users
'aria-live': 'off' // tell screen readers not to automatically read the time as it changes
});
el.appendChild(this.contentEl_);
return el;
}
}, {
key: 'updateContent',
value: function updateContent() {
// Allows for smooth scrubbing, when player can't keep up.
var time = this.player_.scrubbing ? this.player_.getCache().currentTime : this.player_.currentTime();
var localizedText = this.localize('Current Time');
var formattedTime = Lib.formatTime(time, this.player_.duration());
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime;
}
}]);
return CurrentTimeDisplay;
})(_Component3['default']);
_Component3['default'].registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
exports['default'] = CurrentTimeDisplay;
module.exports = exports['default'];
},{"../../component.js":7,"../../lib.js":46}],31:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('../../lib.js');
var Lib = _interopRequireWildcard(_import);
/**
* Displays the duration
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var DurationDisplay = (function (_Component) {
function DurationDisplay(player, options) {
_classCallCheck(this, DurationDisplay);
_get(Object.getPrototypeOf(DurationDisplay.prototype), 'constructor', this).call(this, player, options);
// this might need to be changed to 'durationchange' instead of 'timeupdate' eventually,
// however the durationchange event fires before this.player_.duration() is set,
// so the value cannot be written out using this method.
// Once the order of durationchange and this.player_.duration() being set is figured out,
// this can be updated.
this.on(player, 'timeupdate', this.updateContent);
}
_inherits(DurationDisplay, _Component);
_createClass(DurationDisplay, [{
key: 'createEl',
value: function createEl() {
var el = _get(Object.getPrototypeOf(DurationDisplay.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-duration vjs-time-control vjs-control'
});
this.contentEl_ = Lib.createEl('div', {
className: 'vjs-duration-display',
innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> 0:00', // label the duration time for screen reader users
'aria-live': 'off' // tell screen readers not to automatically read the time as it changes
});
el.appendChild(this.contentEl_);
return el;
}
}, {
key: 'updateContent',
value: function updateContent() {
var duration = this.player_.duration();
if (duration) {
var localizedText = this.localize('Duration Time');
var formattedTime = Lib.formatTime(duration);
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; // label the duration time for screen reader users
}
}
}]);
return DurationDisplay;
})(_Component3['default']);
_Component3['default'].registerComponent('DurationDisplay', DurationDisplay);
exports['default'] = DurationDisplay;
module.exports = exports['default'];
},{"../../component.js":7,"../../lib.js":46}],32:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('../../lib');
var Lib = _interopRequireWildcard(_import);
/**
* Displays the time left in the video
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var RemainingTimeDisplay = (function (_Component) {
function RemainingTimeDisplay(player, options) {
_classCallCheck(this, RemainingTimeDisplay);
_get(Object.getPrototypeOf(RemainingTimeDisplay.prototype), 'constructor', this).call(this, player, options);
this.on(player, 'timeupdate', this.updateContent);
}
_inherits(RemainingTimeDisplay, _Component);
_createClass(RemainingTimeDisplay, [{
key: 'createEl',
value: function createEl() {
var el = _get(Object.getPrototypeOf(RemainingTimeDisplay.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-remaining-time vjs-time-control vjs-control'
});
this.contentEl_ = Lib.createEl('div', {
className: 'vjs-remaining-time-display',
innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> -0:00', // label the remaining time for screen reader users
'aria-live': 'off' // tell screen readers not to automatically read the time as it changes
});
el.appendChild(this.contentEl_);
return el;
}
}, {
key: 'updateContent',
value: function updateContent() {
if (this.player_.duration()) {
var localizedText = this.localize('Remaining Time');
var formattedTime = Lib.formatTime(this.player_.remainingTime());
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> -' + formattedTime;
}
// Allows for smooth scrubbing, when player can't keep up.
// var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime();
// this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration());
}
}]);
return RemainingTimeDisplay;
})(_Component3['default']);
_Component3['default'].registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
exports['default'] = RemainingTimeDisplay;
module.exports = exports['default'];
},{"../../component.js":7,"../../lib":46}],33:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
/**
* The separator between the current time and duration
*
* Can be hidden if it's not needed in the design.
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var TimeDivider = (function (_Component) {
function TimeDivider() {
_classCallCheck(this, TimeDivider);
if (_Component != null) {
_Component.apply(this, arguments);
}
}
_inherits(TimeDivider, _Component);
_createClass(TimeDivider, [{
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(TimeDivider.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-time-control vjs-time-divider',
innerHTML: '<div><span>/</span></div>'
});
}
}]);
return TimeDivider;
})(_Component3['default']);
_Component3['default'].registerComponent('TimeDivider', TimeDivider);
exports['default'] = TimeDivider;
module.exports = exports['default'];
},{"../../component.js":7}],34:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Slider2 = _dereq_('../../slider/slider.js');
var _Slider3 = _interopRequireWildcard(_Slider2);
var _import = _dereq_('../../lib.js');
var Lib = _interopRequireWildcard(_import);
// Required children
var _VolumeHandle = _dereq_('./volume-handle.js');
var _VolumeHandle2 = _interopRequireWildcard(_VolumeHandle);
var _VolumeLevel = _dereq_('./volume-level.js');
var _VolumeLevel2 = _interopRequireWildcard(_VolumeLevel);
/**
* The bar that contains the volume level and can be clicked on to adjust the level
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var VolumeBar = (function (_Slider) {
function VolumeBar(player, options) {
_classCallCheck(this, VolumeBar);
_get(Object.getPrototypeOf(VolumeBar.prototype), 'constructor', this).call(this, player, options);
this.on(player, 'volumechange', this.updateARIAAttributes);
player.ready(Lib.bind(this, this.updateARIAAttributes));
}
_inherits(VolumeBar, _Slider);
_createClass(VolumeBar, [{
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(VolumeBar.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-volume-bar',
'aria-label': 'volume level'
});
}
}, {
key: 'handleMouseMove',
value: function handleMouseMove(event) {
if (this.player_.muted()) {
this.player_.muted(false);
}
this.player_.volume(this.calculateDistance(event));
}
}, {
key: 'getPercent',
value: function getPercent() {
if (this.player_.muted()) {
return 0;
} else {
return this.player_.volume();
}
}
}, {
key: 'stepForward',
value: function stepForward() {
this.player_.volume(this.player_.volume() + 0.1);
}
}, {
key: 'stepBack',
value: function stepBack() {
this.player_.volume(this.player_.volume() - 0.1);
}
}, {
key: 'updateARIAAttributes',
value: function updateARIAAttributes() {
// Current value of volume bar as a percentage
this.el_.setAttribute('aria-valuenow', Lib.round(this.player_.volume() * 100, 2));
this.el_.setAttribute('aria-valuetext', Lib.round(this.player_.volume() * 100, 2) + '%');
}
}]);
return VolumeBar;
})(_Slider3['default']);
VolumeBar.prototype.options_ = {
children: {
volumeLevel: {},
volumeHandle: {}
},
barName: 'volumeLevel',
handleName: 'volumeHandle'
};
VolumeBar.prototype.playerEvent = 'volumechange';
_Slider3['default'].registerComponent('VolumeBar', VolumeBar);
exports['default'] = VolumeBar;
module.exports = exports['default'];
},{"../../lib.js":46,"../../slider/slider.js":58,"./volume-handle.js":36,"./volume-level.js":37}],35:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('../../lib.js');
var Lib = _interopRequireWildcard(_import);
// Required children
var _VolumeBar = _dereq_('./volume-bar.js');
var _VolumeBar2 = _interopRequireWildcard(_VolumeBar);
/**
* The component for controlling the volume level
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var VolumeControl = (function (_Component) {
function VolumeControl(player, options) {
_classCallCheck(this, VolumeControl);
_get(Object.getPrototypeOf(VolumeControl.prototype), 'constructor', this).call(this, player, options);
// hide volume controls when they're not supported by the current tech
if (player.tech && player.tech.featuresVolumeControl === false) {
this.addClass('vjs-hidden');
}
this.on(player, 'loadstart', function () {
if (player.tech.featuresVolumeControl === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
});
}
_inherits(VolumeControl, _Component);
_createClass(VolumeControl, [{
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(VolumeControl.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-volume-control vjs-control'
});
}
}]);
return VolumeControl;
})(_Component3['default']);
VolumeControl.prototype.options_ = {
children: {
volumeBar: {}
}
};
_Component3['default'].registerComponent('VolumeControl', VolumeControl);
exports['default'] = VolumeControl;
module.exports = exports['default'];
},{"../../component.js":7,"../../lib.js":46,"./volume-bar.js":34}],36:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _SliderHandle2 = _dereq_('../../slider/slider-handle.js');
var _SliderHandle3 = _interopRequireWildcard(_SliderHandle2);
/**
* The volume handle can be dragged to adjust the volume level
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var VolumeHandle = (function (_SliderHandle) {
function VolumeHandle() {
_classCallCheck(this, VolumeHandle);
if (_SliderHandle != null) {
_SliderHandle.apply(this, arguments);
}
}
_inherits(VolumeHandle, _SliderHandle);
_createClass(VolumeHandle, [{
key: 'createEl',
/** @inheritDoc */
value: function createEl() {
return _get(Object.getPrototypeOf(VolumeHandle.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-volume-handle'
});
}
}]);
return VolumeHandle;
})(_SliderHandle3['default']);
VolumeHandle.prototype.defaultValue = '00:00';
_SliderHandle3['default'].registerComponent('VolumeHandle', VolumeHandle);
exports['default'] = VolumeHandle;
module.exports = exports['default'];
},{"../../slider/slider-handle.js":57}],37:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
/**
* Shows volume level
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var VolumeLevel = (function (_Component) {
function VolumeLevel() {
_classCallCheck(this, VolumeLevel);
if (_Component != null) {
_Component.apply(this, arguments);
}
}
_inherits(VolumeLevel, _Component);
_createClass(VolumeLevel, [{
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(VolumeLevel.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-volume-level',
innerHTML: '<span class="vjs-control-text"></span>'
});
}
}]);
return VolumeLevel;
})(_Component3['default']);
_Component3['default'].registerComponent('VolumeLevel', VolumeLevel);
exports['default'] = VolumeLevel;
module.exports = exports['default'];
},{"../../component.js":7}],38:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Button = _dereq_('../button.js');
var _Button2 = _interopRequireWildcard(_Button);
var _Menu = _dereq_('../menu/menu.js');
var _Menu2 = _interopRequireWildcard(_Menu);
var _MenuButton2 = _dereq_('../menu/menu-button.js');
var _MenuButton3 = _interopRequireWildcard(_MenuButton2);
var _MuteToggle = _dereq_('./mute-toggle.js');
var _MuteToggle2 = _interopRequireWildcard(_MuteToggle);
var _import = _dereq_('../lib.js');
var Lib = _interopRequireWildcard(_import);
var _VolumeBar = _dereq_('./volume-control/volume-bar.js');
var _VolumeBar2 = _interopRequireWildcard(_VolumeBar);
/**
* Menu button with a popup for showing the volume slider.
* @constructor
*/
var VolumeMenuButton = (function (_MenuButton) {
function VolumeMenuButton(player, options) {
_classCallCheck(this, VolumeMenuButton);
_get(Object.getPrototypeOf(VolumeMenuButton.prototype), 'constructor', this).call(this, player, options);
// Same listeners as MuteToggle
this.on(player, 'volumechange', this.volumeUpdate);
// hide mute toggle if the current tech doesn't support volume control
if (player.tech && player.tech.featuresVolumeControl === false) {
this.addClass('vjs-hidden');
}
this.on(player, 'loadstart', function () {
if (player.tech.featuresVolumeControl === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
});
this.addClass('vjs-menu-button');
}
_inherits(VolumeMenuButton, _MenuButton);
_createClass(VolumeMenuButton, [{
key: 'createMenu',
value: function createMenu() {
var menu = new _Menu2['default'](this.player_, {
contentElType: 'div'
});
// The volumeBar is vertical by default in the base theme when used with a VolumeMenuButton
var options = this.options_.volumeBar || {};
options.vertical = options.vertical || true;
var vc = new _VolumeBar2['default'](this.player_, options);
vc.on('focus', function () {
menu.lockShowing();
});
vc.on('blur', function () {
menu.unlockShowing();
});
menu.addChild(vc);
return menu;
}
}, {
key: 'handleClick',
value: function handleClick() {
_MuteToggle2['default'].prototype.handleClick.call(this);
_get(Object.getPrototypeOf(VolumeMenuButton.prototype), 'handleClick', this).call(this);
}
}, {
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(VolumeMenuButton.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-volume-menu-button vjs-menu-button vjs-control vjs-button',
innerHTML: '<div><span class="vjs-control-text">' + this.localize('Mute') + '</span></div>'
});
}
}]);
return VolumeMenuButton;
})(_MenuButton3['default']);
VolumeMenuButton.prototype.volumeUpdate = _MuteToggle2['default'].prototype.update;
_Button2['default'].registerComponent('VolumeMenuButton', VolumeMenuButton);
exports['default'] = VolumeMenuButton;
module.exports = exports['default'];
},{"../button.js":6,"../lib.js":46,"../menu/menu-button.js":49,"../menu/menu.js":51,"./mute-toggle.js":11,"./volume-control/volume-bar.js":34}],39:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _import = _dereq_('./lib');
var Lib = _interopRequireWildcard(_import);
/**
* Core Object/Class for objects that use inheritance + constructors
*
* To create a class that can be subclassed itself, extend the CoreObject class.
*
* var Animal = CoreObject.extend();
* var Horse = Animal.extend();
*
* The constructor can be defined through the init property of an object argument.
*
* var Animal = CoreObject.extend({
* init: function(name, sound){
* this.name = name;
* }
* });
*
* Other methods and properties can be added the same way, or directly to the
* prototype.
*
* var Animal = CoreObject.extend({
* init: function(name){
* this.name = name;
* },
* getName: function(){
* return this.name;
* },
* sound: '...'
* });
*
* Animal.prototype.makeSound = function(){
* alert(this.sound);
* };
*
* To create an instance of a class, use the create method.
*
* var fluffy = Animal.create('Fluffy');
* fluffy.getName(); // -> Fluffy
*
* Methods and properties can be overridden in subclasses.
*
* var Horse = Animal.extend({
* sound: 'Neighhhhh!'
* });
*
* var horsey = Horse.create('Horsey');
* horsey.getName(); // -> Horsey
* horsey.makeSound(); // -> Alert: Neighhhhh!
*
* @class
* @constructor
*/
var CoreObject = function CoreObject() {};
// Manually exporting vjs['CoreObject'] here for Closure Compiler
// because of the use of the extend/create class methods
// If we didn't do this, those functions would get flattened to something like
// `a = ...` and `this.prototype` would refer to the global object instead of
// CoreObject
/**
* Create a new object that inherits from this Object
*
* var Animal = CoreObject.extend();
* var Horse = Animal.extend();
*
* @param {Object} props Functions and properties to be applied to the
* new object's prototype
* @return {CoreObject} An object that inherits from CoreObject
* @this {*}
*/
CoreObject.extend = function () {
var props = arguments[0] === undefined ? {} : arguments[0];
// Set up the constructor using the supplied init method
// or using the init of the parent object
// Make sure to check the unobfuscated version for external libs
var init = props.init || props.init || this.prototype.init || this.prototype.init || function () {};
// In Resig's simple class inheritance (previously used) the constructor
// is a function that calls `this.init.apply(arguments)`
// However that would prevent us from using `ParentObject.call(this);`
// in a Child constructor because the `this` in `this.init`
// would still refer to the Child and cause an infinite loop.
// We would instead have to do
// `ParentObject.prototype.init.apply(this, arguments);`
// Bleh. We're not creating a _super() function, so it's good to keep
// the parent constructor reference simple.
var subObj = function subObj() {
init.apply(this, arguments);
};
// Inherit from this object's prototype
subObj.prototype = Lib.obj.create(this.prototype);
// Reset the constructor property for subObj otherwise
// instances of subObj would have the constructor of the parent Object
subObj.prototype.constructor = subObj;
// Make the class extendable
subObj.extend = CoreObject.extend;
// Make a function for creating instances
subObj.create = CoreObject.create;
// Extend subObj's prototype with functions and other properties from props
for (var name in props) {
if (props.hasOwnProperty(name)) {
subObj.prototype[name] = props[name];
}
}
return subObj;
};
/**
* Create a new instance of this Object class
*
* var myAnimal = Animal.create();
*
* @return {CoreObject} An instance of a CoreObject subclass
* @this {*}
*/
CoreObject.create = function () {
// Create a new object that inherits from this object's prototype
var inst = Lib.obj.create(this.prototype);
// Apply this constructor function to the new object
this.apply(inst, arguments);
// Return the new object
return inst;
};
exports['default'] = CoreObject;
module.exports = exports['default'];
},{"./lib":46}],40:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
/**
* @fileoverview Main function src.
*/
var _Player = _dereq_('./player');
var _Player2 = _interopRequireWildcard(_Player);
var _Plugins = _dereq_('./plugins');
var _Plugins2 = _interopRequireWildcard(_Plugins);
var _Options = _dereq_('./options');
var _Options2 = _interopRequireWildcard(_Options);
var _import = _dereq_('./lib');
var Lib = _interopRequireWildcard(_import);
var _import2 = _dereq_('./util');
var VjsUtil = _interopRequireWildcard(_import2);
var _CoreObject = _dereq_('./core-object');
var _CoreObject2 = _interopRequireWildcard(_CoreObject);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
/**
* Doubles as the main function for users to create a player instance and also
* the main library object.
*
* **ALIASES** videojs, _V_ (deprecated)
*
* The `vjs` function can be used to initialize or retrieve a player.
*
* var myPlayer = vjs('my_video_id');
*
* @param {String|Element} id Video element or video element ID
* @param {Object=} options Optional options object for config/settings
* @param {Function=} ready Optional ready callback
* @return {Player} A player instance
* @namespace
*/
var videojs = function videojs(id, options, ready) {
var tag; // Element of ID
// Allow for element or ID to be passed in
// String ID
if (typeof id === 'string') {
// Adjust for jQuery ID syntax
if (id.indexOf('#') === 0) {
id = id.slice(1);
}
// If a player instance has already been created for this ID return it.
if (_Player2['default'].players[id]) {
// If options or ready funtion are passed, warn
if (options) {
Lib.log.warn('Player "' + id + '" is already initialised. Options will not be applied.');
}
if (ready) {
_Player2['default'].players[id].ready(ready);
}
return _Player2['default'].players[id];
// Otherwise get element for ID
} else {
tag = Lib.el(id);
}
// ID is a media element
} else {
tag = id;
}
// Check for a useable element
if (!tag || !tag.nodeName) {
// re: nodeName, could be a box div also
throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns
}
// Element may have a player attr referring to an already created player instance.
// If not, set up a new player and return the instance.
return tag.player || new _Player2['default'](tag, options, ready);
};
// CDN Version. Used to target right flash swf.
videojs.CDN_VERSION = '5.0';
videojs.ACCESS_PROTOCOL = 'https:' == _document2['default'].location.protocol ? 'https://' : 'http://';
/**
* Full player version
* @type {string}
*/
videojs.VERSION = '5.0.0-2';
// Set CDN Version of swf
// The added (+) blocks the replace from changing this _VERSION_NO_PATCH_ string
if (videojs.CDN_VERSION !== '__VERSION_' + 'NO_PATCH__') {
_Options2['default'].flash.swf = '' + videojs.ACCESS_PROTOCOL + 'vjs.zencdn.net/' + videojs.CDN_VERSION + '/video-js.swf';
}
/**
* Utility function for adding languages to the default options. Useful for
* amending multiple language support at runtime.
*
* Example: videojs.addLanguage('es', {'Hello':'Hola'});
*
* @param {String} code The language code or dictionary property
* @param {Object} data The data values to be translated
* @return {Object} The resulting global languages dictionary object
*/
videojs.addLanguage = function (code, data) {
if (_Options2['default'].languages[code] !== undefined) {
_Options2['default'].languages[code] = VjsUtil.mergeOptions(_Options2['default'].languages[code], data);
} else {
_Options2['default'].languages[code] = data;
}
return _Options2['default'].languages;
};
/**
* Custom Universal Module Definition (UMD)
*
* Video.js will never be a non-browser lib so we can simplify UMD a bunch and
* still support requirejs and browserify. This also needs to be closure
* compiler compatible, so string keys are used.
*/
if (typeof define === 'function' && define.amd) {
define('videojs', [], function () {
return videojs;
});
// checking that module is an object too because of umdjs/umd#35
} else if (typeof exports === 'object' && typeof module === 'object') {
module.exports = videojs;
}
exports['default'] = videojs;
module.exports = exports['default'];
},{"./core-object":39,"./lib":46,"./options":52,"./player":53,"./plugins":54,"./util":70,"global/document":1}],41:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('./component');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('./lib');
var Lib = _interopRequireWildcard(_import);
/**
* Display that an error has occurred making the video unplayable
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var ErrorDisplay = (function (_Component) {
function ErrorDisplay(player, options) {
_classCallCheck(this, ErrorDisplay);
_get(Object.getPrototypeOf(ErrorDisplay.prototype), 'constructor', this).call(this, player, options);
this.update();
this.on(player, 'error', this.update);
}
_inherits(ErrorDisplay, _Component);
_createClass(ErrorDisplay, [{
key: 'createEl',
value: function createEl() {
var el = _get(Object.getPrototypeOf(ErrorDisplay.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-error-display'
});
this.contentEl_ = Lib.createEl('div');
el.appendChild(this.contentEl_);
return el;
}
}, {
key: 'update',
value: function update() {
if (this.player().error()) {
this.contentEl_.innerHTML = this.localize(this.player().error().message);
}
}
}]);
return ErrorDisplay;
})(_Component3['default']);
_Component3['default'].registerComponent('ErrorDisplay', ErrorDisplay);
exports['default'] = ErrorDisplay;
module.exports = exports['default'];
},{"./component":7,"./lib":46}],42:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _import = _dereq_('./events');
var Events = _interopRequireWildcard(_import);
var _import2 = _dereq_('./lib');
var Lib = _interopRequireWildcard(_import2);
var EventEmitter = function EventEmitter() {};
EventEmitter.prototype.allowedEvents_ = {};
EventEmitter.prototype.on = function (type, fn) {
// Remove the addEventListener alias before calling Events.on
// so we don't get into an infinite type loop
var ael = this.addEventListener;
this.addEventListener = Function.prototype;
Events.on(this, type, fn);
this.addEventListener = ael;
};
EventEmitter.prototype.addEventListener = EventEmitter.prototype.on;
EventEmitter.prototype.off = function (type, fn) {
Events.off(this, type, fn);
};
EventEmitter.prototype.removeEventListener = EventEmitter.prototype.off;
EventEmitter.prototype.one = function (type, fn) {
Events.one(this, type, fn);
};
EventEmitter.prototype.trigger = function (event) {
var type = event.type || event;
if (typeof event === 'string') {
event = {
type: type
};
}
event = Events.fixEvent(event);
if (this.allowedEvents_[type] && this['on' + type]) {
this['on' + type](event);
}
Events.trigger(this, event);
};
// The standard DOM EventTarget.dispatchEvent() is aliased to trigger()
EventEmitter.prototype.dispatchEvent = EventEmitter.prototype.trigger;
exports['default'] = EventEmitter;
module.exports = exports['default'];
},{"./events":43,"./lib":46}],43:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
/**
* @fileoverview Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
* (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
* This should work very similarly to jQuery's events, however it's based off the book version which isn't as
* robust as jquery's, so there's probably some differences.
*/
var _import = _dereq_('./lib');
var Lib = _interopRequireWildcard(_import);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
/**
* Fix a native event to have standard property values
* @param {Object} event Event object to fix
* @return {Object}
* @private
*/
var fixEvent = function fixEvent(event) {
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Test if fixing up is needed
// Used to check if !event.stopPropagation instead of isPropagationStopped
// But native events return true for stopPropagation, but don't have
// other expected methods like isPropagationStopped. Seems to be a problem
// with the Javascript Ninja code. So we're just overriding all events now.
if (!event || !event.isPropagationStopped) {
var old = event || _window2['default'].event;
event = {};
// Clone the old object so that we can modify the values event = {};
// IE8 Doesn't like when you mess with native event properties
// Firefox returns false for event.hasOwnProperty('type') and other props
// which makes copying more difficult.
// TODO: Probably best to create a whitelist of event props
for (var key in old) {
// Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
// Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation') {
// Chrome 32+ warns if you try to copy deprecated returnValue, but
// we still want to if preventDefault isn't supported (IE8).
if (!(key === 'returnValue' && old.preventDefault)) {
event[key] = old[key];
}
}
}
// The event occurred on this element
if (!event.target) {
event.target = event.srcElement || _document2['default'];
}
// Handle which other element the event is related to
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
// Stop the default browser action
event.preventDefault = function () {
if (old.preventDefault) {
old.preventDefault();
}
event.returnValue = false;
event.defaultPrevented = true;
};
event.defaultPrevented = false;
// Stop the event from bubbling
event.stopPropagation = function () {
if (old.stopPropagation) {
old.stopPropagation();
}
event.cancelBubble = true;
event.isPropagationStopped = returnTrue;
};
event.isPropagationStopped = returnFalse;
// Stop the event from bubbling and executing other handlers
event.stopImmediatePropagation = function () {
if (old.stopImmediatePropagation) {
old.stopImmediatePropagation();
}
event.isImmediatePropagationStopped = returnTrue;
event.stopPropagation();
};
event.isImmediatePropagationStopped = returnFalse;
// Handle mouse position
if (event.clientX != null) {
var doc = _document2['default'].documentElement,
body = _document2['default'].body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// Handle key presses
event.which = event.charCode || event.keyCode;
// Fix button for mouse clicks:
// 0 == left; 1 == middle; 2 == right
if (event.button != null) {
event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
}
}
// Returns fixed-up instance
return event;
};
/**
* Add an event listener to element
* It stores the handler function in a separate cache object
* and adds a generic handler to the element's event,
* along with a unique id (guid) to the element.
* @param {Element|Object} elem Element or object to bind listeners to
* @param {String|Array} type Type of event to bind to.
* @param {Function} fn Event listener.
* @private
*/
var on = (function (_on) {
function on(_x, _x2, _x3) {
return _on.apply(this, arguments);
}
on.toString = function () {
return on.toString();
};
return on;
})(function (elem, type, fn) {
if (Lib.obj.isArray(type)) {
return _handleMultipleEvents(on, elem, type, fn);
}
var data = Lib.getData(elem);
// We need a place to store all our handler data
if (!data.handlers) data.handlers = {};
if (!data.handlers[type]) data.handlers[type] = [];
if (!fn.guid) fn.guid = Lib.guid++;
data.handlers[type].push(fn);
if (!data.dispatcher) {
data.disabled = false;
data.dispatcher = function (event) {
if (data.disabled) return;
event = fixEvent(event);
var handlers = data.handlers[event.type];
if (handlers) {
// Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
var handlersCopy = handlers.slice(0);
for (var m = 0, n = handlersCopy.length; m < n; m++) {
if (event.isImmediatePropagationStopped()) {
break;
} else {
handlersCopy[m].call(elem, event);
}
}
}
};
}
if (data.handlers[type].length == 1) {
if (elem.addEventListener) {
elem.addEventListener(type, data.dispatcher, false);
} else if (elem.attachEvent) {
elem.attachEvent('on' + type, data.dispatcher);
}
}
});
/**
* Removes event listeners from an element
* @param {Element|Object} elem Object to remove listeners from
* @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element.
* @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type.
* @private
*/
var off = (function (_off) {
function off(_x4, _x5, _x6) {
return _off.apply(this, arguments);
}
off.toString = function () {
return off.toString();
};
return off;
})(function (elem, type, fn) {
// Don't want to add a cache object through getData if not needed
if (!Lib.hasData(elem)) return;
var data = Lib.getData(elem);
// If no events exist, nothing to unbind
if (!data.handlers) {
return;
}
if (Lib.obj.isArray(type)) {
return _handleMultipleEvents(off, elem, type, fn);
}
// Utility function
var removeType = function removeType(t) {
data.handlers[t] = [];
cleanUpEvents(elem, t);
};
// Are we removing all bound events?
if (!type) {
for (var t in data.handlers) {
removeType(t);
}return;
}
var handlers = data.handlers[type];
// If no handlers exist, nothing to unbind
if (!handlers) return;
// If no listener was provided, remove all listeners for type
if (!fn) {
removeType(type);
return;
}
// We're only removing a single handler
if (fn.guid) {
for (var n = 0; n < handlers.length; n++) {
if (handlers[n].guid === fn.guid) {
handlers.splice(n--, 1);
}
}
}
cleanUpEvents(elem, type);
});
/**
* Clean up the listener cache and dispatchers
* @param {Element|Object} elem Element to clean up
* @param {String} type Type of event to clean up
* @private
*/
var cleanUpEvents = function cleanUpEvents(elem, type) {
var data = Lib.getData(elem);
// Remove the events of a particular type if there are none left
if (data.handlers[type].length === 0) {
delete data.handlers[type];
// data.handlers[type] = null;
// Setting to null was causing an error with data.handlers
// Remove the meta-handler from the element
if (elem.removeEventListener) {
elem.removeEventListener(type, data.dispatcher, false);
} else if (elem.detachEvent) {
elem.detachEvent('on' + type, data.dispatcher);
}
}
// Remove the events object if there are no types left
if (Lib.isEmpty(data.handlers)) {
delete data.handlers;
delete data.dispatcher;
delete data.disabled;
// data.handlers = null;
// data.dispatcher = null;
// data.disabled = null;
}
// Finally remove the expando if there is no data left
if (Lib.isEmpty(data)) {
Lib.removeData(elem);
}
};
/**
* Trigger an event for an element
* @param {Element|Object} elem Element to trigger an event on
* @param {Event|Object|String} event A string (the type) or an event object with a type attribute
* @private
*/
var trigger = (function (_trigger) {
function trigger(_x7, _x8) {
return _trigger.apply(this, arguments);
}
trigger.toString = function () {
return trigger.toString();
};
return trigger;
})(function (elem, event) {
// Fetches element data and a reference to the parent (for bubbling).
// Don't want to add a data object to cache for every parent,
// so checking hasData first.
var elemData = Lib.hasData(elem) ? Lib.getData(elem) : {};
var parent = elem.parentNode || elem.ownerDocument;
// type = event.type || event,
// handler;
// If an event name was passed as a string, creates an event out of it
if (typeof event === 'string') {
event = { type: event, target: elem };
}
// Normalizes the event properties.
event = fixEvent(event);
// If the passed element has a dispatcher, executes the established handlers.
if (elemData.dispatcher) {
elemData.dispatcher.call(elem, event);
}
// Unless explicitly stopped or the event does not bubble (e.g. media events)
// recursively calls this function to bubble the event up the DOM.
if (parent && !event.isPropagationStopped() && event.bubbles !== false) {
trigger(parent, event);
// If at the top of the DOM, triggers the default action unless disabled.
} else if (!parent && !event.defaultPrevented) {
var targetData = Lib.getData(event.target);
// Checks if the target has a default action for this event.
if (event.target[event.type]) {
// Temporarily disables event dispatching on the target as we have already executed the handler.
targetData.disabled = true;
// Executes the default action.
if (typeof event.target[event.type] === 'function') {
event.target[event.type]();
}
// Re-enables event dispatching.
targetData.disabled = false;
}
}
// Inform the triggerer if the default was prevented by returning false
return !event.defaultPrevented;
});
/**
* Trigger a listener only once for an event
* @param {Element|Object} elem Element or object to
* @param {String|Array} type
* @param {Function} fn
* @private
*/
var one = (function (_one) {
function one(_x9, _x10, _x11) {
return _one.apply(this, arguments);
}
one.toString = function () {
return one.toString();
};
return one;
})(function (elem, type, fn) {
if (Lib.obj.isArray(type)) {
return _handleMultipleEvents(one, elem, type, fn);
}
var func = (function (_func) {
function func() {
return _func.apply(this, arguments);
}
func.toString = function () {
return func.toString();
};
return func;
})(function () {
off(elem, type, func);
fn.apply(this, arguments);
});
// copy the guid to the new function so it can removed using the original function's ID
func.guid = fn.guid = fn.guid || Lib.guid++;
on(elem, type, func);
});
/**
* Loops through an array of event types and calls the requested method for each type.
* @param {Function} fn The event method we want to use.
* @param {Element|Object} elem Element or object to bind listeners to
* @param {String} type Type of event to bind to.
* @param {Function} callback Event listener.
* @private
*/
function _handleMultipleEvents(fn, elem, type, callback) {
Lib.arr.forEach(type, function (type) {
fn(elem, type, callback); //Call the event method for each one of the types
});
}
exports.on = on;
exports.off = off;
exports.cleanUpEvents = cleanUpEvents;
exports.fixEvent = fixEvent;
exports.one = one;
exports.trigger = trigger;
},{"./lib":46,"global/document":1,"global/window":2}],44:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _import = _dereq_('./lib');
var Lib = _interopRequireWildcard(_import);
/**
* A combination of node inherits and babel's inherits (after transpile).
* Both work the same but node adds `super_` to the subClass
* and Bable adds the superClass as __proto__. Both seem useful.
*/
var _inherits = function _inherits(subClass, superClass) {
if (typeof superClass !== 'function' && superClass !== null) {
throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) {
// node
subClass.super_ = superClass;
}
};
/**
* Function for subclassing using the same inheritance that
* videojs uses internally
*
* ```
* var Button = videojs.getComponent('Button');
*
* var MyButton = videojs.extends(Button, {
* constructor: function(player, options) {
* Button.call(this, player, options);
* },
*
* onClick: function() {
* // doSomething
* }
* });
* ```
*/
var extendsFn = function extendsFn(superClass) {
var subClassMethods = arguments[1] === undefined ? {} : arguments[1];
var subClass = function subClass() {
superClass.apply(this, arguments);
};
var methods = {};
if (subClassMethods.constructor !== Object.prototype.constructor) {
subClass = subClassMethods.constructor;
methods = subClassMethods;
} else if (typeof subClassMethods === 'function') {
subClass = subClassMethods;
}
_inherits(subClass, superClass);
// Extend subObj's prototype with functions and other properties from props
for (var name in methods) {
if (methods.hasOwnProperty(name)) {
subClass.prototype[name] = methods[name];
}
}
return subClass;
};
exports['default'] = extendsFn;
module.exports = exports['default'];
},{"./lib":46}],45:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
/**
* Store the browser-specific methods for the fullscreen API
* @type {Object|undefined}
* @private
*/
var FullscreenApi = {};
// browser API methods
// map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js
var apiMap = [
// Spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html
['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'],
// WebKit
['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'],
// Old WebKit (Safari 5.1)
['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'],
// Mozilla
['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'],
// Microsoft
['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']];
var specApi = apiMap[0];
var browserApi = undefined;
// determine the supported set of functions
for (var i = 0; i < apiMap.length; i++) {
// check for exitFullscreen function
if (apiMap[i][1] in _document2['default']) {
browserApi = apiMap[i];
break;
}
}
// map the browser API names to the spec API names
if (browserApi) {
for (var i = 0; i < browserApi.length; i++) {
FullscreenApi[specApi[i]] = browserApi[i];
}
}
exports['default'] = FullscreenApi;
module.exports = exports['default'];
},{"global/document":1}],46:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
var navigator = _window2['default'].navigator;
var hasOwnProp = Object.prototype.hasOwnProperty;
/**
* Creates an element and applies properties.
* @param {String=} tagName Name of tag to be created.
* @param {Object=} properties Element properties to be applied.
* @return {Element}
* @private
*/
var createEl = function createEl() {
var tagName = arguments[0] === undefined ? 'div' : arguments[0];
var properties = arguments[1] === undefined ? {} : arguments[1];
var el = _document2['default'].createElement(tagName);
obj.each(properties, function (propName, val) {
// Not remembering why we were checking for dash
// but using setAttribute means you have to use getAttribute
// The check for dash checks for the aria-* attributes, like aria-label, aria-valuemin.
// The additional check for "role" is because the default method for adding attributes does not
// add the attribute "role". My guess is because it's not a valid attribute in some namespaces, although
// browsers handle the attribute just fine. The W3C allows for aria-* attributes to be used in pre-HTML5 docs.
// http://www.w3.org/TR/wai-aria-primer/#ariahtml. Using setAttribute gets around this problem.
if (propName.indexOf('aria-') !== -1 || propName == 'role') {
el.setAttribute(propName, val);
} else {
el[propName] = val;
}
});
return el;
};
/**
* Uppercase the first letter of a string
* @param {String} string String to be uppercased
* @return {String}
* @private
*/
var capitalize = function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
/**
* Object functions container
* @type {Object}
* @private
*/
var obj = {};
/**
* Object.create shim for prototypal inheritance
*
* https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
*
* @function
* @param {Object} obj Object to use as prototype
* @private
*/
obj.create = Object.create || function (obj) {
//Create a new function called 'F' which is just an empty object.
function F() {}
//the prototype of the 'F' function should point to the
//parameter of the anonymous function.
F.prototype = obj;
//create a new constructor function based off of the 'F' function.
return new F();
};
/**
* Loop through each property in an object and call a function
* whose arguments are (key,value)
* @param {Object} obj Object of properties
* @param {Function} fn Function to be called on each property.
* @this {*}
* @private
*/
obj.each = function (obj, fn, context) {
for (var key in obj) {
if (hasOwnProp.call(obj, key)) {
fn.call(context || this, key, obj[key]);
}
}
};
/**
* Merge two objects together and return the original.
* @param {Object} obj1
* @param {Object} obj2
* @return {Object}
* @private
*/
obj.merge = function (obj1, obj2) {
if (!obj2) {
return obj1;
}
for (var key in obj2) {
if (hasOwnProp.call(obj2, key)) {
obj1[key] = obj2[key];
}
}
return obj1;
};
/**
* Merge two objects, and merge any properties that are objects
* instead of just overwriting one. Uses to merge options hashes
* where deeper default settings are important.
* @param {Object} obj1 Object to override
* @param {Object} obj2 Overriding object
* @return {Object} New object. Obj1 and Obj2 will be untouched.
* @private
*/
obj.deepMerge = function (obj1, obj2) {
var key, val1, val2;
// make a copy of obj1 so we're not overwriting original values.
// like prototype.options_ and all sub options objects
obj1 = obj.copy(obj1);
for (key in obj2) {
if (hasOwnProp.call(obj2, key)) {
val1 = obj1[key];
val2 = obj2[key];
// Check if both properties are pure objects and do a deep merge if so
if (obj.isPlain(val1) && obj.isPlain(val2)) {
obj1[key] = obj.deepMerge(val1, val2);
} else {
obj1[key] = obj2[key];
}
}
}
return obj1;
};
/**
* Make a copy of the supplied object
* @param {Object} obj Object to copy
* @return {Object} Copy of object
* @private
*/
obj.copy = function (objToCopy) {
return obj.merge({}, objToCopy);
};
/**
* Check if an object is plain, and not a dom node or any object sub-instance
* @param {Object} obj Object to check
* @return {Boolean} True if plain, false otherwise
* @private
*/
obj.isPlain = function (obj) {
return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object;
};
/**
* Check if an object is Array
* Since instanceof Array will not work on arrays created in another frame we need to use Array.isArray, but since IE8 does not support Array.isArray we need this shim
* @param {Object} obj Object to check
* @return {Boolean} True if plain, false otherwise
* @private
*/
obj.isArray = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) === '[object Array]';
};
/**
* Bind (a.k.a proxy or Context). A simple method for changing the context of a function
It also stores a unique id on the function so it can be easily removed from events
* @param {*} context The object to bind as scope
* @param {Function} fn The function to be bound to a scope
* @param {Number=} uid An optional unique ID for the function to be set
* @return {Function}
* @private
*/
var bind = function bind(context, fn, uid) {
// Make sure the function has a unique ID
if (!fn.guid) {
fn.guid = (exports.guid = guid += 1, guid - 1);
}
// Create the new function that changes the context
var ret = function ret() {
return fn.apply(context, arguments);
};
// Allow for the ability to individualize this function
// Needed in the case where multiple objects might share the same prototype
// IF both items add an event listener with the same function, then you try to remove just one
// it will remove both because they both have the same guid.
// when using this, you need to use the bind method when you remove the listener as well.
// currently used in text tracks
ret.guid = uid ? uid + '_' + fn.guid : fn.guid;
return ret;
};
/**
* Element Data Store. Allows for binding data to an element without putting it directly on the element.
* Ex. Event listeners are stored here.
* (also from jsninja.com, slightly modified and updated for closure compiler)
* @type {Object}
* @private
*/
var cache = {};
/**
* Unique ID for an element or function
* @type {Number}
* @private
*/
var guid = 1;
/**
* Unique attribute name to store an element's guid in
* @type {String}
* @constant
* @private
*/
var expando = 'vdata' + new Date().getTime();
/**
* Returns the cache object where data for an element is stored
* @param {Element} el Element to store data for.
* @return {Object}
* @private
*/
var getData = function getData(el) {
var id = el[expando];
if (!id) {
id = el[expando] = (exports.guid = guid += 1, guid - 1);
}
if (!cache[id]) {
cache[id] = {};
}
return cache[id];
};
/**
* Returns the cache object where data for an element is stored
* @param {Element} el Element to store data for.
* @return {Object}
* @private
*/
var hasData = function hasData(el) {
var id = el[expando];
return !(!id || isEmpty(cache[id]));
};
/**
* Delete data for the element from the cache and the guid attr from getElementById
* @param {Element} el Remove data for an element
* @private
*/
var removeData = function removeData(el) {
var id = el[expando];
if (!id) {
return;
}
// Remove all stored data
// Changed to = null
// http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/
// cache[id] = null;
delete cache[id];
// Remove the expando property from the DOM node
try {
delete el[expando];
} catch (e) {
if (el.removeAttribute) {
el.removeAttribute(expando);
} else {
// IE doesn't appear to support removeAttribute on the document element
el[expando] = null;
}
}
};
/**
* Check if an object is empty
* @param {Object} obj The object to check for emptiness
* @return {Boolean}
* @private
*/
var isEmpty = function isEmpty(obj) {
for (var prop in obj) {
// Inlude null properties as empty.
if (obj[prop] !== null) {
return false;
}
}
return true;
};
/**
* Check if an element has a CSS class
* @param {Element} element Element to check
* @param {String} classToCheck Classname to check
* @private
*/
var hasClass = function hasClass(element, classToCheck) {
return (' ' + element.className + ' ').indexOf(' ' + classToCheck + ' ') !== -1;
};
/**
* Add a CSS class name to an element
* @param {Element} element Element to add class name to
* @param {String} classToAdd Classname to add
* @private
*/
var addClass = function addClass(element, classToAdd) {
if (!hasClass(element, classToAdd)) {
element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd;
}
};
/**
* Remove a CSS class name from an element
* @param {Element} element Element to remove from class name
* @param {String} classToAdd Classname to remove
* @private
*/
var removeClass = function removeClass(element, classToRemove) {
if (!hasClass(element, classToRemove)) {
return;
}
var classNames = element.className.split(' ');
// no arr.indexOf in ie8, and we don't want to add a big shim
for (var i = classNames.length - 1; i >= 0; i--) {
if (classNames[i] === classToRemove) {
classNames.splice(i, 1);
}
}
element.className = classNames.join(' ');
};
/**
* Element for testing browser HTML5 video capabilities
* @type {Element}
* @constant
* @private
*/
var TEST_VID = createEl('video');
var track = _document2['default'].createElement('track');
track.kind = 'captions';
track.srclang = 'en';
track.label = 'English';
TEST_VID.appendChild(track);
/**
* Useragent for browser testing.
* @type {String}
* @constant
* @private
*/
var USER_AGENT = navigator.userAgent;
/**
* Device is an iPhone
* @type {Boolean}
* @constant
* @private
*/
var IS_IPHONE = /iPhone/i.test(USER_AGENT);
var IS_IPAD = /iPad/i.test(USER_AGENT);
var IS_IPOD = /iPod/i.test(USER_AGENT);
var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
var IOS_VERSION = (function () {
var match = USER_AGENT.match(/OS (\d+)_/i);
if (match && match[1]) {
return match[1];
}
})();
var IS_ANDROID = /Android/i.test(USER_AGENT);
var ANDROID_VERSION = (function () {
// This matches Android Major.Minor.Patch versions
// ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i),
major,
minor;
if (!match) {
return null;
}
major = match[1] && parseFloat(match[1]);
minor = match[2] && parseFloat(match[2]);
if (major && minor) {
return parseFloat(match[1] + '.' + match[2]);
} else if (major) {
return major;
} else {
return null;
}
})();
// Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser
var IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3;
var IS_FIREFOX = /Firefox/i.test(USER_AGENT);
var IS_CHROME = /Chrome/i.test(USER_AGENT);
var IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT);
var TOUCH_ENABLED = !!('ontouchstart' in _window2['default'] || _window2['default'].DocumentTouch && _document2['default'] instanceof _window2['default'].DocumentTouch);
var BACKGROUND_SIZE_SUPPORTED = ('backgroundSize' in TEST_VID.style);
/**
* Apply attributes to an HTML element.
* @param {Element} el Target element.
* @param {Object=} attributes Element attributes to be applied.
* @private
*/
var setElementAttributes = function setElementAttributes(el, attributes) {
obj.each(attributes, function (attrName, attrValue) {
if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
el.removeAttribute(attrName);
} else {
el.setAttribute(attrName, attrValue === true ? '' : attrValue);
}
});
};
/**
* Get an element's attribute values, as defined on the HTML tag
* Attributes are not the same as properties. They're defined on the tag
* or with setAttribute (which shouldn't be used with HTML)
* This will return true or false for boolean attributes.
* @param {Element} tag Element from which to get tag attributes
* @return {Object}
* @private
*/
var getElementAttributes = function getElementAttributes(tag) {
var obj, knownBooleans, attrs, attrName, attrVal;
obj = {};
// known boolean attributes
// we can check for matching boolean properties, but older browsers
// won't know about HTML5 boolean attributes that we still read from
knownBooleans = ',' + 'autoplay,controls,loop,muted,default' + ',';
if (tag && tag.attributes && tag.attributes.length > 0) {
attrs = tag.attributes;
for (var i = attrs.length - 1; i >= 0; i--) {
attrName = attrs[i].name;
attrVal = attrs[i].value;
// check for known booleans
// the matching element property will return a value for typeof
if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) {
// the value of an included boolean attribute is typically an empty
// string ('') which would equal false if we just check for a false value.
// we also don't want support bad code like autoplay='false'
attrVal = attrVal !== null ? true : false;
}
obj[attrName] = attrVal;
}
}
return obj;
};
/**
* Get the computed style value for an element
* From http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/
* @param {Element} el Element to get style value for
* @param {String} strCssRule Style name
* @return {String} Style value
* @private
*/
var getComputedDimension = function getComputedDimension(el, strCssRule) {
var strValue = '';
if (_document2['default'].defaultView && _document2['default'].defaultView.getComputedStyle) {
strValue = _document2['default'].defaultView.getComputedStyle(el, '').getPropertyValue(strCssRule);
} else if (el.currentStyle) {
// IE8 Width/Height support
var upperCasedRule = strCssRule.substr(0, 1).toUpperCase() + strCssRule.substr(1);
strValue = el['client' + upperCasedRule] + 'px';
}
return strValue;
};
/**
* Insert an element as the first child node of another
* @param {Element} child Element to insert
* @param {[type]} parent Element to insert child into
* @private
*/
var insertFirst = function insertFirst(child, parent) {
if (parent.firstChild) {
parent.insertBefore(child, parent.firstChild);
} else {
parent.appendChild(child);
}
};
/**
* Object to hold browser support information
* @type {Object}
* @private
*/
var browser = {};
/**
* Shorthand for document.getElementById()
* Also allows for CSS (jQuery) ID syntax. But nothing other than IDs.
* @param {String} id Element ID
* @return {Element} Element with supplied ID
* @private
*/
var el = function el(id) {
if (id.indexOf('#') === 0) {
id = id.slice(1);
}
return _document2['default'].getElementById(id);
};
/**
* Format seconds as a time string, H:MM:SS or M:SS
* Supplying a guide (in seconds) will force a number of leading zeros
* to cover the length of the guide
* @param {Number} seconds Number of seconds to be turned into a string
* @param {Number} guide Number (in seconds) to model the string after
* @return {String} Time formatted as H:MM:SS or M:SS
* @private
*/
var formatTime = function formatTime(seconds) {
var guide = arguments[1] === undefined ? seconds : arguments[1];
return (function () {
var s = Math.floor(seconds % 60);
var m = Math.floor(seconds / 60 % 60);
var h = Math.floor(seconds / 3600);
var gm = Math.floor(guide / 60 % 60);
var gh = Math.floor(guide / 3600);
// handle invalid times
if (isNaN(seconds) || seconds === Infinity) {
// '-' is false for all relational operators (e.g. <, >=) so this setting
// will add the minimum number of fields specified by the guide
h = m = s = '-';
}
// Check if we need to show hours
h = h > 0 || gh > 0 ? h + ':' : '';
// If hours are showing, we may need to add a leading zero.
// Always show at least one digit of minutes.
m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':';
// Check if leading zero is need for seconds
s = s < 10 ? '0' + s : s;
return h + m + s;
})();
};
// Attempt to block the ability to select text while dragging controls
var blockTextSelection = function blockTextSelection() {
_document2['default'].body.focus();
_document2['default'].onselectstart = function () {
return false;
};
};
// Turn off text selection blocking
var unblockTextSelection = function unblockTextSelection() {
_document2['default'].onselectstart = function () {
return true;
};
};
/**
* Trim whitespace from the ends of a string.
* @param {String} string String to trim
* @return {String} Trimmed string
* @private
*/
var trim = function trim(str) {
return (str + '').replace(/^\s+|\s+$/g, '');
};
/**
* Should round off a number to a decimal place
* @param {Number} num Number to round
* @param {Number} dec Number of decimal places to round to
* @return {Number} Rounded number
* @private
*/
var round = function round(num) {
var dec = arguments[1] === undefined ? 0 : arguments[1];
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
};
/**
* Should create a fake TimeRange object
* Mimics an HTML5 time range instance, which has functions that
* return the start and end times for a range
* TimeRanges are returned by the buffered() method
* @param {Number} start Start time in seconds
* @param {Number} end End time in seconds
* @return {Object} Fake TimeRange object
* @private
*/
var createTimeRange = function createTimeRange(start, end) {
return {
length: 1,
start: (function (_start) {
function start() {
return _start.apply(this, arguments);
}
start.toString = function () {
return start.toString();
};
return start;
})(function () {
return start;
}),
end: (function (_end) {
function end() {
return _end.apply(this, arguments);
}
end.toString = function () {
return end.toString();
};
return end;
})(function () {
return end;
})
};
};
/**
* Add to local storage (maybe removable)
* @private
*/
var setLocalStorage = function setLocalStorage(key, value) {
try {
// IE was throwing errors referencing the var anywhere without this
var _localStorage = _window2['default'].localStorage || false;
if (!_localStorage) {
return;
}
_localStorage[key] = value;
} catch (e) {
if (e.code == 22 || e.code == 1014) {
// Webkit == 22 / Firefox == 1014
log('LocalStorage Full (VideoJS)', e);
} else {
if (e.code == 18) {
log('LocalStorage not allowed (VideoJS)', e);
} else {
log('LocalStorage Error (VideoJS)', e);
}
}
}
};
/**
* Get absolute version of relative URL. Used to tell flash correct URL.
* http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
* @param {String} url URL to make absolute
* @return {String} Absolute URL
* @private
*/
var getAbsoluteURL = function getAbsoluteURL(url) {
// Check if absolute URL
if (!url.match(/^https?:\/\//)) {
// Convert to absolute URL. Flash hosted off-site needs an absolute URL.
url = createEl('div', {
innerHTML: '<a href="' + url + '">x</a>'
}).firstChild.href;
}
return url;
};
/**
* Resolve and parse the elements of a URL
* @param {String} url The url to parse
* @return {Object} An object of url details
*/
var parseUrl = function parseUrl(url) {
var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];
// add the url to an anchor and let the browser parse the URL
var a = createEl('a', { href: url });
// IE8 (and 9?) Fix
// ie8 doesn't parse the URL correctly until the anchor is actually
// added to the body, and an innerHTML is needed to trigger the parsing
var addToBody = a.host === '' && a.protocol !== 'file:';
var div = undefined;
if (addToBody) {
div = createEl('div');
div.innerHTML = '<a href="' + url + '"></a>';
a = div.firstChild;
// prevent the div from affecting layout
div.setAttribute('style', 'display:none; position:absolute;');
_document2['default'].body.appendChild(div);
}
// Copy the specific URL properties to a new object
// This is also needed for IE8 because the anchor loses its
// properties when it's removed from the dom
var details = {};
for (var i = 0; i < props.length; i++) {
details[props[i]] = a[props[i]];
}
// IE9 adds the port to the host property unlike everyone else. If
// a port identifier is added for standard ports, strip it.
if (details.protocol === 'http:') {
details.host = details.host.replace(/:80$/, '');
}
if (details.protocol === 'https:') {
details.host = details.host.replace(/:443$/, '');
}
if (addToBody) {
_document2['default'].body.removeChild(div);
}
return details;
};
/**
* Log messages to the console and history based on the type of message
*
* @param {String} type The type of message, or `null` for `log`
* @param {[type]} args The args to be passed to the log
* @private
*/
function _logType(type, args) {
// convert args to an array to get array functions
var argsArray = Array.prototype.slice.call(args);
// if there's no console then don't try to output messages
// they will still be stored in Lib.log.history
// Was setting these once outside of this function, but containing them
// in the function makes it easier to test cases where console doesn't exist
var noop = function noop() {};
var console = _window2['default'].console || {
log: noop,
warn: noop,
error: noop
};
if (type) {
// add the type to the front of the message
argsArray.unshift(type.toUpperCase() + ':');
} else {
// default to log with no prefix
type = 'log';
}
// add to history
log.history.push(argsArray);
// add console prefix after adding to history
argsArray.unshift('VIDEOJS:');
// call appropriate log function
if (console[type].apply) {
console[type].apply(console, argsArray);
} else {
// ie8 doesn't allow error.apply, but it will just join() the array anyway
console[type](argsArray.join(' '));
}
}
/**
* Log plain debug messages
*/
var log = function log() {
_logType(null, arguments);
};
/**
* Keep a history of log messages
* @type {Array}
*/
log.history = [];
/**
* Log error messages
*/
log.error = function () {
_logType('error', arguments);
};
/**
* Log warning messages
*/
log.warn = function () {
_logType('warn', arguments);
};
// Offset Left
// getBoundingClientRect technique from John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/
var findPosition = function findPosition(el) {
var box = undefined;
if (el.getBoundingClientRect && el.parentNode) {
box = el.getBoundingClientRect();
}
if (!box) {
return {
left: 0,
top: 0
};
}
var docEl = _document2['default'].documentElement;
var body = _document2['default'].body;
var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var scrollLeft = _window2['default'].pageXOffset || body.scrollLeft;
var left = box.left + scrollLeft - clientLeft;
var clientTop = docEl.clientTop || body.clientTop || 0;
var scrollTop = _window2['default'].pageYOffset || body.scrollTop;
var top = box.top + scrollTop - clientTop;
// Android sometimes returns slightly off decimal values, so need to round
return {
left: round(left),
top: round(top)
};
};
/**
* Array functions container
* @type {Object}
* @private
*/
var arr = {};
/*
* Loops through an array and runs a function for each item inside it.
* @param {Array} array The array
* @param {Function} callback The function to be run for each item
* @param {*} thisArg The `this` binding of callback
* @returns {Array} The array
* @private
*/
arr.forEach = function (array, callback, thisArg) {
thisArg = thisArg || this;
if (obj.isArray(array) && callback instanceof Function) {
for (var i = 0, len = array.length; i < len; ++i) {
callback.call(thisArg, array[i], i, array);
}
}
return array;
};
/**
* Returns the extension of the passed file name. It will return an empty string if you pass an invalid path
*
* @param {String} path The fileName path like '/path/to/file.mp4'
* @returns {String} The extension in lower case or an empty string if no extension could be found.
*/
var getFileExtension = function getFileExtension(path) {
if (typeof path === 'string') {
var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i;
var pathParts = splitPathRe.exec(path);
if (pathParts) {
return pathParts.pop().toLowerCase();
}
}
return '';
};
exports.createEl = createEl;
exports.capitalize = capitalize;
exports.obj = obj;
exports.isNaN = isNaN;
exports.bind = bind;
exports.cache = cache;
exports.guid = guid;
exports.expando = expando;
exports.getData = getData;
exports.hasData = hasData;
exports.removeData = removeData;
exports.isEmpty = isEmpty;
exports.hasClass = hasClass;
exports.addClass = addClass;
exports.removeClass = removeClass;
exports.TEST_VID = TEST_VID;
exports.USER_AGENT = USER_AGENT;
exports.IS_IPHONE = IS_IPHONE;
exports.IS_IPAD = IS_IPAD;
exports.IS_IPOD = IS_IPOD;
exports.IS_IOS = IS_IOS;
exports.IOS_VERSION = IOS_VERSION;
exports.IS_ANDROID = IS_ANDROID;
exports.ANDROID_VERSION = ANDROID_VERSION;
exports.IS_OLD_ANDROID = IS_OLD_ANDROID;
exports.IS_FIREFOX = IS_FIREFOX;
exports.IS_IE8 = IS_IE8;
exports.IS_CHROME = IS_CHROME;
exports.TOUCH_ENABLED = TOUCH_ENABLED;
exports.BACKGROUND_SIZE_SUPPORTED = BACKGROUND_SIZE_SUPPORTED;
exports.setElementAttributes = setElementAttributes;
exports.getElementAttributes = getElementAttributes;
exports.getComputedDimension = getComputedDimension;
exports.insertFirst = insertFirst;
exports.browser = browser;
exports.el = el;
exports.formatTime = formatTime;
exports.blockTextSelection = blockTextSelection;
exports.unblockTextSelection = unblockTextSelection;
exports.trim = trim;
exports.round = round;
exports.createTimeRange = createTimeRange;
exports.setLocalStorage = setLocalStorage;
exports.getAbsoluteURL = getAbsoluteURL;
exports.parseUrl = parseUrl;
exports.log = log;
exports.findPosition = findPosition;
exports.arr = arr;
exports.getFileExtension = getFileExtension;
},{"global/document":1,"global/window":2}],47:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('./component');
var _Component3 = _interopRequireWildcard(_Component2);
/* Loading Spinner
================================================================================ */
/**
* Loading spinner for waiting events
* @param {Player|Object} player
* @param {Object=} options
* @class
* @constructor
*/
var LoadingSpinner = (function (_Component) {
function LoadingSpinner() {
_classCallCheck(this, LoadingSpinner);
if (_Component != null) {
_Component.apply(this, arguments);
}
}
_inherits(LoadingSpinner, _Component);
_createClass(LoadingSpinner, [{
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(LoadingSpinner.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-loading-spinner'
});
}
}]);
return LoadingSpinner;
})(_Component3['default']);
_Component3['default'].registerComponent('LoadingSpinner', LoadingSpinner);
exports['default'] = LoadingSpinner;
module.exports = exports['default'];
},{"./component":7}],48:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _import = _dereq_('./lib');
var Lib = _interopRequireWildcard(_import);
/**
* Custom MediaError to mimic the HTML5 MediaError
* @param {Number} code The media error code
*/
var MediaError = (function (_MediaError) {
function MediaError(_x) {
return _MediaError.apply(this, arguments);
}
MediaError.toString = function () {
return MediaError.toString();
};
return MediaError;
})(function (code) {
if (typeof code === 'number') {
this.code = code;
} else if (typeof code === 'string') {
// default code is zero, so this is a custom error
this.message = code;
} else if (typeof code === 'object') {
// object
Lib.obj.merge(this, code);
}
if (!this.message) {
this.message = MediaError.defaultMessages[this.code] || '';
}
});
/**
* The error code that refers two one of the defined
* MediaError types
* @type {Number}
*/
MediaError.prototype.code = 0;
/**
* An optional message to be shown with the error.
* Message is not part of the HTML5 video spec
* but allows for more informative custom errors.
* @type {String}
*/
MediaError.prototype.message = '';
/**
* An optional status code that can be set by plugins
* to allow even more detail about the error.
* For example the HLS plugin might provide the specific
* HTTP status code that was returned when the error
* occurred, then allowing a custom error overlay
* to display more information.
* @type {[type]}
*/
MediaError.prototype.status = null;
MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', // = 0
'MEDIA_ERR_ABORTED', // = 1
'MEDIA_ERR_NETWORK', // = 2
'MEDIA_ERR_DECODE', // = 3
'MEDIA_ERR_SRC_NOT_SUPPORTED', // = 4
'MEDIA_ERR_ENCRYPTED' // = 5
];
MediaError.defaultMessages = {
1: 'You aborted the video playback',
2: 'A network error caused the video download to fail part-way.',
3: 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support.',
4: 'The video could not be loaded, either because the server or network failed or because the format is not supported.',
5: 'The video is encrypted and we do not have the keys to decrypt it.'
};
// Add types as properties on MediaError
// e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) {
MediaError[MediaError.errorTypes[errNum]] = errNum;
// values should be accessible on both the class and instance
MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
}
exports['default'] = MediaError;
module.exports = exports['default'];
},{"./lib":46}],49:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Button2 = _dereq_('../button.js');
var _Button3 = _interopRequireWildcard(_Button2);
var _Menu = _dereq_('./menu.js');
var _Menu2 = _interopRequireWildcard(_Menu);
var _import = _dereq_('../lib.js');
var Lib = _interopRequireWildcard(_import);
/**
* A button class with a popup menu
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var MenuButton = (function (_Button) {
function MenuButton(player, options) {
_classCallCheck(this, MenuButton);
_get(Object.getPrototypeOf(MenuButton.prototype), 'constructor', this).call(this, player, options);
this.update();
this.on('keydown', this.handleKeyPress);
this.el_.setAttribute('aria-haspopup', true);
this.el_.setAttribute('role', 'button');
}
_inherits(MenuButton, _Button);
_createClass(MenuButton, [{
key: 'update',
value: function update() {
var menu = this.createMenu();
if (this.menu) {
this.removeChild(this.menu);
}
this.menu = menu;
this.addChild(menu);
/**
* Track the state of the menu button
* @type {Boolean}
* @private
*/
this.buttonPressed_ = false;
if (this.items && this.items.length === 0) {
this.hide();
} else if (this.items && this.items.length > 1) {
this.show();
}
}
}, {
key: 'createMenu',
value: function createMenu() {
var menu = new _Menu2['default'](this.player_);
// Add a title list item to the top
if (this.options().title) {
menu.contentEl().appendChild(Lib.createEl('li', {
className: 'vjs-menu-title',
innerHTML: Lib.capitalize(this.options().title),
tabindex: -1
}));
}
this.items = this.createItems();
if (this.items) {
// Add menu items to the menu
for (var i = 0; i < this.items.length; i++) {
menu.addItem(this.items[i]);
}
}
return menu;
}
}, {
key: 'createItems',
/**
* Create the list of menu items. Specific to each subclass.
*/
value: function createItems() {}
}, {
key: 'buildCSSClass',
/** @inheritDoc */
value: function buildCSSClass() {
return '' + this.className + ' vjs-menu-button ' + _get(Object.getPrototypeOf(MenuButton.prototype), 'buildCSSClass', this).call(this);
}
}, {
key: 'handleFocus',
// Focus - Add keyboard functionality to element
// This function is not needed anymore. Instead, the keyboard functionality is handled by
// treating the button as triggering a submenu. When the button is pressed, the submenu
// appears. Pressing the button again makes the submenu disappear.
value: function handleFocus() {}
}, {
key: 'handleBlur',
// Can't turn off list display that we turned on with focus, because list would go away.
value: function handleBlur() {}
}, {
key: 'handleClick',
value: function handleClick() {
// When you click the button it adds focus, which will show the menu indefinitely.
// So we'll remove focus when the mouse leaves the button.
// Focus is needed for tab navigation.
this.one('mouseout', Lib.bind(this, function () {
this.menu.unlockShowing();
this.el_.blur();
}));
if (this.buttonPressed_) {
this.unpressButton();
} else {
this.pressButton();
}
}
}, {
key: 'handleKeyPress',
value: function handleKeyPress(event) {
// Check for space bar (32) or enter (13) keys
if (event.which == 32 || event.which == 13) {
if (this.buttonPressed_) {
this.unpressButton();
} else {
this.pressButton();
}
event.preventDefault();
// Check for escape (27) key
} else if (event.which == 27) {
if (this.buttonPressed_) {
this.unpressButton();
}
event.preventDefault();
}
}
}, {
key: 'pressButton',
value: function pressButton() {
this.buttonPressed_ = true;
this.menu.lockShowing();
this.el_.setAttribute('aria-pressed', true);
if (this.items && this.items.length > 0) {
this.items[0].el().focus(); // set the focus to the title of the submenu
}
}
}, {
key: 'unpressButton',
value: function unpressButton() {
this.buttonPressed_ = false;
this.menu.unlockShowing();
this.el_.setAttribute('aria-pressed', false);
}
}]);
return MenuButton;
})(_Button3['default']);
_Button3['default'].registerComponent('MenuButton', MenuButton);
exports['default'] = MenuButton;
module.exports = exports['default'];
},{"../button.js":6,"../lib.js":46,"./menu.js":51}],50:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Button2 = _dereq_('../button.js');
var _Button3 = _interopRequireWildcard(_Button2);
var _import = _dereq_('../lib.js');
var Lib = _interopRequireWildcard(_import);
/**
* The component for a menu item. `<li>`
*
* @param {Player|Object} player
* @param {Object=} options
* @class
* @constructor
*/
var MenuItem = (function (_Button) {
function MenuItem(player, options) {
_classCallCheck(this, MenuItem);
_get(Object.getPrototypeOf(MenuItem.prototype), 'constructor', this).call(this, player, options);
this.selected(options.selected);
}
_inherits(MenuItem, _Button);
_createClass(MenuItem, [{
key: 'createEl',
/** @inheritDoc */
value: function createEl(type, props) {
return _get(Object.getPrototypeOf(MenuItem.prototype), 'createEl', this).call(this, 'li', Lib.obj.merge({
className: 'vjs-menu-item',
innerHTML: this.localize(this.options_.label)
}, props));
}
}, {
key: 'handleClick',
/**
* Handle a click on the menu item, and set it to selected
*/
value: function handleClick() {
this.selected(true);
}
}, {
key: 'selected',
/**
* Set this menu item as selected or not
* @param {Boolean} selected
*/
value: (function (_selected) {
function selected(_x) {
return _selected.apply(this, arguments);
}
selected.toString = function () {
return selected.toString();
};
return selected;
})(function (selected) {
if (selected) {
this.addClass('vjs-selected');
this.el_.setAttribute('aria-selected', true);
} else {
this.removeClass('vjs-selected');
this.el_.setAttribute('aria-selected', false);
}
})
}]);
return MenuItem;
})(_Button3['default']);
_Button3['default'].registerComponent('MenuItem', MenuItem);
exports['default'] = MenuItem;
module.exports = exports['default'];
},{"../button.js":6,"../lib.js":46}],51:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('../lib.js');
var Lib = _interopRequireWildcard(_import);
var _import2 = _dereq_('../events.js');
var Events = _interopRequireWildcard(_import2);
/* Menu
================================================================================ */
/**
* The Menu component is used to build pop up menus, including subtitle and
* captions selection menus.
*
* @param {Player|Object} player
* @param {Object=} options
* @class
* @constructor
*/
var Menu = (function (_Component) {
function Menu() {
_classCallCheck(this, Menu);
if (_Component != null) {
_Component.apply(this, arguments);
}
}
_inherits(Menu, _Component);
_createClass(Menu, [{
key: 'addItem',
/**
* Add a menu item to the menu
* @param {Object|String} component Component or component type to add
*/
value: function addItem(component) {
this.addChild(component);
component.on('click', Lib.bind(this, function () {
this.unlockShowing();
}));
}
}, {
key: 'createEl',
value: function createEl() {
var contentElType = this.options().contentElType || 'ul';
this.contentEl_ = Lib.createEl(contentElType, {
className: 'vjs-menu-content'
});
var el = _get(Object.getPrototypeOf(Menu.prototype), 'createEl', this).call(this, 'div', {
append: this.contentEl_,
className: 'vjs-menu'
});
el.appendChild(this.contentEl_);
// Prevent clicks from bubbling up. Needed for Menu Buttons,
// where a click on the parent is significant
Events.on(el, 'click', function (event) {
event.preventDefault();
event.stopImmediatePropagation();
});
return el;
}
}]);
return Menu;
})(_Component3['default']);
_Component3['default'].registerComponent('Menu', Menu);
exports['default'] = Menu;
module.exports = exports['default'];
},{"../component.js":7,"../events.js":43,"../lib.js":46}],52:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
var navigator = _window2['default'].navigator;
/**
* Global Player instance options, surfaced from Player.prototype.options_
* options = Player.prototype.options_
* All options should use string keys so they avoid
* renaming by closure compiler
* @type {Object}
*/
exports['default'] = {
// Default order of fallback technology
techOrder: ['html5', 'flash'],
// techOrder: ['flash','html5'],
html5: {},
flash: {},
// Default of web browser is 300x150. Should rely on source width/height.
width: 300,
height: 150,
// defaultVolume: 0.85,
defaultVolume: 0, // The freakin seaguls are driving me crazy!
// default inactivity timeout
inactivityTimeout: 2000,
// default playback rates
playbackRates: [],
// Add playback rate selection by adding rates
// 'playbackRates': [0.5, 1, 1.5, 2],
// Included control sets
children: {
mediaLoader: {},
posterImage: {},
textTrackDisplay: {},
loadingSpinner: {},
bigPlayButton: {},
controlBar: {},
errorDisplay: {},
textTrackSettings: {}
},
language: _document2['default'].getElementsByTagName('html')[0].getAttribute('lang') || navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language || 'en',
// locales and their language translations
languages: {},
// Default message to show when a video cannot be played.
notSupportedMessage: 'No compatible source was found for this video.'
};
module.exports = exports['default'];
},{"global/document":1,"global/window":2}],53:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('./component.js');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('./lib.js');
var Lib = _interopRequireWildcard(_import);
var _import2 = _dereq_('./events.js');
var Events = _interopRequireWildcard(_import2);
var _FullscreenApi = _dereq_('./fullscreen-api.js');
var _FullscreenApi2 = _interopRequireWildcard(_FullscreenApi);
var _MediaError = _dereq_('./media-error.js');
var _MediaError2 = _interopRequireWildcard(_MediaError);
var _Options = _dereq_('./options.js');
var _Options2 = _interopRequireWildcard(_Options);
var _safeParseTuple = _dereq_('safe-json-parse/tuple');
var _safeParseTuple2 = _interopRequireWildcard(_safeParseTuple);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
// Include required child components
var _MediaLoader = _dereq_('./tech/loader.js');
var _MediaLoader2 = _interopRequireWildcard(_MediaLoader);
var _Poster = _dereq_('./poster-image.js');
var _Poster2 = _interopRequireWildcard(_Poster);
var _TextTrackDisplay = _dereq_('./tracks/text-track-display.js');
var _TextTrackDisplay2 = _interopRequireWildcard(_TextTrackDisplay);
var _LoadingSpinner = _dereq_('./loading-spinner.js');
var _LoadingSpinner2 = _interopRequireWildcard(_LoadingSpinner);
var _BigPlayButton = _dereq_('./big-play-button.js');
var _BigPlayButton2 = _interopRequireWildcard(_BigPlayButton);
var _controlBar = _dereq_('./control-bar/control-bar.js');
var _controlBar2 = _interopRequireWildcard(_controlBar);
var _ErrorDisplay = _dereq_('./error-display.js');
var _ErrorDisplay2 = _interopRequireWildcard(_ErrorDisplay);
var _TextTrackSettings = _dereq_('./tracks/text-track-settings.js');
var _TextTrackSettings2 = _interopRequireWildcard(_TextTrackSettings);
// Require html5 for disposing the original video tag
var _Html5 = _dereq_('./tech/html5.js');
var _Html52 = _interopRequireWildcard(_Html5);
/**
* An instance of the `Player` class is created when any of the Video.js setup methods are used to initialize a video.
*
* ```js
* var myPlayer = videojs('example_video_1');
* ```
*
* In the following example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready.
*
* ```html
* <video id="example_video_1" data-setup='{}' controls>
* <source src="my-source.mp4" type="video/mp4">
* </video>
* ```
*
* After an instance has been created it can be accessed globally using `Video('example_video_1')`.
*
* @class
* @extends Component
*/
var Player = (function (_Component) {
/**
* player's constructor function
*
* @constructs
* @method init
* @param {Element} tag The original video tag used for configuring options
* @param {Object=} options Player options
* @param {Function=} ready Ready callback function
*/
function Player(tag, options, ready) {
_classCallCheck(this, Player);
// Make sure tag ID exists
tag.id = tag.id || 'vjs_video_' + Lib.guid++;
// Set Options
// The options argument overrides options set in the video tag
// which overrides globally set options.
// This latter part coincides with the load order
// (tag must exist before Player)
options = Lib.obj.merge(Player.getTagSettings(tag), options);
// Delay the initialization of children because we need to set up
// player properties first, and can't use `this` before `super()`
options.initChildren = false;
// Same with creating the element
options.createEl = false;
// we don't want the player to report touch activity on itself
// see enableTouchActivity in Component
options.reportTouchActivity = false;
// Run base component initializing with new options
_get(Object.getPrototypeOf(Player.prototype), 'constructor', this).call(this, null, options, ready);
// if the global option object was accidentally blown away by
// someone, bail early with an informative error
if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) {
throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
}
this.tag = tag; // Store the original tag used to set options
// Store the tag attributes used to restore html5 element
this.tagAttributes = tag && Lib.getElementAttributes(tag);
// Update Current Language
this.language_ = options.language || _Options2['default'].language;
// Update Supported Languages
this.languages_ = options.languages || _Options2['default'].languages;
// Cache for video property values.
this.cache_ = {};
// Set poster
this.poster_ = options.poster || '';
// Set controls
this.controls_ = !!options.controls;
// Original tag settings stored in options
// now remove immediately so native controls don't flash.
// May be turned back on by HTML5 tech if nativeControlsForTouch is true
tag.controls = false;
/**
* Store the internal state of scrubbing
* @private
* @return {Boolean} True if the user is scrubbing
*/
this.scrubbing_ = false;
this.el_ = this.createEl();
// Load plugins
if (options.plugins) {
Lib.obj.each(options.plugins, function (key, val) {
this[key](val);
}, this);
}
this.initChildren();
// Set isAudio based on whether or not an audio tag was used
this.isAudio(tag.nodeName.toLowerCase() === 'audio');
// Update controls className. Can't do this when the controls are initially
// set because the element doesn't exist yet.
if (this.controls()) {
this.addClass('vjs-controls-enabled');
} else {
this.addClass('vjs-controls-disabled');
}
if (this.isAudio()) {
this.addClass('vjs-audio');
}
if (this.flexNotSupported_()) {
this.addClass('vjs-no-flex');
}
// TODO: Make this smarter. Toggle user state between touching/mousing
// using events, since devices can have both touch and mouse events.
// if (Lib.TOUCH_ENABLED) {
// this.addClass('vjs-touch-enabled');
// }
// Make player easily findable by ID
Player.players[this.id_] = this;
// When the player is first initialized, trigger activity so components
// like the control bar show themselves if needed
this.userActive_ = true;
this.reportUserActivity();
this.listenForUserActivity();
}
_inherits(Player, _Component);
_createClass(Player, [{
key: 'dispose',
/**
* Destroys the video player and does any necessary cleanup
*
* myPlayer.dispose();
*
* This is especially helpful if you are dynamically adding and removing videos
* to/from the DOM.
*/
value: function dispose() {
this.trigger('dispose');
// prevent dispose from being called twice
this.off('dispose');
// Kill reference to this player
Player.players[this.id_] = null;
if (this.tag && this.tag.player) {
this.tag.player = null;
}
if (this.el_ && this.el_.player) {
this.el_.player = null;
}
if (this.tech) {
this.tech.dispose();
}
_get(Object.getPrototypeOf(Player.prototype), 'dispose', this).call(this);
}
}, {
key: 'createEl',
value: function createEl() {
var el = this.el_ = _get(Object.getPrototypeOf(Player.prototype), 'createEl', this).call(this, 'div');
var tag = this.tag;
// Remove width/height attrs from tag so CSS can make it 100% width/height
tag.removeAttribute('width');
tag.removeAttribute('height');
// Copy over all the attributes from the tag, including ID and class
// ID will now reference player box, not the video tag
var attrs = Lib.getElementAttributes(tag);
Lib.obj.each(attrs, function (attr) {
// workaround so we don't totally break IE7
// http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7
if (attr == 'class') {
el.className = attrs[attr];
} else {
el.setAttribute(attr, attrs[attr]);
}
});
// Update tag id/class for use as HTML5 playback tech
// Might think we should do this after embedding in container so .vjs-tech class
// doesn't flash 100% width/height, but class only applies with .video-js parent
tag.id += '_html5_api';
tag.className = 'vjs-tech';
// Make player findable on elements
tag.player = el.player = this;
// Default state of video is paused
this.addClass('vjs-paused');
// Make box use width/height of tag, or rely on default implementation
// Enforce with CSS since width/height attrs don't work on divs
this.width(this.options_.width, true); // (true) Skip resize listener on load
this.height(this.options_.height, true);
// Lib.insertFirst seems to cause the networkState to flicker from 3 to 2, so
// keep track of the original for later so we can know if the source originally failed
tag.initNetworkState_ = tag.networkState;
// Wrap video tag in div (el/box) container
if (tag.parentNode) {
tag.parentNode.insertBefore(el, tag);
}
Lib.insertFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup.
// The event listeners need to be added before the children are added
// in the component init because the tech (loaded with mediaLoader) may
// fire events, like loadstart, that these events need to capture.
// Long term it might be better to expose a way to do this in component.init
// like component.initEventListeners() that runs between el creation and
// adding children
this.el_ = el;
this.on('loadstart', this.handleLoadStart);
this.on('waiting', this.handleWaiting);
this.on(['canplay', 'canplaythrough', 'playing', 'ended'], this.handleWaitEnd);
this.on('seeking', this.handleSeeking);
this.on('seeked', this.handleSeeked);
this.on('ended', this.handleEnded);
this.on('play', this.handlePlay);
this.on('firstplay', this.handleFirstPlay);
this.on('pause', this.handlePause);
this.on('progress', this.handleProgress);
this.on('durationchange', this.handleDurationChange);
this.on('fullscreenchange', this.handleFullscreenChange);
return el;
}
}, {
key: 'loadTech',
/**
* Load the Media Playback Technology (tech)
* Load/Create an instance of playback technology including element and API methods
* And append playback element in player div.
*/
value: function loadTech(techName, source) {
// Pause and remove current playback technology
if (this.tech) {
this.unloadTech();
}
// get rid of the HTML5 video tag as soon as we are using another tech
if (techName !== 'Html5' && this.tag) {
_Component3['default'].getComponent('Html5').disposeMediaElement(this.tag);
this.tag = null;
}
this.techName = techName;
// Turn off API access because we're loading a new tech that might load asynchronously
this.isReady_ = false;
var techReady = function techReady() {
this.player_.triggerReady();
};
// Grab tech-specific options from player options and add source and parent element to use.
var techOptions = Lib.obj.merge({ source: source, parentEl: this.el_ }, this.options_[techName.toLowerCase()]);
if (source) {
this.currentType_ = source.type;
if (source.src == this.cache_.src && this.cache_.currentTime > 0) {
techOptions.startTime = this.cache_.currentTime;
}
this.cache_.src = source.src;
}
// Initialize tech instance
var techComponent = _Component3['default'].getComponent(techName);
this.tech = new techComponent(this, techOptions);
this.tech.ready(techReady);
}
}, {
key: 'unloadTech',
value: function unloadTech() {
this.isReady_ = false;
this.tech.dispose();
this.tech = false;
}
}, {
key: 'handleLoadStart',
/**
* Fired when the user agent begins looking for media data
* @event loadstart
*/
value: function handleLoadStart() {
// TODO: Update to use `emptied` event instead. See #1277.
this.removeClass('vjs-ended');
// reset the error state
this.error(null);
// If it's already playing we want to trigger a firstplay event now.
// The firstplay event relies on both the play and loadstart events
// which can happen in any order for a new source
if (!this.paused()) {
this.trigger('firstplay');
} else {
// reset the hasStarted state
this.hasStarted(false);
}
}
}, {
key: 'hasStarted',
value: (function (_hasStarted) {
function hasStarted(_x) {
return _hasStarted.apply(this, arguments);
}
hasStarted.toString = function () {
return hasStarted.toString();
};
return hasStarted;
})(function (hasStarted) {
if (hasStarted !== undefined) {
// only update if this is a new value
if (this.hasStarted_ !== hasStarted) {
this.hasStarted_ = hasStarted;
if (hasStarted) {
this.addClass('vjs-has-started');
// trigger the firstplay event if this newly has played
this.trigger('firstplay');
} else {
this.removeClass('vjs-has-started');
}
}
return this;
}
return !!this.hasStarted_;
})
}, {
key: 'handlePlay',
/**
* Fired whenever the media begins or resumes playback
* @event play
*/
value: function handlePlay() {
this.removeClass('vjs-ended');
this.removeClass('vjs-paused');
this.addClass('vjs-playing');
// hide the poster when the user hits play
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play
this.hasStarted(true);
}
}, {
key: 'handleWaiting',
/**
* Fired whenever the media begins waiting
* @event waiting
*/
value: function handleWaiting() {
this.addClass('vjs-waiting');
}
}, {
key: 'handleWaitEnd',
/**
* A handler for events that signal that waiting has ended
* which is not consistent between browsers. See #1351
* @private
*/
value: function handleWaitEnd() {
this.removeClass('vjs-waiting');
}
}, {
key: 'handleSeeking',
/**
* Fired whenever the player is jumping to a new time
* @event seeking
*/
value: function handleSeeking() {
this.addClass('vjs-seeking');
}
}, {
key: 'handleSeeked',
/**
* Fired when the player has finished jumping to a new time
* @event seeked
*/
value: function handleSeeked() {
this.removeClass('vjs-seeking');
}
}, {
key: 'handleFirstPlay',
/**
* Fired the first time a video is played
*
* Not part of the HLS spec, and we're not sure if this is the best
* implementation yet, so use sparingly. If you don't have a reason to
* prevent playback, use `myPlayer.one('play');` instead.
*
* @event firstplay
*/
value: function handleFirstPlay() {
//If the first starttime attribute is specified
//then we will start at the given offset in seconds
if (this.options_.starttime) {
this.currentTime(this.options_.starttime);
}
this.addClass('vjs-has-started');
}
}, {
key: 'handlePause',
/**
* Fired whenever the media has been paused
* @event pause
*/
value: function handlePause() {
this.removeClass('vjs-playing');
this.addClass('vjs-paused');
}
}, {
key: 'handleProgress',
/**
* Fired while the user agent is downloading media data
* @event progress
*/
value: function handleProgress() {
// Add custom event for when source is finished downloading.
if (this.bufferedPercent() == 1) {
this.trigger('loadedalldata');
}
}
}, {
key: 'handleEnded',
/**
* Fired when the end of the media resource is reached (currentTime == duration)
* @event ended
*/
value: function handleEnded() {
this.addClass('vjs-ended');
if (this.options_.loop) {
this.currentTime(0);
this.play();
} else if (!this.paused()) {
this.pause();
}
}
}, {
key: 'handleDurationChange',
/**
* Fired when the duration of the media resource is first known or changed
* @event durationchange
*/
value: function handleDurationChange() {
// Allows for caching value instead of asking player each time.
// We need to get the techGet response and check for a value so we don't
// accidentally cause the stack to blow up.
var duration = this.techGet('duration');
if (duration) {
if (duration < 0) {
duration = Infinity;
}
this.duration(duration);
// Determine if the stream is live and propagate styles down to UI.
if (duration === Infinity) {
this.addClass('vjs-live');
} else {
this.removeClass('vjs-live');
}
}
}
}, {
key: 'handleFullscreenChange',
/**
* Fired when the player switches in or out of fullscreen mode
* @event fullscreenchange
*/
value: function handleFullscreenChange() {
if (this.isFullscreen()) {
this.addClass('vjs-fullscreen');
} else {
this.removeClass('vjs-fullscreen');
}
}
}, {
key: 'getCache',
/**
* Object for cached values.
*/
value: function getCache() {
return this.cache_;
}
}, {
key: 'techCall',
// Pass values to the playback tech
value: function techCall(method, arg) {
// If it's not ready yet, call method when it is
if (this.tech && !this.tech.isReady_) {
this.tech.ready(function () {
this[method](arg);
});
// Otherwise call method now
} else {
try {
this.tech[method](arg);
} catch (e) {
Lib.log(e);
throw e;
}
}
}
}, {
key: 'techGet',
// Get calls can't wait for the tech, and sometimes don't need to.
value: function techGet(method) {
if (this.tech && this.tech.isReady_) {
// Flash likes to die and reload when you hide or reposition it.
// In these cases the object methods go away and we get errors.
// When that happens we'll catch the errors and inform tech that it's not ready any more.
try {
return this.tech[method]();
} catch (e) {
// When building additional tech libs, an expected method may not be defined yet
if (this.tech[method] === undefined) {
Lib.log('Video.js: ' + method + ' method not defined for ' + this.techName + ' playback technology.', e);
} else {
// When a method isn't available on the object it throws a TypeError
if (e.name == 'TypeError') {
Lib.log('Video.js: ' + method + ' unavailable on ' + this.techName + ' playback technology element.', e);
this.tech.isReady_ = false;
} else {
Lib.log(e);
}
}
throw e;
}
}
return;
}
}, {
key: 'play',
/**
* start media playback
*
* myPlayer.play();
*
* @return {Player} self
*/
value: function play() {
this.techCall('play');
return this;
}
}, {
key: 'pause',
/**
* Pause the video playback
*
* myPlayer.pause();
*
* @return {Player} self
*/
value: function pause() {
this.techCall('pause');
return this;
}
}, {
key: 'paused',
/**
* Check if the player is paused
*
* var isPaused = myPlayer.paused();
* var isPlaying = !myPlayer.paused();
*
* @return {Boolean} false if the media is currently playing, or true otherwise
*/
value: function paused() {
// The initial state of paused should be true (in Safari it's actually false)
return this.techGet('paused') === false ? false : true;
}
}, {
key: 'scrubbing',
/**
* Returns whether or not the user is "scrubbing". Scrubbing is when the user
* has clicked the progress bar handle and is dragging it along the progress bar.
* @param {Boolean} isScrubbing True/false the user is scrubbing
* @return {Boolean} The scrubbing status when getting
* @return {Object} The player when setting
*/
value: function scrubbing(isScrubbing) {
if (isScrubbing !== undefined) {
this.scrubbing_ = !!isScrubbing;
if (isScrubbing) {
this.addClass('vjs-scrubbing');
} else {
this.removeClass('vjs-scrubbing');
}
return this;
}
return this.scrubbing_;
}
}, {
key: 'currentTime',
/**
* Get or set the current time (in seconds)
*
* // get
* var whereYouAt = myPlayer.currentTime();
*
* // set
* myPlayer.currentTime(120); // 2 minutes into the video
*
* @param {Number|String=} seconds The time to seek to
* @return {Number} The time in seconds, when not setting
* @return {Player} self, when the current time is set
*/
value: function currentTime(seconds) {
if (seconds !== undefined) {
this.techCall('setCurrentTime', seconds);
return this;
}
// cache last currentTime and return. default to 0 seconds
//
// Caching the currentTime is meant to prevent a massive amount of reads on the tech's
// currentTime when scrubbing, but may not provide much performance benefit afterall.
// Should be tested. Also something has to read the actual current time or the cache will
// never get updated.
return this.cache_.currentTime = this.techGet('currentTime') || 0;
}
}, {
key: 'duration',
/**
* Get the length in time of the video in seconds
*
* var lengthOfVideo = myPlayer.duration();
*
* **NOTE**: The video must have started loading before the duration can be
* known, and in the case of Flash, may not be known until the video starts
* playing.
*
* @return {Number} The duration of the video in seconds
*/
value: function duration(seconds) {
if (seconds !== undefined) {
// cache the last set value for optimized scrubbing (esp. Flash)
this.cache_.duration = parseFloat(seconds);
return this;
}
if (this.cache_.duration === undefined) {
this.handleDurationChange();
}
return this.cache_.duration || 0;
}
}, {
key: 'remainingTime',
/**
* Calculates how much time is left.
*
* var timeLeft = myPlayer.remainingTime();
*
* Not a native video element function, but useful
* @return {Number} The time remaining in seconds
*/
value: function remainingTime() {
return this.duration() - this.currentTime();
}
}, {
key: 'buffered',
// http://dev.w3.org/html5/spec/video.html#dom-media-buffered
// Buffered returns a timerange object.
// Kind of like an array of portions of the video that have been downloaded.
/**
* Get a TimeRange object with the times of the video that have been downloaded
*
* If you just want the percent of the video that's been downloaded,
* use bufferedPercent.
*
* // Number of different ranges of time have been buffered. Usually 1.
* numberOfRanges = bufferedTimeRange.length,
*
* // Time in seconds when the first range starts. Usually 0.
* firstRangeStart = bufferedTimeRange.start(0),
*
* // Time in seconds when the first range ends
* firstRangeEnd = bufferedTimeRange.end(0),
*
* // Length in seconds of the first time range
* firstRangeLength = firstRangeEnd - firstRangeStart;
*
* @return {Object} A mock TimeRange object (following HTML spec)
*/
value: (function (_buffered) {
function buffered() {
return _buffered.apply(this, arguments);
}
buffered.toString = function () {
return buffered.toString();
};
return buffered;
})(function () {
var buffered = this.techGet('buffered');
if (!buffered || !buffered.length) {
buffered = Lib.createTimeRange(0, 0);
}
return buffered;
})
}, {
key: 'bufferedPercent',
/**
* Get the percent (as a decimal) of the video that's been downloaded
*
* var howMuchIsDownloaded = myPlayer.bufferedPercent();
*
* 0 means none, 1 means all.
* (This method isn't in the HTML5 spec, but it's very convenient)
*
* @return {Number} A decimal between 0 and 1 representing the percent
*/
value: function bufferedPercent() {
var duration = this.duration(),
buffered = this.buffered(),
bufferedDuration = 0,
start,
end;
if (!duration) {
return 0;
}
for (var i = 0; i < buffered.length; i++) {
start = buffered.start(i);
end = buffered.end(i);
// buffered end can be bigger than duration by a very small fraction
if (end > duration) {
end = duration;
}
bufferedDuration += end - start;
}
return bufferedDuration / duration;
}
}, {
key: 'bufferedEnd',
/**
* Get the ending time of the last buffered time range
*
* This is used in the progress bar to encapsulate all time ranges.
* @return {Number} The end of the last buffered time range
*/
value: function bufferedEnd() {
var buffered = this.buffered(),
duration = this.duration(),
end = buffered.end(buffered.length - 1);
if (end > duration) {
end = duration;
}
return end;
}
}, {
key: 'volume',
/**
* Get or set the current volume of the media
*
* // get
* var howLoudIsIt = myPlayer.volume();
*
* // set
* myPlayer.volume(0.5); // Set volume to half
*
* 0 is off (muted), 1.0 is all the way up, 0.5 is half way.
*
* @param {Number} percentAsDecimal The new volume as a decimal percent
* @return {Number} The current volume, when getting
* @return {Player} self, when setting
*/
value: function volume(percentAsDecimal) {
var vol = undefined;
if (percentAsDecimal !== undefined) {
vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1
this.cache_.volume = vol;
this.techCall('setVolume', vol);
Lib.setLocalStorage('volume', vol);
return this;
}
// Default to 1 when returning current volume.
vol = parseFloat(this.techGet('volume'));
return isNaN(vol) ? 1 : vol;
}
}, {
key: 'muted',
/**
* Get the current muted state, or turn mute on or off
*
* // get
* var isVolumeMuted = myPlayer.muted();
*
* // set
* myPlayer.muted(true); // mute the volume
*
* @param {Boolean=} muted True to mute, false to unmute
* @return {Boolean} True if mute is on, false if not, when getting
* @return {Player} self, when setting mute
*/
value: (function (_muted) {
function muted(_x2) {
return _muted.apply(this, arguments);
}
muted.toString = function () {
return muted.toString();
};
return muted;
})(function (muted) {
if (muted !== undefined) {
this.techCall('setMuted', muted);
return this;
}
return this.techGet('muted') || false; // Default to false
})
}, {
key: 'supportsFullScreen',
// Check if current tech can support native fullscreen
// (e.g. with built in controls like iOS, so not our flash swf)
value: function supportsFullScreen() {
return this.techGet('supportsFullScreen') || false;
}
}, {
key: 'isFullscreen',
/**
* Check if the player is in fullscreen mode
*
* // get
* var fullscreenOrNot = myPlayer.isFullscreen();
*
* // set
* myPlayer.isFullscreen(true); // tell the player it's in fullscreen
*
* NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
* property and instead document.fullscreenElement is used. But isFullscreen is
* still a valuable property for internal player workings.
*
* @param {Boolean=} isFS Update the player's fullscreen state
* @return {Boolean} true if fullscreen, false if not
* @return {Player} self, when setting
*/
value: function isFullscreen(isFS) {
if (isFS !== undefined) {
this.isFullscreen_ = !!isFS;
return this;
}
return !!this.isFullscreen_;
}
}, {
key: 'isFullScreen',
/**
* Old naming for isFullscreen()
* @deprecated for lowercase 's' version
*/
value: function isFullScreen(isFS) {
Lib.log.warn('player.isFullScreen() has been deprecated, use player.isFullscreen() with a lowercase "s")');
return this.isFullscreen(isFS);
}
}, {
key: 'requestFullscreen',
/**
* Increase the size of the video to full screen
*
* myPlayer.requestFullscreen();
*
* In some browsers, full screen is not supported natively, so it enters
* "full window mode", where the video fills the browser window.
* In browsers and devices that support native full screen, sometimes the
* browser's default controls will be shown, and not the Video.js custom skin.
* This includes most mobile devices (iOS, Android) and older versions of
* Safari.
*
* @return {Player} self
*/
value: function requestFullscreen() {
var fsApi = _FullscreenApi2['default'];
this.isFullscreen(true);
if (fsApi) {
// the browser supports going fullscreen at the element level so we can
// take the controls fullscreen as well as the video
// Trigger fullscreenchange event after change
// We have to specifically add this each time, and remove
// when canceling fullscreen. Otherwise if there's multiple
// players on a page, they would all be reacting to the same fullscreen
// events
Events.on(_document2['default'], fsApi.fullscreenchange, Lib.bind(this, function documentFullscreenChange(e) {
this.isFullscreen(_document2['default'][fsApi.fullscreenElement]);
// If cancelling fullscreen, remove event listener.
if (this.isFullscreen() === false) {
Events.off(_document2['default'], fsApi.fullscreenchange, documentFullscreenChange);
}
this.trigger('fullscreenchange');
}));
this.el_[fsApi.requestFullscreen]();
} else if (this.tech.supportsFullScreen()) {
// we can't take the video.js controls fullscreen but we can go fullscreen
// with native controls
this.techCall('enterFullScreen');
} else {
// fullscreen isn't supported so we'll just stretch the video element to
// fill the viewport
this.enterFullWindow();
this.trigger('fullscreenchange');
}
return this;
}
}, {
key: 'requestFullScreen',
/**
* Old naming for requestFullscreen
* @deprecated for lower case 's' version
*/
value: function requestFullScreen() {
Lib.log.warn('player.requestFullScreen() has been deprecated, use player.requestFullscreen() with a lowercase "s")');
return this.requestFullscreen();
}
}, {
key: 'exitFullscreen',
/**
* Return the video to its normal size after having been in full screen mode
*
* myPlayer.exitFullscreen();
*
* @return {Player} self
*/
value: function exitFullscreen() {
var fsApi = _FullscreenApi2['default'];
this.isFullscreen(false);
// Check for browser element fullscreen support
if (fsApi) {
_document2['default'][fsApi.exitFullscreen]();
} else if (this.tech.supportsFullScreen()) {
this.techCall('exitFullScreen');
} else {
this.exitFullWindow();
this.trigger('fullscreenchange');
}
return this;
}
}, {
key: 'cancelFullScreen',
/**
* Old naming for exitFullscreen
* @deprecated for exitFullscreen
*/
value: function cancelFullScreen() {
Lib.log.warn('player.cancelFullScreen() has been deprecated, use player.exitFullscreen()');
return this.exitFullscreen();
}
}, {
key: 'enterFullWindow',
// When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us.
value: function enterFullWindow() {
this.isFullWindow = true;
// Storing original doc overflow value to return to when fullscreen is off
this.docOrigOverflow = _document2['default'].documentElement.style.overflow;
// Add listener for esc key to exit fullscreen
Events.on(_document2['default'], 'keydown', Lib.bind(this, this.fullWindowOnEscKey));
// Hide any scroll bars
_document2['default'].documentElement.style.overflow = 'hidden';
// Apply fullscreen styles
Lib.addClass(_document2['default'].body, 'vjs-full-window');
this.trigger('enterFullWindow');
}
}, {
key: 'fullWindowOnEscKey',
value: function fullWindowOnEscKey(event) {
if (event.keyCode === 27) {
if (this.isFullscreen() === true) {
this.exitFullscreen();
} else {
this.exitFullWindow();
}
}
}
}, {
key: 'exitFullWindow',
value: function exitFullWindow() {
this.isFullWindow = false;
Events.off(_document2['default'], 'keydown', this.fullWindowOnEscKey);
// Unhide scroll bars.
_document2['default'].documentElement.style.overflow = this.docOrigOverflow;
// Remove fullscreen styles
Lib.removeClass(_document2['default'].body, 'vjs-full-window');
// Resize the box, controller, and poster to original sizes
// this.positionAll();
this.trigger('exitFullWindow');
}
}, {
key: 'selectSource',
value: function selectSource(sources) {
// Loop through each playback technology in the options order
for (var i = 0, j = this.options_.techOrder; i < j.length; i++) {
var techName = Lib.capitalize(j[i]);
var tech = _Component3['default'].getComponent(techName);
// Check if the current tech is defined before continuing
if (!tech) {
Lib.log.error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.');
continue;
}
// Check if the browser supports this technology
if (tech.isSupported()) {
// Loop through each source object
for (var a = 0, b = sources; a < b.length; a++) {
var source = b[a];
// Check if source can be played with this technology
if (tech.canPlaySource(source)) {
return { source: source, tech: techName };
}
}
}
}
return false;
}
}, {
key: 'src',
/**
* The source function updates the video source
*
* There are three types of variables you can pass as the argument.
*
* **URL String**: A URL to the the video file. Use this method if you are sure
* the current playback technology (HTML5/Flash) can support the source you
* provide. Currently only MP4 files can be used in both HTML5 and Flash.
*
* myPlayer.src("http://www.example.com/path/to/video.mp4");
*
* **Source Object (or element):** A javascript object containing information
* about the source file. Use this method if you want the player to determine if
* it can support the file using the type information.
*
* myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" });
*
* **Array of Source Objects:** To provide multiple versions of the source so
* that it can be played using HTML5 across browsers you can use an array of
* source objects. Video.js will detect which version is supported and load that
* file.
*
* myPlayer.src([
* { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" },
* { type: "video/webm", src: "http://www.example.com/path/to/video.webm" },
* { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" }
* ]);
*
* @param {String|Object|Array=} source The source URL, object, or array of sources
* @return {String} The current video source when getting
* @return {String} The player when setting
*/
value: function src() {
var source = arguments[0] === undefined ? this.techGet('src') : arguments[0];
var currentTech = _Component3['default'].getComponent(this.techName);
// case: Array of source objects to choose from and pick the best to play
if (Lib.obj.isArray(source)) {
this.sourceList_(source);
// case: URL String (http://myvideo...)
} else if (typeof source === 'string') {
// create a source object from the string
this.src({ src: source });
// case: Source object { src: '', type: '' ... }
} else if (source instanceof Object) {
// check if the source has a type and the loaded tech cannot play the source
// if there's no type we'll just try the current tech
if (source.type && !currentTech.canPlaySource(source)) {
// create a source list with the current source and send through
// the tech loop to check for a compatible technology
this.sourceList_([source]);
} else {
this.cache_.src = source.src;
this.currentType_ = source.type || '';
// wait until the tech is ready to set the source
this.ready(function () {
// The setSource tech method was added with source handlers
// so older techs won't support it
// We need to check the direct prototype for the case where subclasses
// of the tech do not support source handlers
if (currentTech.prototype.hasOwnProperty('setSource')) {
this.techCall('setSource', source);
} else {
this.techCall('src', source.src);
}
if (this.options_.preload == 'auto') {
this.load();
}
if (this.options_.autoplay) {
this.play();
}
});
}
}
return this;
}
}, {
key: 'sourceList_',
/**
* Handle an array of source objects
* @param {[type]} sources Array of source objects
* @private
*/
value: function sourceList_(sources) {
var sourceTech = this.selectSource(sources);
if (sourceTech) {
if (sourceTech.tech === this.techName) {
// if this technology is already loaded, set the source
this.src(sourceTech.source);
} else {
// load this technology with the chosen source
this.loadTech(sourceTech.tech, sourceTech.source);
}
} else {
// We need to wrap this in a timeout to give folks a chance to add error event handlers
this.setTimeout(function () {
this.error({ code: 4, message: this.localize(this.options().notSupportedMessage) });
}, 0);
// we could not find an appropriate tech, but let's still notify the delegate that this is it
// this needs a better comment about why this is needed
this.triggerReady();
}
}
}, {
key: 'load',
/**
* Begin loading the src data.
* @return {Player} Returns the player
*/
value: function load() {
this.techCall('load');
return this;
}
}, {
key: 'currentSrc',
/**
* Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
* Can be used in conjuction with `currentType` to assist in rebuilding the current source object.
* @return {String} The current source
*/
value: function currentSrc() {
return this.techGet('currentSrc') || this.cache_.src || '';
}
}, {
key: 'currentType',
/**
* Get the current source type e.g. video/mp4
* This can allow you rebuild the current source object so that you could load the same
* source and tech later
* @return {String} The source MIME type
*/
value: function currentType() {
return this.currentType_ || '';
}
}, {
key: 'preload',
/**
* Get or set the preload attribute.
* @return {String} The preload attribute value when getting
* @return {Player} Returns the player when setting
*/
value: function preload(value) {
if (value !== undefined) {
this.techCall('setPreload', value);
this.options_.preload = value;
return this;
}
return this.techGet('preload');
}
}, {
key: 'autoplay',
/**
* Get or set the autoplay attribute.
* @return {String} The autoplay attribute value when getting
* @return {Player} Returns the player when setting
*/
value: function autoplay(value) {
if (value !== undefined) {
this.techCall('setAutoplay', value);
this.options_.autoplay = value;
return this;
}
return this.techGet('autoplay', value);
}
}, {
key: 'loop',
/**
* Get or set the loop attribute on the video element.
* @return {String} The loop attribute value when getting
* @return {Player} Returns the player when setting
*/
value: function loop(value) {
if (value !== undefined) {
this.techCall('setLoop', value);
this.options_.loop = value;
return this;
}
return this.techGet('loop');
}
}, {
key: 'poster',
/**
* get or set the poster image source url
*
* ##### EXAMPLE:
*
* // getting
* var currentPoster = myPlayer.poster();
*
* // setting
* myPlayer.poster('http://example.com/myImage.jpg');
*
* @param {String=} [src] Poster image source URL
* @return {String} poster URL when getting
* @return {Player} self when setting
*/
value: function poster(src) {
if (src === undefined) {
return this.poster_;
}
// The correct way to remove a poster is to set as an empty string
// other falsey values will throw errors
if (!src) {
src = '';
}
// update the internal poster variable
this.poster_ = src;
// update the tech's poster
this.techCall('setPoster', src);
// alert components that the poster has been set
this.trigger('posterchange');
return this;
}
}, {
key: 'controls',
/**
* Get or set whether or not the controls are showing.
* @param {Boolean} controls Set controls to showing or not
* @return {Boolean} Controls are showing
*/
value: function controls(bool) {
if (bool !== undefined) {
bool = !!bool; // force boolean
// Don't trigger a change event unless it actually changed
if (this.controls_ !== bool) {
this.controls_ = bool;
if (bool) {
this.removeClass('vjs-controls-disabled');
this.addClass('vjs-controls-enabled');
this.trigger('controlsenabled');
} else {
this.removeClass('vjs-controls-enabled');
this.addClass('vjs-controls-disabled');
this.trigger('controlsdisabled');
}
}
return this;
}
return !!this.controls_;
}
}, {
key: 'usingNativeControls',
/**
* Toggle native controls on/off. Native controls are the controls built into
* devices (e.g. default iPhone controls), Flash, or other techs
* (e.g. Vimeo Controls)
*
* **This should only be set by the current tech, because only the tech knows
* if it can support native controls**
*
* @param {Boolean} bool True signals that native controls are on
* @return {Player} Returns the player
* @private
*/
value: function usingNativeControls(bool) {
if (bool !== undefined) {
bool = !!bool; // force boolean
// Don't trigger a change event unless it actually changed
if (this.usingNativeControls_ !== bool) {
this.usingNativeControls_ = bool;
if (bool) {
this.addClass('vjs-using-native-controls');
/**
* player is using the native device controls
*
* @event usingnativecontrols
* @memberof Player
* @instance
* @private
*/
this.trigger('usingnativecontrols');
} else {
this.removeClass('vjs-using-native-controls');
/**
* player is using the custom HTML controls
*
* @event usingcustomcontrols
* @memberof Player
* @instance
* @private
*/
this.trigger('usingcustomcontrols');
}
}
return this;
}
return !!this.usingNativeControls_;
}
}, {
key: 'error',
/**
* Set or get the current MediaError
* @param {*} err A MediaError or a String/Number to be turned into a MediaError
* @return {MediaError|null} when getting
* @return {Player} when setting
*/
value: function error(err) {
if (err === undefined) {
return this.error_ || null;
}
// restoring to default
if (err === null) {
this.error_ = err;
this.removeClass('vjs-error');
return this;
}
// error instance
if (err instanceof _MediaError2['default']) {
this.error_ = err;
} else {
this.error_ = new _MediaError2['default'](err);
}
// fire an error event on the player
this.trigger('error');
// add the vjs-error classname to the player
this.addClass('vjs-error');
// log the name of the error type and any message
// ie8 just logs "[object object]" if you just log the error object
Lib.log.error('(CODE:' + this.error_.code + ' ' + _MediaError2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_);
return this;
}
}, {
key: 'ended',
/**
* Returns whether or not the player is in the "ended" state.
* @return {Boolean} True if the player is in the ended state, false if not.
*/
value: function ended() {
return this.techGet('ended');
}
}, {
key: 'seeking',
/**
* Returns whether or not the player is in the "seeking" state.
* @return {Boolean} True if the player is in the seeking state, false if not.
*/
value: function seeking() {
return this.techGet('seeking');
}
}, {
key: 'reportUserActivity',
value: function reportUserActivity(event) {
this.userActivity_ = true;
}
}, {
key: 'userActive',
value: function userActive(bool) {
if (bool !== undefined) {
bool = !!bool;
if (bool !== this.userActive_) {
this.userActive_ = bool;
if (bool) {
// If the user was inactive and is now active we want to reset the
// inactivity timer
this.userActivity_ = true;
this.removeClass('vjs-user-inactive');
this.addClass('vjs-user-active');
this.trigger('useractive');
} else {
// We're switching the state to inactive manually, so erase any other
// activity
this.userActivity_ = false;
// Chrome/Safari/IE have bugs where when you change the cursor it can
// trigger a mousemove event. This causes an issue when you're hiding
// the cursor when the user is inactive, and a mousemove signals user
// activity. Making it impossible to go into inactive mode. Specifically
// this happens in fullscreen when we really need to hide the cursor.
//
// When this gets resolved in ALL browsers it can be removed
// https://code.google.com/p/chromium/issues/detail?id=103041
if (this.tech) {
this.tech.one('mousemove', function (e) {
e.stopPropagation();
e.preventDefault();
});
}
this.removeClass('vjs-user-active');
this.addClass('vjs-user-inactive');
this.trigger('userinactive');
}
}
return this;
}
return this.userActive_;
}
}, {
key: 'listenForUserActivity',
value: function listenForUserActivity() {
var mouseInProgress = undefined,
lastMoveX = undefined,
lastMoveY = undefined;
var handleActivity = Lib.bind(this, this.reportUserActivity);
var handleMouseMove = function handleMouseMove(e) {
// #1068 - Prevent mousemove spamming
// Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
if (e.screenX != lastMoveX || e.screenY != lastMoveY) {
lastMoveX = e.screenX;
lastMoveY = e.screenY;
handleActivity();
}
};
var handleMouseDown = function handleMouseDown() {
handleActivity();
// For as long as the they are touching the device or have their mouse down,
// we consider them active even if they're not moving their finger or mouse.
// So we want to continue to update that they are active
this.clearInterval(mouseInProgress);
// Setting userActivity=true now and setting the interval to the same time
// as the activityCheck interval (250) should ensure we never miss the
// next activityCheck
mouseInProgress = this.setInterval(handleActivity, 250);
};
var handleMouseUp = function handleMouseUp(event) {
handleActivity();
// Stop the interval that maintains activity if the mouse/touch is down
this.clearInterval(mouseInProgress);
};
// Any mouse movement will be considered user activity
this.on('mousedown', handleMouseDown);
this.on('mousemove', handleMouseMove);
this.on('mouseup', handleMouseUp);
// Listen for keyboard navigation
// Shouldn't need to use inProgress interval because of key repeat
this.on('keydown', handleActivity);
this.on('keyup', handleActivity);
// Run an interval every 250 milliseconds instead of stuffing everything into
// the mousemove/touchmove function itself, to prevent performance degradation.
// `this.reportUserActivity` simply sets this.userActivity_ to true, which
// then gets picked up by this loop
// http://ejohn.org/blog/learning-from-twitter/
var activityCheck = this.setInterval(function () {
var inactivityTimeout = undefined;
// Check to see if mouse/touch activity has happened
if (this.userActivity_) {
// Reset the activity tracker
this.userActivity_ = false;
// If the user state was inactive, set the state to active
this.userActive(true);
// Clear any existing inactivity timeout to start the timer over
this.clearTimeout(inactivityTimeout);
var timeout = this.options().inactivityTimeout;
if (timeout > 0) {
// In <timeout> milliseconds, if no more activity has occurred the
// user will be considered inactive
inactivityTimeout = this.setTimeout(function () {
// Protect against the case where the inactivityTimeout can trigger just
// before the next user activity is picked up by the activityCheck loop
// causing a flicker
if (!this.userActivity_) {
this.userActive(false);
}
}, timeout);
}
}
}, 250);
}
}, {
key: 'playbackRate',
/**
* Gets or sets the current playback rate. A playback rate of
* 1.0 represents normal speed and 0.5 would indicate half-speed
* playback, for instance.
* @param {Number} rate New playback rate to set.
* @return {Number} Returns the new playback rate when setting
* @return {Number} Returns the current playback rate when getting
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
*/
value: function playbackRate(rate) {
if (rate !== undefined) {
this.techCall('setPlaybackRate', rate);
return this;
}
if (this.tech && this.tech.featuresPlaybackRate) {
return this.techGet('playbackRate');
} else {
return 1;
}
}
}, {
key: 'isAudio',
/**
* Gets or sets the audio flag
*
* @param {Boolean} bool True signals that this is an audio player.
* @return {Boolean} Returns true if player is audio, false if not when getting
* @return {Player} Returns the player if setting
* @private
*/
value: function isAudio(bool) {
if (bool !== undefined) {
this.isAudio_ = !!bool;
return this;
}
return !!this.isAudio_;
}
}, {
key: 'networkState',
/**
* Returns the current state of network activity for the element, from
* the codes in the list below.
* - NETWORK_EMPTY (numeric value 0)
* The element has not yet been initialised. All attributes are in
* their initial states.
* - NETWORK_IDLE (numeric value 1)
* The element's resource selection algorithm is active and has
* selected a resource, but it is not actually using the network at
* this time.
* - NETWORK_LOADING (numeric value 2)
* The user agent is actively trying to download data.
* - NETWORK_NO_SOURCE (numeric value 3)
* The element's resource selection algorithm is active, but it has
* not yet found a resource to use.
* @return {Number} the current network activity state
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
*/
value: function networkState() {
return this.techGet('networkState');
}
}, {
key: 'readyState',
/**
* Returns a value that expresses the current state of the element
* with respect to rendering the current playback position, from the
* codes in the list below.
* - HAVE_NOTHING (numeric value 0)
* No information regarding the media resource is available.
* - HAVE_METADATA (numeric value 1)
* Enough of the resource has been obtained that the duration of the
* resource is available.
* - HAVE_CURRENT_DATA (numeric value 2)
* Data for the immediate current playback position is available.
* - HAVE_FUTURE_DATA (numeric value 3)
* Data for the immediate current playback position is available, as
* well as enough data for the user agent to advance the current
* playback position in the direction of playback.
* - HAVE_ENOUGH_DATA (numeric value 4)
* The user agent estimates that enough data is available for
* playback to proceed uninterrupted.
* @return {Number} the current playback rendering state
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
*/
value: function readyState() {
return this.techGet('readyState');
}
}, {
key: 'textTracks',
/**
* Text tracks are tracks of timed text events.
* Captions - text displayed over the video for the hearing impaired
* Subtitles - text displayed over the video for those who don't understand language in the video
* Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video
* Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device
*/
/**
* Get an array of associated text tracks. captions, subtitles, chapters, descriptions
* http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
* @return {Array} Array of track objects
*/
value: function textTracks() {
// cannot use techGet directly because it checks to see whether the tech is ready.
// Flash is unlikely to be ready in time but textTracks should still work.
return this.tech && this.tech.textTracks();
}
}, {
key: 'remoteTextTracks',
value: function remoteTextTracks() {
return this.tech && this.tech.remoteTextTracks();
}
}, {
key: 'addTextTrack',
/**
* Add a text track
* In addition to the W3C settings we allow adding additional info through options.
* http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
* @param {String} kind Captions, subtitles, chapters, descriptions, or metadata
* @param {String=} label Optional label
* @param {String=} language Optional language
*/
value: function addTextTrack(kind, label, language) {
return this.tech && this.tech.addTextTrack(kind, label, language);
}
}, {
key: 'addRemoteTextTrack',
value: function addRemoteTextTrack(options) {
return this.tech && this.tech.addRemoteTextTrack(options);
}
}, {
key: 'removeRemoteTextTrack',
value: function removeRemoteTextTrack(track) {
this.tech && this.tech.removeRemoteTextTrack(track);
}
}, {
key: 'language',
// Methods to add support for
// initialTime: function(){ return this.techCall('initialTime'); },
// startOffsetTime: function(){ return this.techCall('startOffsetTime'); },
// played: function(){ return this.techCall('played'); },
// seekable: function(){ return this.techCall('seekable'); },
// videoTracks: function(){ return this.techCall('videoTracks'); },
// audioTracks: function(){ return this.techCall('audioTracks'); },
// videoWidth: function(){ return this.techCall('videoWidth'); },
// videoHeight: function(){ return this.techCall('videoHeight'); },
// defaultPlaybackRate: function(){ return this.techCall('defaultPlaybackRate'); },
// mediaGroup: function(){ return this.techCall('mediaGroup'); },
// controller: function(){ return this.techCall('controller'); },
// defaultMuted: function(){ return this.techCall('defaultMuted'); }
// TODO
// currentSrcList: the array of sources including other formats and bitrates
// playList: array of source lists in order of playback
/**
* The player's language code
* @param {String} languageCode The locale string
* @return {String} The locale string when getting
* @return {Player} self, when setting
*/
value: function language(languageCode) {
if (languageCode === undefined) {
return this.language_;
}
this.language_ = languageCode;
return this;
}
}, {
key: 'languages',
/**
* Get the player's language dictionary
*/
value: function languages() {
return this.languages_;
}
}], [{
key: 'getTagSettings',
value: function getTagSettings(tag) {
var baseOptions = {
sources: [],
tracks: []
};
var tagOptions = Lib.getElementAttributes(tag);
var dataSetup = tagOptions['data-setup'];
// Check if data-setup attr exists.
if (dataSetup !== null) {
// Parse options JSON
// If empty string, make it a parsable json object.
Lib.obj.merge(tagOptions, _safeParseTuple2['default'](dataSetup || '{}')[1]);
}
Lib.obj.merge(baseOptions, tagOptions);
// Get tag children settings
if (tag.hasChildNodes()) {
var children = tag.childNodes;
for (var i = 0, j = children.length; i < j; i++) {
var child = children[i];
// Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
var childName = child.nodeName.toLowerCase();
if (childName === 'source') {
baseOptions.sources.push(Lib.getElementAttributes(child));
} else if (childName === 'track') {
baseOptions.tracks.push(Lib.getElementAttributes(child));
}
}
}
return baseOptions;
}
}]);
return Player;
})(_Component3['default']);
/**
* Global player list
* @type {Object}
*/
Player.players = {};
/**
* Player instance options, surfaced using options
* options = Player.prototype.options_
* Make changes in options, not here.
* All options should use string keys so they avoid
* renaming by closure compiler
* @type {Object}
* @private
*/
Player.prototype.options_ = _Options2['default'];
/**
* Fired when the player has initial duration and dimension information
* @event loadedmetadata
*/
Player.prototype.handleLoadedMetaData;
/**
* Fired when the player has downloaded data at the current playback position
* @event loadeddata
*/
Player.prototype.handleLoadedData;
/**
* Fired when the player has finished downloading the source data
* @event loadedalldata
*/
Player.prototype.handleLoadedAllData;
/**
* Fired when the user is active, e.g. moves the mouse over the player
* @event useractive
*/
Player.prototype.handleUserActive;
/**
* Fired when the user is inactive, e.g. a short delay after the last mouse move or control interaction
* @event userinactive
*/
Player.prototype.handleUserInactive;
/**
* Fired when the current playback position has changed
*
* During playback this is fired every 15-250 milliseconds, depending on the
* playback technology in use.
* @event timeupdate
*/
Player.prototype.handleTimeUpdate;
/**
* Fired when the volume changes
* @event volumechange
*/
Player.prototype.handleVolumeChange;
/**
* Fired when an error occurs
* @event error
*/
Player.prototype.handleError;
Player.prototype.flexNotSupported_ = function () {
var elem = _document2['default'].createElement('i');
return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style);
};
_Component3['default'].registerComponent('Player', Player);
exports['default'] = Player;
module.exports = exports['default'];
},{"./big-play-button.js":5,"./component.js":7,"./control-bar/control-bar.js":8,"./error-display.js":41,"./events.js":43,"./fullscreen-api.js":45,"./lib.js":46,"./loading-spinner.js":47,"./media-error.js":48,"./options.js":52,"./poster-image.js":55,"./tech/html5.js":61,"./tech/loader.js":62,"./tracks/text-track-display.js":65,"./tracks/text-track-settings.js":68,"global/document":1,"global/window":2,"safe-json-parse/tuple":4}],54:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Player = _dereq_('./player');
var _Player2 = _interopRequireWildcard(_Player);
/**
* the method for registering a video.js plugin
*
* @param {String} name The name of the plugin
* @param {Function} init The function that is run when the player inits
*/
var plugin = function plugin(name, init) {
_Player2['default'].prototype[name] = init;
};
exports['default'] = plugin;
module.exports = exports['default'];
},{"./player":53}],55:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Button2 = _dereq_('./button');
var _Button3 = _interopRequireWildcard(_Button2);
var _import = _dereq_('./lib');
var Lib = _interopRequireWildcard(_import);
/* Poster Image
================================================================================ */
/**
* The component that handles showing the poster image.
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var PosterImage = (function (_Button) {
function PosterImage(player, options) {
_classCallCheck(this, PosterImage);
_get(Object.getPrototypeOf(PosterImage.prototype), 'constructor', this).call(this, player, options);
this.update();
player.on('posterchange', Lib.bind(this, this.update));
}
_inherits(PosterImage, _Button);
_createClass(PosterImage, [{
key: 'dispose',
/**
* Clean up the poster image
*/
value: function dispose() {
this.player().off('posterchange', this.update);
_get(Object.getPrototypeOf(PosterImage.prototype), 'dispose', this).call(this);
}
}, {
key: 'createEl',
/**
* Create the poster image element
* @return {Element}
*/
value: function createEl() {
var el = Lib.createEl('div', {
className: 'vjs-poster',
// Don't want poster to be tabbable.
tabIndex: -1
});
// To ensure the poster image resizes while maintaining its original aspect
// ratio, use a div with `background-size` when available. For browsers that
// do not support `background-size` (e.g. IE8), fall back on using a regular
// img element.
if (!Lib.BACKGROUND_SIZE_SUPPORTED) {
this.fallbackImg_ = Lib.createEl('img');
el.appendChild(this.fallbackImg_);
}
return el;
}
}, {
key: 'update',
/**
* Event handler for updates to the player's poster source
*/
value: function update() {
var url = this.player().poster();
this.setSrc(url);
// If there's no poster source we should display:none on this component
// so it's not still clickable or right-clickable
if (url) {
this.show();
} else {
this.hide();
}
}
}, {
key: 'setSrc',
/**
* Set the poster source depending on the display method
*/
value: function setSrc(url) {
if (this.fallbackImg_) {
this.fallbackImg_.src = url;
} else {
var backgroundImage = '';
// Any falsey values should stay as an empty string, otherwise
// this will throw an extra error
if (url) {
backgroundImage = 'url("' + url + '")';
}
this.el_.style.backgroundImage = backgroundImage;
}
}
}, {
key: 'handleClick',
/**
* Event handler for clicks on the poster image
*/
value: function handleClick() {
// We don't want a click to trigger playback when controls are disabled
// but CSS should be hiding the poster to prevent that from happening
if (this.player_.paused()) {
this.player_.play();
} else {
this.player_.pause();
}
}
}]);
return PosterImage;
})(_Button3['default']);
_Button3['default'].registerComponent('PosterImage', PosterImage);
exports['default'] = PosterImage;
module.exports = exports['default'];
},{"./button":6,"./lib":46}],56:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _import = _dereq_('./events');
var Events = _interopRequireWildcard(_import);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
var _windowLoaded = false;
var videojs = undefined;
/**
* @fileoverview Functions for automatically setting up a player
* based on the data-setup attribute of the video tag
*/
// Automatically set up any tags that have a data-setup attribute
var autoSetup = function autoSetup() {
// One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack*
// var vids = Array.prototype.slice.call(document.getElementsByTagName('video'));
// var audios = Array.prototype.slice.call(document.getElementsByTagName('audio'));
// var mediaEls = vids.concat(audios);
// Because IE8 doesn't support calling slice on a node list, we need to loop through each list of elements
// to build up a new, combined list of elements.
var vids = _document2['default'].getElementsByTagName('video');
var audios = _document2['default'].getElementsByTagName('audio');
var mediaEls = [];
if (vids && vids.length > 0) {
for (var i = 0, e = vids.length; i < e; i++) {
mediaEls.push(vids[i]);
}
}
if (audios && audios.length > 0) {
for (var i = 0, e = audios.length; i < e; i++) {
mediaEls.push(audios[i]);
}
}
// Check if any media elements exist
if (mediaEls && mediaEls.length > 0) {
for (var i = 0, e = mediaEls.length; i < e; i++) {
var mediaEl = mediaEls[i];
// Check if element exists, has getAttribute func.
// IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately.
if (mediaEl && mediaEl.getAttribute) {
// Make sure this player hasn't already been set up.
if (mediaEl.player === undefined) {
var options = mediaEl.getAttribute('data-setup');
// Check if data-setup attr exists.
// We only auto-setup if they've added the data-setup attr.
if (options !== null) {
// Create new video.js instance.
var player = videojs(mediaEl);
}
}
// If getAttribute isn't defined, we need to wait for the DOM.
} else {
autoSetupTimeout(1);
break;
}
}
// No videos were found, so keep looping unless page is finished loading.
} else if (!_windowLoaded) {
autoSetupTimeout(1);
}
};
// Pause to let the DOM keep processing
var autoSetupTimeout = function autoSetupTimeout(wait, vjs) {
videojs = vjs;
setTimeout(autoSetup, wait);
};
if (_document2['default'].readyState === 'complete') {
_windowLoaded = true;
} else {
Events.one(_window2['default'], 'load', function () {
_windowLoaded = true;
});
}
var hasLoaded = function hasLoaded() {
return _windowLoaded;
};
exports.autoSetup = autoSetup;
exports.autoSetupTimeout = autoSetupTimeout;
exports.hasLoaded = hasLoaded;
},{"./events":43,"global/document":1,"global/window":2}],57:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('../lib.js');
var Lib = _interopRequireWildcard(_import);
/**
* SeekBar Behavior includes play progress bar, and seek handle
* Needed so it can determine seek position based on handle position/size
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var SliderHandle = (function (_Component) {
function SliderHandle() {
_classCallCheck(this, SliderHandle);
if (_Component != null) {
_Component.apply(this, arguments);
}
}
_inherits(SliderHandle, _Component);
_createClass(SliderHandle, [{
key: 'createEl',
/** @inheritDoc */
value: function createEl(type, props) {
props = props || {};
// Add the slider element class to all sub classes
props.className = props.className + ' vjs-slider-handle';
props = Lib.obj.merge({
innerHTML: '<span class="vjs-control-text">' + (this.defaultValue || 0) + '</span>'
}, props);
return _get(Object.getPrototypeOf(SliderHandle.prototype), 'createEl', this).call(this, 'div', props);
}
}]);
return SliderHandle;
})(_Component3['default']);
_Component3['default'].registerComponent('SliderHandle', SliderHandle);
exports['default'] = SliderHandle;
module.exports = exports['default'];
},{"../component.js":7,"../lib.js":46}],58:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../component.js');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('../lib.js');
var Lib = _interopRequireWildcard(_import);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
/* Slider
================================================================================ */
/**
* The base functionality for sliders like the volume bar and seek bar
*
* @param {Player|Object} player
* @param {Object=} options
* @constructor
*/
var Slider = (function (_Component) {
function Slider(player, options) {
_classCallCheck(this, Slider);
_get(Object.getPrototypeOf(Slider.prototype), 'constructor', this).call(this, player, options);
// Set property names to bar and handle to match with the child Slider class is looking for
this.bar = this.getChild(this.options_.barName);
this.handle = this.getChild(this.options_.handleName);
// Set a horizontal or vertical class on the slider depending on the slider type
this.vertical(!!this.options().vertical);
this.on('mousedown', this.handleMouseDown);
this.on('touchstart', this.handleMouseDown);
this.on('focus', this.handleFocus);
this.on('blur', this.handleBlur);
this.on('click', this.handleClick);
this.on(player, 'controlsvisible', this.update);
this.on(player, this.playerEvent, this.update);
}
_inherits(Slider, _Component);
_createClass(Slider, [{
key: 'createEl',
value: function createEl(type) {
var props = arguments[1] === undefined ? {} : arguments[1];
// Add the slider element class to all sub classes
props.className = props.className + ' vjs-slider';
props = Lib.obj.merge({
role: 'slider',
'aria-valuenow': 0,
'aria-valuemin': 0,
'aria-valuemax': 100,
tabIndex: 0
}, props);
return _get(Object.getPrototypeOf(Slider.prototype), 'createEl', this).call(this, type, props);
}
}, {
key: 'handleMouseDown',
value: function handleMouseDown(event) {
event.preventDefault();
Lib.blockTextSelection();
this.addClass('vjs-sliding');
this.on(_document2['default'], 'mousemove', this.handleMouseMove);
this.on(_document2['default'], 'mouseup', this.handleMouseUp);
this.on(_document2['default'], 'touchmove', this.handleMouseMove);
this.on(_document2['default'], 'touchend', this.handleMouseUp);
this.handleMouseMove(event);
}
}, {
key: 'handleMouseMove',
// To be overridden by a subclass
value: function handleMouseMove() {}
}, {
key: 'handleMouseUp',
value: function handleMouseUp() {
Lib.unblockTextSelection();
this.removeClass('vjs-sliding');
this.off(_document2['default'], 'mousemove', this.handleMouseMove);
this.off(_document2['default'], 'mouseup', this.handleMouseUp);
this.off(_document2['default'], 'touchmove', this.handleMouseMove);
this.off(_document2['default'], 'touchend', this.handleMouseUp);
this.update();
}
}, {
key: 'update',
value: function update() {
// In VolumeBar init we have a setTimeout for update that pops and update to the end of the
// execution stack. The player is destroyed before then update will cause an error
if (!this.el_) {
return;
} // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse.
// On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later.
// var progress = (this.player_.scrubbing) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration();
var progress = this.getPercent();
var bar = this.bar;
// If there's no bar...
if (!bar) {
return;
} // Protect against no duration and other division issues
if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) {
progress = 0;
}
// If there is a handle, we need to account for the handle in our calculation for progress bar
// so that it doesn't fall short of or extend past the handle.
var barProgress = this.updateHandlePosition(progress);
// Convert to a percentage for setting
var percentage = Lib.round(barProgress * 100, 2) + '%';
// Set the new bar width or height
if (this.vertical()) {
bar.el().style.height = percentage;
} else {
bar.el().style.width = percentage;
}
}
}, {
key: 'updateHandlePosition',
/**
* Update the handle position.
*/
value: function updateHandlePosition(progress) {
var handle = this.handle;
if (!handle) {
return;
}var vertical = this.vertical();
var box = this.el_;
var boxSize = undefined,
handleSize = undefined;
if (vertical) {
boxSize = box.offsetHeight;
handleSize = handle.el().offsetHeight;
} else {
boxSize = box.offsetWidth;
handleSize = handle.el().offsetWidth;
}
// The width of the handle in percent of the containing box
// In IE, widths may not be ready yet causing NaN
var handlePercent = handleSize ? handleSize / boxSize : 0;
// Get the adjusted size of the box, considering that the handle's center never touches the left or right side.
// There is a margin of half the handle's width on both sides.
var boxAdjustedPercent = 1 - handlePercent;
// Adjust the progress that we'll use to set widths to the new adjusted box width
var adjustedProgress = progress * boxAdjustedPercent;
// The bar does reach the left side, so we need to account for this in the bar's width
var barProgress = adjustedProgress + handlePercent / 2;
var percentage = Lib.round(adjustedProgress * 100, 2) + '%';
if (vertical) {
handle.el().style.bottom = percentage;
} else {
handle.el().style.left = percentage;
}
return barProgress;
}
}, {
key: 'calculateDistance',
value: function calculateDistance(event) {
var el = this.el_;
var box = Lib.findPosition(el);
var boxW = el.offsetWidth;
var boxH = el.offsetHeight;
var handle = this.handle;
if (this.options().vertical) {
var boxY = box.top;
var pageY = undefined;
if (event.changedTouches) {
pageY = event.changedTouches[0].pageY;
} else {
pageY = event.pageY;
}
if (handle) {
var handleH = handle.el().offsetHeight;
// Adjusted X and Width, so handle doesn't go outside the bar
boxY = boxY + handleH / 2;
boxH = boxH - handleH;
}
// Percent that the click is through the adjusted area
return Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH));
} else {
var boxX = box.left;
var pageX = undefined;
if (event.changedTouches) {
pageX = event.changedTouches[0].pageX;
} else {
pageX = event.pageX;
}
if (handle) {
var handleW = handle.el().offsetWidth;
// Adjusted X and Width, so handle doesn't go outside the bar
boxX = boxX + handleW / 2;
boxW = boxW - handleW;
}
// Percent that the click is through the adjusted area
return Math.max(0, Math.min(1, (pageX - boxX) / boxW));
}
}
}, {
key: 'handleFocus',
value: function handleFocus() {
this.on(_document2['default'], 'keydown', this.handleKeyPress);
}
}, {
key: 'handleKeyPress',
value: function handleKeyPress(event) {
if (event.which == 37 || event.which == 40) {
// Left and Down Arrows
event.preventDefault();
this.stepBack();
} else if (event.which == 38 || event.which == 39) {
// Up and Right Arrows
event.preventDefault();
this.stepForward();
}
}
}, {
key: 'handleBlur',
value: function handleBlur() {
this.off(_document2['default'], 'keydown', this.handleKeyPress);
}
}, {
key: 'handleClick',
/**
* Listener for click events on slider, used to prevent clicks
* from bubbling up to parent elements like button menus.
* @param {Object} event Event object
*/
value: function handleClick(event) {
event.stopImmediatePropagation();
event.preventDefault();
}
}, {
key: 'vertical',
value: function vertical(bool) {
if (bool === undefined) {
return this.vertical_ || false;
}
this.vertical_ = !!bool;
if (this.vertical_) {
this.addClass('vjs-slider-vertical');
} else {
this.addClass('vjs-slider-horizontal');
}
return this;
}
}]);
return Slider;
})(_Component3['default']);
_Component3['default'].registerComponent('Slider', Slider);
exports['default'] = Slider;
module.exports = exports['default'];
},{"../component.js":7,"../lib.js":46,"global/document":1}],59:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function FlashRtmpDecorator(Flash) {
Flash.streamingFormats = {
'rtmp/mp4': 'MP4',
'rtmp/flv': 'FLV'
};
Flash.streamFromParts = function (connection, stream) {
return connection + '&' + stream;
};
Flash.streamToParts = function (src) {
var parts = {
connection: '',
stream: ''
};
if (!src) return parts;
// Look for the normal URL separator we expect, '&'.
// If found, we split the URL into two pieces around the
// first '&'.
var connEnd = src.indexOf('&');
var streamBegin = undefined;
if (connEnd !== -1) {
streamBegin = connEnd + 1;
} else {
// If there's not a '&', we use the last '/' as the delimiter.
connEnd = streamBegin = src.lastIndexOf('/') + 1;
if (connEnd === 0) {
// really, there's not a '/'?
connEnd = streamBegin = src.length;
}
}
parts.connection = src.substring(0, connEnd);
parts.stream = src.substring(streamBegin, src.length);
return parts;
};
Flash.isStreamingType = function (srcType) {
return srcType in Flash.streamingFormats;
};
// RTMP has four variations, any string starting
// with one of these protocols should be valid
Flash.RTMP_RE = /^rtmp[set]?:\/\//i;
Flash.isStreamingSrc = function (src) {
return Flash.RTMP_RE.test(src);
};
/**
* A source handler for RTMP urls
* @type {Object}
*/
Flash.rtmpSourceHandler = {};
/**
* Check Flash can handle the source natively
* @param {Object} source The source object
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Flash.rtmpSourceHandler.canHandleSource = function (source) {
if (Flash.isStreamingType(source.type) || Flash.isStreamingSrc(source.src)) {
return 'maybe';
}
return '';
};
/**
* Pass the source to the flash object
* Adaptive source handlers will have more complicated workflows before passing
* video data to the video element
* @param {Object} source The source object
* @param {Flash} tech The instance of the Flash tech
*/
Flash.rtmpSourceHandler.handleSource = function (source, tech) {
var srcParts = Flash.streamToParts(source.src);
tech.setRtmpConnection(srcParts.connection);
tech.setRtmpStream(srcParts.stream);
};
// Register the native source handler
Flash.registerSourceHandler(Flash.rtmpSourceHandler);
return Flash;
}
exports['default'] = FlashRtmpDecorator;
module.exports = exports['default'];
},{}],60:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
/**
* @fileoverview VideoJS-SWF - Custom Flash Player with HTML5-ish API
* https://github.com/zencoder/video-js-swf
* Not using setupTriggers. Using global onEvent func to distribute events
*/
var _Tech2 = _dereq_('./tech');
var _Tech3 = _interopRequireWildcard(_Tech2);
var _import = _dereq_('../lib');
var Lib = _interopRequireWildcard(_import);
var _FlashRtmpDecorator = _dereq_('./flash-rtmp');
var _FlashRtmpDecorator2 = _interopRequireWildcard(_FlashRtmpDecorator);
var _Component = _dereq_('../component');
var _Component2 = _interopRequireWildcard(_Component);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
var navigator = _window2['default'].navigator;
/**
* Flash Media Controller - Wrapper for fallback SWF API
*
* @param {Player} player
* @param {Object=} options
* @param {Function=} ready
* @constructor
*/
var Flash = (function (_Tech) {
function Flash(player, options, ready) {
_classCallCheck(this, Flash);
_get(Object.getPrototypeOf(Flash.prototype), 'constructor', this).call(this, player, options, ready);
var source = options.source;
var parentEl = options.parentEl;
// Create a temporary element to be replaced by swf object
var placeHolder = this.el_ = Lib.createEl('div', { id: player.id() + '_temp_flash' });
// Generate ID for swf object
var objId = player.id() + '_flash_api';
// Store player options in local var for optimization
// TODO: switch to using player methods instead of options
// e.g. player.autoplay();
var playerOptions = player.options_;
// Merge default flashvars with ones passed in to init
var flashVars = Lib.obj.merge({
// SWF Callback Functions
readyFunction: 'videojs.Flash.onReady',
eventProxyFunction: 'videojs.Flash.onEvent',
errorEventProxyFunction: 'videojs.Flash.onError',
// Player Settings
autoplay: playerOptions.autoplay,
preload: playerOptions.preload,
loop: playerOptions.loop,
muted: playerOptions.muted
}, options.flashVars);
// Merge default parames with ones passed in
var params = Lib.obj.merge({
wmode: 'opaque', // Opaque is needed to overlay controls, but can affect playback performance
bgcolor: '#000000' // Using bgcolor prevents a white flash when the object is loading
}, options.params);
// Merge default attributes with ones passed in
var attributes = Lib.obj.merge({
id: objId,
name: objId, // Both ID and Name needed or swf to identify itself
'class': 'vjs-tech'
}, options.attributes);
// If source was supplied pass as a flash var.
if (source) {
this.ready(function () {
this.setSource(source);
});
}
// Add placeholder to player div
Lib.insertFirst(placeHolder, parentEl);
// Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers
// This allows resetting the playhead when we catch the reload
if (options.startTime) {
this.ready(function () {
this.load();
this.play();
this.currentTime(options.startTime);
});
}
// firefox doesn't bubble mousemove events to parent. videojs/video-js-swf#37
// bugzilla bug: https://bugzilla.mozilla.org/show_bug.cgi?id=836786
if (Lib.IS_FIREFOX) {
this.ready(function () {
this.on('mousemove', function () {
// since it's a custom event, don't bubble higher than the player
this.player().trigger({ type: 'mousemove', bubbles: false });
});
});
}
// native click events on the SWF aren't triggered on IE11, Win8.1RT
// use stageclick events triggered from inside the SWF instead
player.on('stageclick', player.reportUserActivity);
this.el_ = Flash.embed(options.swf, placeHolder, flashVars, params, attributes);
}
_inherits(Flash, _Tech);
_createClass(Flash, [{
key: 'play',
value: function play() {
this.el_.vjs_play();
}
}, {
key: 'pause',
value: function pause() {
this.el_.vjs_pause();
}
}, {
key: 'src',
value: (function (_src) {
function src(_x) {
return _src.apply(this, arguments);
}
src.toString = function () {
return src.toString();
};
return src;
})(function (src) {
if (src === undefined) {
return this.currentSrc();
}
// Setting src through `src` not `setSrc` will be deprecated
return this.setSrc(src);
})
}, {
key: 'setSrc',
value: function setSrc(src) {
// Make sure source URL is absolute.
src = Lib.getAbsoluteURL(src);
this.el_.vjs_src(src);
// Currently the SWF doesn't autoplay if you load a source later.
// e.g. Load player w/ no source, wait 2s, set src.
if (this.player_.autoplay()) {
var tech = this;
this.setTimeout(function () {
tech.play();
}, 0);
}
}
}, {
key: 'setCurrentTime',
value: function setCurrentTime(time) {
this.lastSeekTarget_ = time;
this.el_.vjs_setProperty('currentTime', time);
_get(Object.getPrototypeOf(Flash.prototype), 'setCurrentTime', this).call(this);
}
}, {
key: 'currentTime',
value: function currentTime(time) {
// when seeking make the reported time keep up with the requested time
// by reading the time we're seeking to
if (this.seeking()) {
return this.lastSeekTarget_ || 0;
}
return this.el_.vjs_getProperty('currentTime');
}
}, {
key: 'currentSrc',
value: function currentSrc() {
if (this.currentSource_) {
return this.currentSource_.src;
} else {
return this.el_.vjs_getProperty('currentSrc');
}
}
}, {
key: 'load',
value: function load() {
this.el_.vjs_load();
}
}, {
key: 'poster',
value: function poster() {
this.el_.vjs_getProperty('poster');
}
}, {
key: 'setPoster',
// poster images are not handled by the Flash tech so make this a no-op
value: function setPoster() {}
}, {
key: 'buffered',
value: function buffered() {
return Lib.createTimeRange(0, this.el_.vjs_getProperty('buffered'));
}
}, {
key: 'supportsFullScreen',
value: function supportsFullScreen() {
return false; // Flash does not allow fullscreen through javascript
}
}, {
key: 'enterFullScreen',
value: function enterFullScreen() {
return false;
}
}]);
return Flash;
})(_Tech3['default']);
// Create setters and getters for attributes
var _api = Flash.prototype;
var _readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(',');
var _readOnly = 'error,networkState,readyState,seeking,initialTime,duration,startOffsetTime,paused,played,seekable,ended,videoTracks,audioTracks,videoWidth,videoHeight'.split(',');
function _createSetter(attr) {
var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1);
_api['set' + attrUpper] = function (val) {
return this.el_.vjs_setProperty(attr, val);
};
}
function _createGetter(attr) {
_api[attr] = function () {
return this.el_.vjs_getProperty(attr);
};
}
// Create getter and setters for all read/write attributes
for (var i = 0; i < _readWrite.length; i++) {
_createGetter(_readWrite[i]);
_createSetter(_readWrite[i]);
}
// Create getters for read-only attributes
for (var i = 0; i < _readOnly.length; i++) {
_createGetter(_readOnly[i]);
}
/* Flash Support Testing -------------------------------------------------------- */
Flash.isSupported = function () {
return Flash.version()[0] >= 10;
// return swfobject.hasFlashPlayerVersion('10');
};
// Add Source Handler pattern functions to this tech
_Tech3['default'].withSourceHandlers(Flash);
/**
* The default native source handler.
* This simply passes the source to the video element. Nothing fancy.
* @param {Object} source The source object
* @param {Flash} tech The instance of the Flash tech
*/
Flash.nativeSourceHandler = {};
/**
* Check Flash can handle the source natively
* @param {Object} source The source object
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Flash.nativeSourceHandler.canHandleSource = function (source) {
var type;
function guessMimeType(src) {
var ext = Lib.getFileExtension(src);
if (ext) {
return 'video/' + ext;
}
return '';
}
if (!source.type) {
type = guessMimeType(source.src);
} else {
// Strip code information from the type because we don't get that specific
type = source.type.replace(/;.*/, '').toLowerCase();
}
if (type in Flash.formats) {
return 'maybe';
}
return '';
};
/**
* Pass the source to the flash object
* Adaptive source handlers will have more complicated workflows before passing
* video data to the video element
* @param {Object} source The source object
* @param {Flash} tech The instance of the Flash tech
*/
Flash.nativeSourceHandler.handleSource = function (source, tech) {
tech.setSrc(source.src);
};
/**
* Clean up the source handler when disposing the player or switching sources..
* (no cleanup is needed when supporting the format natively)
*/
Flash.nativeSourceHandler.dispose = function () {};
// Register the native source handler
Flash.registerSourceHandler(Flash.nativeSourceHandler);
Flash.formats = {
'video/flv': 'FLV',
'video/x-flv': 'FLV',
'video/mp4': 'MP4',
'video/m4v': 'MP4'
};
Flash.onReady = function (currSwf) {
var el = Lib.el(currSwf);
// get player from the player div property
var player = el && el.parentNode && el.parentNode.player;
// if there is no el or player then the tech has been disposed
// and the tech element was removed from the player div
if (player) {
// reference player on tech element
el.player = player;
// check that the flash object is really ready
Flash.checkReady(player.tech);
}
};
// The SWF isn't always ready when it says it is. Sometimes the API functions still need to be added to the object.
// If it's not ready, we set a timeout to check again shortly.
Flash.checkReady = function (tech) {
// stop worrying if the tech has been disposed
if (!tech.el()) {
return;
}
// check if API property exists
if (tech.el().vjs_getProperty) {
// tell tech it's ready
tech.triggerReady();
} else {
// wait longer
this.setTimeout(function () {
Flash.checkReady(tech);
}, 50);
}
};
// Trigger events from the swf on the player
Flash.onEvent = function (swfID, eventName) {
var player = Lib.el(swfID).player;
player.trigger(eventName);
};
// Log errors from the swf
Flash.onError = function (swfID, err) {
var player = Lib.el(swfID).player;
var msg = 'FLASH: ' + err;
if (err == 'srcnotfound') {
player.error({ code: 4, message: msg });
// errors we haven't categorized into the media errors
} else {
player.error(msg);
}
};
// Flash Version Check
Flash.version = function () {
var version = '0,0,0';
// IE
try {
version = new _window2['default'].ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
// other browsers
} catch (e) {
try {
if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
}
} catch (err) {}
}
return version.split(',');
};
// Flash embedding method. Only used in non-iframe mode
Flash.embed = function (swf, placeHolder, flashVars, params, attributes) {
var code = Flash.getEmbedCode(swf, flashVars, params, attributes);
// Get element by embedding code and retrieving created element
var obj = Lib.createEl('div', { innerHTML: code }).childNodes[0];
var par = placeHolder.parentNode;
placeHolder.parentNode.replaceChild(obj, placeHolder);
return obj;
};
Flash.getEmbedCode = function (swf, flashVars, params, attributes) {
var objTag = '<object type="application/x-shockwave-flash" ';
var flashVarsString = '';
var paramsString = '';
var attrsString = '';
// Convert flash vars to string
if (flashVars) {
Lib.obj.each(flashVars, function (key, val) {
flashVarsString += '' + key + '=' + val + '&';
});
}
// Add swf, flashVars, and other default params
params = Lib.obj.merge({
movie: swf,
flashvars: flashVarsString,
allowScriptAccess: 'always', // Required to talk to swf
allowNetworking: 'all' // All should be default, but having security issues.
}, params);
// Create param tags string
Lib.obj.each(params, function (key, val) {
paramsString += '<param name="' + key + '" value="' + val + '" />';
});
attributes = Lib.obj.merge({
// Add swf to attributes (need both for IE and Others to work)
data: swf,
// Default to 100% width/height
width: '100%',
height: '100%'
}, attributes);
// Create Attributes string
Lib.obj.each(attributes, function (key, val) {
attrsString += '' + key + '="' + val + '" ';
});
return '' + objTag + '' + attrsString + '>' + paramsString + '</object>';
};
// Run Flash through the RTMP decorator
_FlashRtmpDecorator2['default'](Flash);
_Tech3['default'].registerComponent('Flash', Flash);
exports['default'] = Flash;
module.exports = exports['default'];
},{"../component":7,"../lib":46,"./flash-rtmp":59,"./tech":63,"global/window":2}],61:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
/**
* @fileoverview HTML5 Media Controller - Wrapper for HTML5 Media API
*/
var _Tech2 = _dereq_('./tech.js');
var _Tech3 = _interopRequireWildcard(_Tech2);
var _Component = _dereq_('../component');
var _Component2 = _interopRequireWildcard(_Component);
var _import = _dereq_('../lib');
var Lib = _interopRequireWildcard(_import);
var _import2 = _dereq_('../util');
var VjsUtil = _interopRequireWildcard(_import2);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
/**
* HTML5 Media Controller - Wrapper for HTML5 Media API
* @param {Player|Object} player
* @param {Object=} options
* @param {Function=} ready
* @constructor
*/
var Html5 = (function (_Tech) {
function Html5(player, options, ready) {
_classCallCheck(this, Html5);
_get(Object.getPrototypeOf(Html5.prototype), 'constructor', this).call(this, player, options, ready);
this.setupTriggers();
var source = options.source;
// Set the source if one is provided
// 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
// 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
// anyway so the error gets fired.
if (source && (this.el_.currentSrc !== source.src || player.tag && player.tag.initNetworkState_ === 3)) {
this.setSource(source);
}
if (this.el_.hasChildNodes()) {
var nodes = this.el_.childNodes;
var nodesLength = nodes.length;
var removeNodes = [];
while (nodesLength--) {
var node = nodes[nodesLength];
var nodeName = node.nodeName.toLowerCase();
if (nodeName === 'track') {
if (!this.featuresNativeTextTracks) {
// Empty video tag tracks so the built-in player doesn't use them also.
// This may not be fast enough to stop HTML5 browsers from reading the tags
// so we'll need to turn off any default tracks if we're manually doing
// captions and subtitles. videoElement.textTracks
removeNodes.push(node);
} else {
this.remoteTextTracks().addTrack_(node.track);
}
}
}
for (var i = 0; i < removeNodes.length; i++) {
this.el_.removeChild(removeNodes[i]);
}
}
if (this.featuresNativeTextTracks) {
this.on('loadstart', Lib.bind(this, this.hideCaptions));
}
// Determine if native controls should be used
// Our goal should be to get the custom controls on mobile solid everywhere
// so we can remove this all together. Right now this will block custom
// controls on touch enabled laptops like the Chrome Pixel
if (Lib.TOUCH_ENABLED && player.options().nativeControlsForTouch === true) {
this.useNativeControls();
}
// Chrome and Safari both have issues with autoplay.
// In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work.
// In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays)
// This fixes both issues. Need to wait for API, so it updates displays correctly
player.ready(function () {
if (this.tag && this.options_.autoplay && this.paused()) {
delete this.tag.poster; // Chrome Fix. Fixed in Chrome v16.
this.play();
}
});
this.triggerReady();
}
_inherits(Html5, _Tech);
_createClass(Html5, [{
key: 'dispose',
value: function dispose() {
Html5.disposeMediaElement(this.el_);
_get(Object.getPrototypeOf(Html5.prototype), 'dispose', this).call(this);
}
}, {
key: 'createEl',
value: function createEl() {
var player = this.player_;
var el = player.tag;
// Check if this browser supports moving the element into the box.
// On the iPhone video will break if you move the element,
// So we have to create a brand new element.
if (!el || this.movingMediaElementInDOM === false) {
// If the original tag is still there, clone and remove it.
if (el) {
var clone = el.cloneNode(false);
Html5.disposeMediaElement(el);
el = clone;
player.tag = null;
} else {
el = Lib.createEl('video');
// determine if native controls should be used
var attributes = VjsUtil.mergeOptions({}, player.tagAttributes);
if (!Lib.TOUCH_ENABLED || player.options().nativeControlsForTouch !== true) {
delete attributes.controls;
}
Lib.setElementAttributes(el, Lib.obj.merge(attributes, {
id: player.id() + '_html5_api',
'class': 'vjs-tech'
}));
}
// associate the player with the new tag
el.player = player;
if (player.options_.tracks) {
for (var i = 0; i < player.options_.tracks.length; i++) {
var track = player.options_.tracks[i];
var trackEl = _document2['default'].createElement('track');
trackEl.kind = track.kind;
trackEl.label = track.label;
trackEl.srclang = track.srclang;
trackEl.src = track.src;
if ('default' in track) {
trackEl.setAttribute('default', 'default');
}
el.appendChild(trackEl);
}
}
Lib.insertFirst(el, player.el());
}
// Update specific tag settings, in case they were overridden
var settingsAttrs = ['autoplay', 'preload', 'loop', 'muted'];
for (var i = settingsAttrs.length - 1; i >= 0; i--) {
var attr = settingsAttrs[i];
var overwriteAttrs = {};
if (typeof player.options_[attr] !== 'undefined') {
overwriteAttrs[attr] = player.options_[attr];
}
Lib.setElementAttributes(el, overwriteAttrs);
}
return el;
// jenniisawesome = true;
}
}, {
key: 'hideCaptions',
value: function hideCaptions() {
var tracks = this.el_.querySelectorAll('track');
var i = tracks.length;
var kinds = {
captions: 1,
subtitles: 1
};
while (i--) {
var track = tracks[i].track;
if (track && track.kind in kinds && !tracks[i]['default']) {
track.mode = 'disabled';
}
}
}
}, {
key: 'setupTriggers',
// Make video events trigger player events
// May seem verbose here, but makes other APIs possible.
// Triggers removed using this.off when disposed
value: function setupTriggers() {
for (var i = Html5.Events.length - 1; i >= 0; i--) {
this.on(Html5.Events[i], this.eventHandler);
}
}
}, {
key: 'eventHandler',
value: function eventHandler(evt) {
// In the case of an error on the video element, set the error prop
// on the player and let the player handle triggering the event. On
// some platforms, error events fire that do not cause the error
// property on the video element to be set. See #1465 for an example.
if (evt.type == 'error' && this.error()) {
this.player().error(this.error().code);
// in some cases we pass the event directly to the player
} else {
// No need for media events to bubble up.
evt.bubbles = false;
this.player().trigger(evt);
}
}
}, {
key: 'useNativeControls',
value: function useNativeControls() {
var tech = this;
var player = this.player();
// If the player controls are enabled turn on the native controls
tech.setControls(player.controls());
// Update the native controls when player controls state is updated
var controlsOn = function controlsOn() {
tech.setControls(true);
};
var controlsOff = function controlsOff() {
tech.setControls(false);
};
player.on('controlsenabled', controlsOn);
player.on('controlsdisabled', controlsOff);
// Clean up when not using native controls anymore
var cleanUp = function cleanUp() {
player.off('controlsenabled', controlsOn);
player.off('controlsdisabled', controlsOff);
};
tech.on('dispose', cleanUp);
player.on('usingcustomcontrols', cleanUp);
// Update the state of the player to using native controls
player.usingNativeControls(true);
}
}, {
key: 'play',
value: function play() {
this.el_.play();
}
}, {
key: 'pause',
value: function pause() {
this.el_.pause();
}
}, {
key: 'paused',
value: function paused() {
return this.el_.paused;
}
}, {
key: 'currentTime',
value: function currentTime() {
return this.el_.currentTime;
}
}, {
key: 'setCurrentTime',
value: function setCurrentTime(seconds) {
try {
this.el_.currentTime = seconds;
} catch (e) {
Lib.log(e, 'Video is not ready. (Video.js)');
// this.warning(VideoJS.warnings.videoNotReady);
}
}
}, {
key: 'duration',
value: function duration() {
return this.el_.duration || 0;
}
}, {
key: 'buffered',
value: function buffered() {
return this.el_.buffered;
}
}, {
key: 'volume',
value: function volume() {
return this.el_.volume;
}
}, {
key: 'setVolume',
value: function setVolume(percentAsDecimal) {
this.el_.volume = percentAsDecimal;
}
}, {
key: 'muted',
value: function muted() {
return this.el_.muted;
}
}, {
key: 'setMuted',
value: function setMuted(muted) {
this.el_.muted = muted;
}
}, {
key: 'width',
value: function width() {
return this.el_.offsetWidth;
}
}, {
key: 'height',
value: function height() {
return this.el_.offsetHeight;
}
}, {
key: 'supportsFullScreen',
value: function supportsFullScreen() {
if (typeof this.el_.webkitEnterFullScreen == 'function') {
// Seems to be broken in Chromium/Chrome && Safari in Leopard
if (/Android/.test(Lib.USER_AGENT) || !/Chrome|Mac OS X 10.5/.test(Lib.USER_AGENT)) {
return true;
}
}
return false;
}
}, {
key: 'enterFullScreen',
value: function enterFullScreen() {
var video = this.el_;
if ('webkitDisplayingFullscreen' in video) {
this.one('webkitbeginfullscreen', function () {
this.player_.isFullscreen(true);
this.one('webkitendfullscreen', function () {
this.player_.isFullscreen(false);
this.player_.trigger('fullscreenchange');
});
this.player_.trigger('fullscreenchange');
});
}
if (video.paused && video.networkState <= video.HAVE_METADATA) {
// attempt to prime the video element for programmatic access
// this isn't necessary on the desktop but shouldn't hurt
this.el_.play();
// playing and pausing synchronously during the transition to fullscreen
// can get iOS ~6.1 devices into a play/pause loop
this.setTimeout(function () {
video.pause();
video.webkitEnterFullScreen();
}, 0);
} else {
video.webkitEnterFullScreen();
}
}
}, {
key: 'exitFullScreen',
value: function exitFullScreen() {
this.el_.webkitExitFullScreen();
}
}, {
key: 'src',
value: (function (_src) {
function src(_x) {
return _src.apply(this, arguments);
}
src.toString = function () {
return src.toString();
};
return src;
})(function (src) {
if (src === undefined) {
return this.el_.src;
} else {
// Setting src through `src` instead of `setSrc` will be deprecated
this.setSrc(src);
}
})
}, {
key: 'setSrc',
value: function setSrc(src) {
this.el_.src = src;
}
}, {
key: 'load',
value: function load() {
this.el_.load();
}
}, {
key: 'currentSrc',
value: function currentSrc() {
return this.el_.currentSrc;
}
}, {
key: 'poster',
value: function poster() {
return this.el_.poster;
}
}, {
key: 'setPoster',
value: function setPoster(val) {
this.el_.poster = val;
}
}, {
key: 'preload',
value: function preload() {
return this.el_.preload;
}
}, {
key: 'setPreload',
value: function setPreload(val) {
this.el_.preload = val;
}
}, {
key: 'autoplay',
value: function autoplay() {
return this.el_.autoplay;
}
}, {
key: 'setAutoplay',
value: function setAutoplay(val) {
this.el_.autoplay = val;
}
}, {
key: 'controls',
value: function controls() {
return this.el_.controls;
}
}, {
key: 'setControls',
value: function setControls(val) {
this.el_.controls = !!val;
}
}, {
key: 'loop',
value: function loop() {
return this.el_.loop;
}
}, {
key: 'setLoop',
value: function setLoop(val) {
this.el_.loop = val;
}
}, {
key: 'error',
value: function error() {
return this.el_.error;
}
}, {
key: 'seeking',
value: function seeking() {
return this.el_.seeking;
}
}, {
key: 'ended',
value: function ended() {
return this.el_.ended;
}
}, {
key: 'defaultMuted',
value: function defaultMuted() {
return this.el_.defaultMuted;
}
}, {
key: 'playbackRate',
value: function playbackRate() {
return this.el_.playbackRate;
}
}, {
key: 'setPlaybackRate',
value: function setPlaybackRate(val) {
this.el_.playbackRate = val;
}
}, {
key: 'networkState',
value: function networkState() {
return this.el_.networkState;
}
}, {
key: 'readyState',
value: function readyState() {
return this.el_.readyState;
}
}, {
key: 'textTracks',
value: function textTracks() {
if (!this.featuresNativeTextTracks) {
return _get(Object.getPrototypeOf(Html5.prototype), 'textTracks', this).call(this);
}
return this.el_.textTracks;
}
}, {
key: 'addTextTrack',
value: function addTextTrack(kind, label, language) {
if (!this.featuresNativeTextTracks) {
return _get(Object.getPrototypeOf(Html5.prototype), 'addTextTrack', this).call(this, kind, label, language);
}
return this.el_.addTextTrack(kind, label, language);
}
}, {
key: 'addRemoteTextTrack',
value: function addRemoteTextTrack() {
var options = arguments[0] === undefined ? {} : arguments[0];
if (!this.featuresNativeTextTracks) {
return _get(Object.getPrototypeOf(Html5.prototype), 'addRemoteTextTrack', this).call(this, options);
}
var track = _document2['default'].createElement('track');
if (options.kind) {
track.kind = options.kind;
}
if (options.label) {
track.label = options.label;
}
if (options.language || options.srclang) {
track.srclang = options.language || options.srclang;
}
if (options['default']) {
track['default'] = options['default'];
}
if (options.id) {
track.id = options.id;
}
if (options.src) {
track.src = options.src;
}
this.el().appendChild(track);
if (track.track.kind === 'metadata') {
track.track.mode = 'hidden';
} else {
track.track.mode = 'disabled';
}
track.onload = function () {
var tt = track.track;
if (track.readyState >= 2) {
if (tt.kind === 'metadata' && tt.mode !== 'hidden') {
tt.mode = 'hidden';
} else if (tt.kind !== 'metadata' && tt.mode !== 'disabled') {
tt.mode = 'disabled';
}
track.onload = null;
}
};
this.remoteTextTracks().addTrack_(track.track);
return track;
}
}, {
key: 'removeRemoteTextTrack',
value: function removeRemoteTextTrack(track) {
if (!this.featuresNativeTextTracks) {
return _get(Object.getPrototypeOf(Html5.prototype), 'removeRemoteTextTrack', this).call(this, track);
}
var tracks, i;
this.remoteTextTracks().removeTrack_(track);
tracks = this.el().querySelectorAll('track');
for (i = 0; i < tracks.length; i++) {
if (tracks[i] === track || tracks[i].track === track) {
tracks[i].parentNode.removeChild(tracks[i]);
break;
}
}
}
}]);
return Html5;
})(_Tech3['default']);
/* HTML5 Support Testing ---------------------------------------------------- */
/**
* Check if HTML5 video is supported by this browser/device
* @return {Boolean}
*/
Html5.isSupported = function () {
// IE9 with no Media Player is a LIAR! (#984)
try {
Lib.TEST_VID.volume = 0.5;
} catch (e) {
return false;
}
return !!Lib.TEST_VID.canPlayType;
};
// Add Source Handler pattern functions to this tech
_Tech3['default'].withSourceHandlers(Html5);
/**
* The default native source handler.
* This simply passes the source to the video element. Nothing fancy.
* @param {Object} source The source object
* @param {Html5} tech The instance of the HTML5 tech
*/
Html5.nativeSourceHandler = {};
/**
* Check if the video element can handle the source natively
* @param {Object} source The source object
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Html5.nativeSourceHandler.canHandleSource = function (source) {
var match, ext;
function canPlayType(type) {
// IE9 on Windows 7 without MediaPlayer throws an error here
// https://github.com/videojs/video.js/issues/519
try {
return Lib.TEST_VID.canPlayType(type);
} catch (e) {
return '';
}
}
// If a type was provided we should rely on that
if (source.type) {
return canPlayType(source.type);
} else if (source.src) {
// If no type, fall back to checking 'video/[EXTENSION]'
ext = Lib.getFileExtension(source.src);
return canPlayType('video/' + ext);
}
return '';
};
/**
* Pass the source to the video element
* Adaptive source handlers will have more complicated workflows before passing
* video data to the video element
* @param {Object} source The source object
* @param {Html5} tech The instance of the Html5 tech
*/
Html5.nativeSourceHandler.handleSource = function (source, tech) {
tech.setSrc(source.src);
};
/**
* Clean up the source handler when disposing the player or switching sources..
* (no cleanup is needed when supporting the format natively)
*/
Html5.nativeSourceHandler.dispose = function () {};
// Register the native source handler
Html5.registerSourceHandler(Html5.nativeSourceHandler);
/**
* Check if the volume can be changed in this browser/device.
* Volume cannot be changed in a lot of mobile devices.
* Specifically, it can't be changed from 1 on iOS.
* @return {Boolean}
*/
Html5.canControlVolume = function () {
var volume = Lib.TEST_VID.volume;
Lib.TEST_VID.volume = volume / 2 + 0.1;
return volume !== Lib.TEST_VID.volume;
};
/**
* Check if playbackRate is supported in this browser/device.
* @return {[type]} [description]
*/
Html5.canControlPlaybackRate = function () {
var playbackRate = Lib.TEST_VID.playbackRate;
Lib.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
return playbackRate !== Lib.TEST_VID.playbackRate;
};
/**
* Check to see if native text tracks are supported by this browser/device
* @return {Boolean}
*/
Html5.supportsNativeTextTracks = function () {
var supportsTextTracks;
// Figure out native text track support
// If mode is a number, we cannot change it because it'll disappear from view.
// Browsers with numeric modes include IE10 and older (<=2013) samsung android models.
// Firefox isn't playing nice either with modifying the mode
// TODO: Investigate firefox: https://github.com/videojs/video.js/issues/1862
supportsTextTracks = !!Lib.TEST_VID.textTracks;
if (supportsTextTracks && Lib.TEST_VID.textTracks.length > 0) {
supportsTextTracks = typeof Lib.TEST_VID.textTracks[0].mode !== 'number';
}
if (supportsTextTracks && Lib.IS_FIREFOX) {
supportsTextTracks = false;
}
return supportsTextTracks;
};
/**
* Set the tech's volume control support status
* @type {Boolean}
*/
Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
/**
* Set the tech's playbackRate support status
* @type {Boolean}
*/
Html5.prototype.featuresPlaybackRate = Html5.canControlPlaybackRate();
/**
* Set the tech's status on moving the video element.
* In iOS, if you move a video element in the DOM, it breaks video playback.
* @type {Boolean}
*/
Html5.prototype.movingMediaElementInDOM = !Lib.IS_IOS;
/**
* Set the the tech's fullscreen resize support status.
* HTML video is able to automatically resize when going to fullscreen.
* (No longer appears to be used. Can probably be removed.)
*/
Html5.prototype.featuresFullscreenResize = true;
/**
* Set the tech's progress event support status
* (this disables the manual progress events of the Tech)
*/
Html5.prototype.featuresProgressEvents = true;
/**
* Sets the tech's status on native text track support
* @type {Boolean}
*/
Html5.prototype.featuresNativeTextTracks = Html5.supportsNativeTextTracks();
// HTML5 Feature detection and Device Fixes --------------------------------- //
var canPlayType = undefined;
var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i;
var mp4RE = /^video\/mp4/i;
Html5.patchCanPlayType = function () {
// Android 4.0 and above can play HLS to some extent but it reports being unable to do so
if (Lib.ANDROID_VERSION >= 4) {
if (!canPlayType) {
canPlayType = Lib.TEST_VID.constructor.prototype.canPlayType;
}
Lib.TEST_VID.constructor.prototype.canPlayType = function (type) {
if (type && mpegurlRE.test(type)) {
return 'maybe';
}
return canPlayType.call(this, type);
};
}
// Override Android 2.2 and less canPlayType method which is broken
if (Lib.IS_OLD_ANDROID) {
if (!canPlayType) {
canPlayType = Lib.TEST_VID.constructor.prototype.canPlayType;
}
Lib.TEST_VID.constructor.prototype.canPlayType = function (type) {
if (type && mp4RE.test(type)) {
return 'maybe';
}
return canPlayType.call(this, type);
};
}
};
Html5.unpatchCanPlayType = function () {
var r = Lib.TEST_VID.constructor.prototype.canPlayType;
Lib.TEST_VID.constructor.prototype.canPlayType = canPlayType;
canPlayType = null;
return r;
};
// by default, patch the video element
Html5.patchCanPlayType();
// List of all HTML5 events (various uses).
Html5.Events = 'loadstart,suspend,abort,error,emptied,stalled,loadedmetadata,loadeddata,canplay,canplaythrough,playing,waiting,seeking,seeked,ended,durationchange,timeupdate,progress,play,pause,ratechange,volumechange'.split(',');
Html5.disposeMediaElement = function (el) {
if (!el) {
return;
}
el.player = null;
if (el.parentNode) {
el.parentNode.removeChild(el);
}
// remove any child track or source nodes to prevent their loading
while (el.hasChildNodes()) {
el.removeChild(el.firstChild);
}
// remove any src reference. not setting `src=''` because that causes a warning
// in firefox
el.removeAttribute('src');
// force the media element to update its loading state by calling load()
// however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
if (typeof el.load === 'function') {
// wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
(function () {
try {
el.load();
} catch (e) {}
})();
}
};
_Component2['default'].registerComponent('Html5', Html5);
exports['default'] = Html5;
module.exports = exports['default'];
// not supported
},{"../component":7,"../lib":46,"../util":70,"./tech.js":63,"global/document":1}],62:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../component');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('../lib');
var Lib = _interopRequireWildcard(_import);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
/**
* The Media Loader is the component that decides which playback technology to load
* when the player is initialized.
*
* @constructor
*/
var MediaLoader = (function (_Component) {
function MediaLoader(player, options, ready) {
_classCallCheck(this, MediaLoader);
_get(Object.getPrototypeOf(MediaLoader.prototype), 'constructor', this).call(this, player, options, ready);
// If there are no sources when the player is initialized,
// load the first supported playback technology.
if (!player.options_.sources || player.options_.sources.length === 0) {
for (var i = 0, j = player.options_.techOrder; i < j.length; i++) {
var techName = Lib.capitalize(j[i]);
var tech = _Component3['default'].getComponent(techName);
// Check if the browser supports this technology
if (tech && tech.isSupported()) {
player.loadTech(techName);
break;
}
}
} else {
// // Loop through playback technologies (HTML5, Flash) and check for support.
// // Then load the best source.
// // A few assumptions here:
// // All playback technologies respect preload false.
player.src(player.options_.sources);
}
}
_inherits(MediaLoader, _Component);
return MediaLoader;
})(_Component3['default']);
_Component3['default'].registerComponent('MediaLoader', MediaLoader);
exports['default'] = MediaLoader;
module.exports = exports['default'];
},{"../component":7,"../lib":46,"global/window":2}],63:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
/**
* @fileoverview Media Technology Controller - Base class for media playback
* technology controllers like Flash and HTML5
*/
var _Component2 = _dereq_('../component');
var _Component3 = _interopRequireWildcard(_Component2);
var _TextTrack = _dereq_('../tracks/text-track');
var _TextTrack2 = _interopRequireWildcard(_TextTrack);
var _TextTrackList = _dereq_('../tracks/text-track-list');
var _TextTrackList2 = _interopRequireWildcard(_TextTrackList);
var _import = _dereq_('../lib');
var Lib = _interopRequireWildcard(_import);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
/**
* Base class for media (HTML5 Video, Flash) controllers
* @param {Player|Object} player Central player instance
* @param {Object=} options Options object
* @constructor
*/
var Tech = (function (_Component) {
function Tech(player) {
var options = arguments[1] === undefined ? {} : arguments[1];
var ready = arguments[2] === undefined ? function () {} : arguments[2];
_classCallCheck(this, Tech);
// we don't want the tech to report user activity automatically.
// This is done manually in addControlsListeners
options.reportTouchActivity = false;
_get(Object.getPrototypeOf(Tech.prototype), 'constructor', this).call(this, player, options, ready);
// Manually track progress in cases where the browser/flash player doesn't report it.
if (!this.featuresProgressEvents) {
this.manualProgressOn();
}
// Manually track timeupdates in cases where the browser/flash player doesn't report it.
if (!this.featuresTimeupdateEvents) {
this.manualTimeUpdatesOn();
}
this.initControlsListeners();
if (options.nativeCaptions === false || options.nativeTextTracks === false) {
this.featuresNativeTextTracks = false;
}
if (!this.featuresNativeTextTracks) {
this.emulateTextTracks();
}
this.initTextTrackListeners();
}
_inherits(Tech, _Component);
_createClass(Tech, [{
key: 'initControlsListeners',
/**
* Set up click and touch listeners for the playback element
* On desktops, a click on the video itself will toggle playback,
* on a mobile device a click on the video toggles controls.
* (toggling controls is done by toggling the user state between active and
* inactive)
*
* A tap can signal that a user has become active, or has become inactive
* e.g. a quick tap on an iPhone movie should reveal the controls. Another
* quick tap should hide them again (signaling the user is in an inactive
* viewing state)
*
* In addition to this, we still want the user to be considered inactive after
* a few seconds of inactivity.
*
* Note: the only part of iOS interaction we can't mimic with this setup
* is a touch and hold on the video element counting as activity in order to
* keep the controls showing, but that shouldn't be an issue. A touch and hold on
* any controls will still keep the user active
*/
value: function initControlsListeners() {
var player = this.player();
var activateControls = function activateControls() {
if (player.controls() && !player.usingNativeControls()) {
this.addControlsListeners();
}
};
// Set up event listeners once the tech is ready and has an element to apply
// listeners to
this.ready(activateControls);
this.on(player, 'controlsenabled', activateControls);
this.on(player, 'controlsdisabled', this.removeControlsListeners);
// if we're loading the playback object after it has started loading or playing the
// video (often with autoplay on) then the loadstart event has already fired and we
// need to fire it manually because many things rely on it.
// Long term we might consider how we would do this for other events like 'canplay'
// that may also have fired.
this.ready(function () {
if (this.networkState && this.networkState() > 0) {
this.player().trigger('loadstart');
}
});
}
}, {
key: 'addControlsListeners',
value: function addControlsListeners() {
var userWasActive = undefined;
// Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do
// trigger mousedown/up.
// http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object
// Any touch events are set to block the mousedown event from happening
this.on('mousedown', this.handleClick);
// If the controls were hidden we don't want that to change without a tap event
// so we'll check if the controls were already showing before reporting user
// activity
this.on('touchstart', function (event) {
userWasActive = this.player_.userActive();
});
this.on('touchmove', function (event) {
if (userWasActive) {
this.player().reportUserActivity();
}
});
this.on('touchend', function (event) {
// Stop the mouse events from also happening
event.preventDefault();
});
// Turn on component tap events
this.emitTapEvents();
// The tap listener needs to come after the touchend listener because the tap
// listener cancels out any reportedUserActivity when setting userActive(false)
this.on('tap', this.handleTap);
}
}, {
key: 'removeControlsListeners',
/**
* Remove the listeners used for click and tap controls. This is needed for
* toggling to controls disabled, where a tap/touch should do nothing.
*/
value: function removeControlsListeners() {
// We don't want to just use `this.off()` because there might be other needed
// listeners added by techs that extend this.
this.off('tap');
this.off('touchstart');
this.off('touchmove');
this.off('touchleave');
this.off('touchcancel');
this.off('touchend');
this.off('click');
this.off('mousedown');
}
}, {
key: 'handleClick',
/**
* Handle a click on the media element. By default will play/pause the media.
*/
value: function handleClick(event) {
// We're using mousedown to detect clicks thanks to Flash, but mousedown
// will also be triggered with right-clicks, so we need to prevent that
if (event.button !== 0) {
return;
} // When controls are disabled a click should not toggle playback because
// the click is considered a control
if (this.player().controls()) {
if (this.player().paused()) {
this.player().play();
} else {
this.player().pause();
}
}
}
}, {
key: 'handleTap',
/**
* Handle a tap on the media element. By default it will toggle the user
* activity state, which hides and shows the controls.
*/
value: function handleTap() {
this.player().userActive(!this.player().userActive());
}
}, {
key: 'manualProgressOn',
/* Fallbacks for unsupported event types
================================================================================ */
// Manually trigger progress events based on changes to the buffered amount
// Many flash players and older HTML5 browsers don't send progress or progress-like events
value: function manualProgressOn() {
this.manualProgress = true;
// Trigger progress watching when a source begins loading
this.trackProgress();
}
}, {
key: 'manualProgressOff',
value: function manualProgressOff() {
this.manualProgress = false;
this.stopTrackingProgress();
}
}, {
key: 'trackProgress',
value: function trackProgress() {
this.progressInterval = this.setInterval(function () {
// Don't trigger unless buffered amount is greater than last time
var bufferedPercent = this.player().bufferedPercent();
if (this.bufferedPercent_ != bufferedPercent) {
this.player().trigger('progress');
}
this.bufferedPercent_ = bufferedPercent;
if (bufferedPercent === 1) {
this.stopTrackingProgress();
}
}, 500);
}
}, {
key: 'stopTrackingProgress',
value: function stopTrackingProgress() {
this.clearInterval(this.progressInterval);
}
}, {
key: 'manualTimeUpdatesOn',
/*! Time Tracking -------------------------------------------------------------- */
value: function manualTimeUpdatesOn() {
var player = this.player_;
this.manualTimeUpdates = true;
this.on(player, 'play', this.trackCurrentTime);
this.on(player, 'pause', this.stopTrackingCurrentTime);
// timeupdate is also called by .currentTime whenever current time is set
// Watch for native timeupdate event
this.one('timeupdate', function () {
// Update known progress support for this playback technology
this.featuresTimeupdateEvents = true;
// Turn off manual progress tracking
this.manualTimeUpdatesOff();
});
}
}, {
key: 'manualTimeUpdatesOff',
value: function manualTimeUpdatesOff() {
var player = this.player_;
this.manualTimeUpdates = false;
this.stopTrackingCurrentTime();
this.off(player, 'play', this.trackCurrentTime);
this.off(player, 'pause', this.stopTrackingCurrentTime);
}
}, {
key: 'trackCurrentTime',
value: function trackCurrentTime() {
if (this.currentTimeInterval) {
this.stopTrackingCurrentTime();
}
this.currentTimeInterval = this.setInterval(function () {
this.player().trigger('timeupdate');
}, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
}
}, {
key: 'stopTrackingCurrentTime',
// Turn off play progress tracking (when paused or dragging)
value: function stopTrackingCurrentTime() {
this.clearInterval(this.currentTimeInterval);
// #1002 - if the video ends right before the next timeupdate would happen,
// the progress bar won't make it all the way to the end
this.player().trigger('timeupdate');
}
}, {
key: 'dispose',
value: function dispose() {
// Turn off any manual progress or timeupdate tracking
if (this.manualProgress) {
this.manualProgressOff();
}
if (this.manualTimeUpdates) {
this.manualTimeUpdatesOff();
}
_get(Object.getPrototypeOf(Tech.prototype), 'dispose', this).call(this);
}
}, {
key: 'setCurrentTime',
value: function setCurrentTime() {
// improve the accuracy of manual timeupdates
if (this.manualTimeUpdates) {
this.player().trigger('timeupdate');
}
}
}, {
key: 'initTextTrackListeners',
// TODO: Consider looking at moving this into the text track display directly
// https://github.com/videojs/video.js/issues/1863
value: function initTextTrackListeners() {
var player = this.player_;
var textTrackListChanges = function textTrackListChanges() {
var textTrackDisplay = player.getChild('textTrackDisplay');
if (textTrackDisplay) {
textTrackDisplay.updateDisplay();
}
};
var tracks = this.textTracks();
if (!tracks) {
return;
}tracks.addEventListener('removetrack', textTrackListChanges);
tracks.addEventListener('addtrack', textTrackListChanges);
this.on('dispose', Lib.bind(this, function () {
tracks.removeEventListener('removetrack', textTrackListChanges);
tracks.removeEventListener('addtrack', textTrackListChanges);
}));
}
}, {
key: 'emulateTextTracks',
value: function emulateTextTracks() {
var player = this.player_;
if (!_window2['default'].WebVTT) {
var script = _document2['default'].createElement('script');
script.src = player.options()['vtt.js'] || '../node_modules/vtt.js/dist/vtt.js';
player.el().appendChild(script);
_window2['default'].WebVTT = true;
}
var tracks = this.textTracks();
if (!tracks) {
return;
}
var textTracksChanges = function textTracksChanges() {
var textTrackDisplay = player.getChild('textTrackDisplay');
textTrackDisplay.updateDisplay();
for (var i = 0; i < this.length; i++) {
var track = this[i];
track.removeEventListener('cuechange', Lib.bind(textTrackDisplay, textTrackDisplay.updateDisplay));
if (track.mode === 'showing') {
track.addEventListener('cuechange', Lib.bind(textTrackDisplay, textTrackDisplay.updateDisplay));
}
}
};
tracks.addEventListener('change', textTracksChanges);
this.on('dispose', Lib.bind(this, function () {
tracks.removeEventListener('change', textTracksChanges);
}));
}
}, {
key: 'textTracks',
/**
* Provide default methods for text tracks.
*
* Html5 tech overrides these.
*/
value: function textTracks() {
this.player_.textTracks_ = this.player_.textTracks_ || new _TextTrackList2['default']();
return this.player_.textTracks_;
}
}, {
key: 'remoteTextTracks',
value: function remoteTextTracks() {
this.player_.remoteTextTracks_ = this.player_.remoteTextTracks_ || new _TextTrackList2['default']();
return this.player_.remoteTextTracks_;
}
}, {
key: 'addTextTrack',
value: function addTextTrack(kind, label, language) {
if (!kind) {
throw new Error('TextTrack kind is required but was not provided');
}
return createTrackHelper(this, kind, label, language);
}
}, {
key: 'addRemoteTextTrack',
value: function addRemoteTextTrack(options) {
var track = createTrackHelper(this, options.kind, options.label, options.language, options);
this.remoteTextTracks().addTrack_(track);
return {
track: track
};
}
}, {
key: 'removeRemoteTextTrack',
value: function removeRemoteTextTrack(track) {
this.textTracks().removeTrack_(track);
this.remoteTextTracks().removeTrack_(track);
}
}, {
key: 'setPoster',
/**
* Provide a default setPoster method for techs
*
* Poster support for techs should be optional, so we don't want techs to
* break if they don't have a way to set a poster.
*/
value: function setPoster() {}
}]);
return Tech;
})(_Component3['default']);
/**
* List of associated text tracks
* @type {Array}
* @private
*/
Tech.prototype.textTracks_;
var createTrackHelper = function createTrackHelper(self, kind, label, language) {
var options = arguments[4] === undefined ? {} : arguments[4];
var tracks = self.textTracks();
options.kind = kind;
if (label) {
options.label = label;
}
if (language) {
options.language = language;
}
options.player = self.player_;
var track = new _TextTrack2['default'](options);
tracks.addTrack_(track);
return track;
};
Tech.prototype.featuresVolumeControl = true;
// Resizing plugins using request fullscreen reloads the plugin
Tech.prototype.featuresFullscreenResize = false;
Tech.prototype.featuresPlaybackRate = false;
// Optional events that we can manually mimic with timers
// currently not triggered by video-js-swf
Tech.prototype.featuresProgressEvents = false;
Tech.prototype.featuresTimeupdateEvents = false;
Tech.prototype.featuresNativeTextTracks = false;
/**
* A functional mixin for techs that want to use the Source Handler pattern.
*
* ##### EXAMPLE:
*
* Tech.withSourceHandlers.call(MyTech);
*
*/
Tech.withSourceHandlers = function (_Tech) {
/**
* Register a source handler
* Source handlers are scripts for handling specific formats.
* The source handler pattern is used for adaptive formats (HLS, DASH) that
* manually load video data and feed it into a Source Buffer (Media Source Extensions)
* @param {Function} handler The source handler
* @param {Boolean} first Register it before any existing handlers
*/
_Tech.registerSourceHandler = function (handler, index) {
var handlers = _Tech.sourceHandlers;
if (!handlers) {
handlers = _Tech.sourceHandlers = [];
}
if (index === undefined) {
// add to the end of the list
index = handlers.length;
}
handlers.splice(index, 0, handler);
};
/**
* Return the first source handler that supports the source
* TODO: Answer question: should 'probably' be prioritized over 'maybe'
* @param {Object} source The source object
* @returns {Object} The first source handler that supports the source
* @returns {null} Null if no source handler is found
*/
_Tech.selectSourceHandler = function (source) {
var handlers = _Tech.sourceHandlers || [];
var can = undefined;
for (var i = 0; i < handlers.length; i++) {
can = handlers[i].canHandleSource(source);
if (can) {
return handlers[i];
}
}
return null;
};
/**
* Check if the tech can support the given source
* @param {Object} srcObj The source object
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
_Tech.canPlaySource = function (srcObj) {
var sh = _Tech.selectSourceHandler(srcObj);
if (sh) {
return sh.canHandleSource(srcObj);
}
return '';
};
/**
* Create a function for setting the source using a source object
* and source handlers.
* Should never be called unless a source handler was found.
* @param {Object} source A source object with src and type keys
* @return {Tech} self
*/
_Tech.prototype.setSource = function (source) {
var sh = _Tech.selectSourceHandler(source);
if (!sh) {
// Fall back to a native source hander when unsupported sources are
// deliberately set
if (_Tech.nativeSourceHandler) {
sh = _Tech.nativeSourceHandler;
} else {
Lib.log.error('No source hander found for the current source.');
}
}
// Dispose any existing source handler
this.disposeSourceHandler();
this.off('dispose', this.disposeSourceHandler);
this.currentSource_ = source;
this.sourceHandler_ = sh.handleSource(source, this);
this.on('dispose', this.disposeSourceHandler);
return this;
};
/**
* Clean up any existing source handler
*/
_Tech.prototype.disposeSourceHandler = function () {
if (this.sourceHandler_ && this.sourceHandler_.dispose) {
this.sourceHandler_.dispose();
}
};
};
_Component3['default'].registerComponent('Tech', Tech);
// Old name for Tech
_Component3['default'].registerComponent('MediaTechController', Tech);
exports['default'] = Tech;
module.exports = exports['default'];
},{"../component":7,"../lib":46,"../tracks/text-track":69,"../tracks/text-track-list":67,"global/document":1,"global/window":2}],64:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _import = _dereq_('../lib');
var Lib = _interopRequireWildcard(_import);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist
*
* interface TextTrackCueList {
* readonly attribute unsigned long length;
* getter TextTrackCue (unsigned long index);
* TextTrackCue? getCueById(DOMString id);
* };
*/
var TextTrackCueList = (function (_TextTrackCueList) {
function TextTrackCueList(_x) {
return _TextTrackCueList.apply(this, arguments);
}
TextTrackCueList.toString = function () {
return TextTrackCueList.toString();
};
return TextTrackCueList;
})(function (cues) {
var list = this;
if (Lib.IS_IE8) {
list = _document2['default'].createElement('custom');
for (var prop in TextTrackCueList.prototype) {
list[prop] = TextTrackCueList.prototype[prop];
}
}
TextTrackCueList.prototype.setCues_.call(list, cues);
Object.defineProperty(list, 'length', {
get: function get() {
return this.length_;
}
});
if (Lib.IS_IE8) {
return list;
}
});
TextTrackCueList.prototype.setCues_ = function (cues) {
var oldLength = this.length || 0;
var i = 0;
var l = cues.length;
this.cues_ = cues;
this.length_ = cues.length;
var defineProp = function defineProp(i) {
if (!('' + i in this)) {
Object.defineProperty(this, '' + i, {
get: function get() {
return this.cues_[i];
}
});
}
};
if (oldLength < l) {
i = oldLength;
for (; i < l; i++) {
defineProp.call(this, i);
}
}
};
TextTrackCueList.prototype.getCueById = function (id) {
var result = null;
for (var i = 0, l = this.length; i < l; i++) {
var cue = this[i];
if (cue.id === id) {
result = cue;
break;
}
}
return result;
};
exports['default'] = TextTrackCueList;
module.exports = exports['default'];
},{"../lib":46,"global/document":1}],65:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../component');
var _Component3 = _interopRequireWildcard(_Component2);
var _Menu = _dereq_('../menu/menu.js');
var _Menu2 = _interopRequireWildcard(_Menu);
var _MenuItem = _dereq_('../menu/menu-item.js');
var _MenuItem2 = _interopRequireWildcard(_MenuItem);
var _MenuButton = _dereq_('../menu/menu-button.js');
var _MenuButton2 = _interopRequireWildcard(_MenuButton);
var _import = _dereq_('../lib.js');
var Lib = _interopRequireWildcard(_import);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
var darkGray = '#222';
var lightGray = '#ccc';
var fontMap = {
monospace: 'monospace',
sansSerif: 'sans-serif',
serif: 'serif',
monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
monospaceSerif: '"Courier New", monospace',
proportionalSansSerif: 'sans-serif',
proportionalSerif: 'serif',
casual: '"Comic Sans MS", Impact, fantasy',
script: '"Monotype Corsiva", cursive',
smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
};
/**
* The component for displaying text track cues
*
* @constructor
*/
var TextTrackDisplay = (function (_Component) {
function TextTrackDisplay(player, options, ready) {
_classCallCheck(this, TextTrackDisplay);
_get(Object.getPrototypeOf(TextTrackDisplay.prototype), 'constructor', this).call(this, player, options, ready);
player.on('loadstart', Lib.bind(this, this.toggleDisplay));
// This used to be called during player init, but was causing an error
// if a track should show by default and the display hadn't loaded yet.
// Should probably be moved to an external track loader when we support
// tracks that don't need a display.
player.ready(Lib.bind(this, function () {
if (player.tech && player.tech.featuresNativeTextTracks) {
this.hide();
return;
}
player.on('fullscreenchange', Lib.bind(this, this.updateDisplay));
var tracks = player.options_.tracks || [];
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
this.player_.addRemoteTextTrack(track);
}
}));
}
_inherits(TextTrackDisplay, _Component);
_createClass(TextTrackDisplay, [{
key: 'toggleDisplay',
value: function toggleDisplay() {
if (this.player_.tech && this.player_.tech.featuresNativeTextTracks) {
this.hide();
} else {
this.show();
}
}
}, {
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(TextTrackDisplay.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-text-track-display'
});
}
}, {
key: 'clearDisplay',
value: function clearDisplay() {
if (typeof _window2['default'].WebVTT === 'function') {
_window2['default'].WebVTT.processCues(_window2['default'], [], this.el_);
}
}
}, {
key: 'updateDisplay',
value: function updateDisplay() {
var tracks = this.player_.textTracks();
this.clearDisplay();
if (!tracks) {
return;
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
if (track.mode === 'showing') {
this.updateForTrack(track);
}
}
}
}, {
key: 'updateForTrack',
value: function updateForTrack(track) {
if (typeof _window2['default'].WebVTT !== 'function' || !track.activeCues) {
return;
}
var overrides = this.player_.textTrackSettings.getValues();
var cues = [];
for (var _i = 0; _i < track.activeCues.length; _i++) {
cues.push(track.activeCues[_i]);
}
_window2['default'].WebVTT.processCues(_window2['default'], track.activeCues, this.el_);
var i = cues.length;
while (i--) {
var cueDiv = cues[i].displayState;
if (overrides.color) {
cueDiv.firstChild.style.color = overrides.color;
}
if (overrides.textOpacity) {
tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
}
if (overrides.backgroundColor) {
cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
}
if (overrides.backgroundOpacity) {
tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
}
if (overrides.windowColor) {
if (overrides.windowOpacity) {
tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
} else {
cueDiv.style.backgroundColor = overrides.windowColor;
}
}
if (overrides.edgeStyle) {
if (overrides.edgeStyle === 'dropshadow') {
cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray;
} else if (overrides.edgeStyle === 'raised') {
cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray;
} else if (overrides.edgeStyle === 'depressed') {
cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray;
} else if (overrides.edgeStyle === 'uniform') {
cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray;
}
}
if (overrides.fontPercent && overrides.fontPercent !== 1) {
var fontSize = _window2['default'].parseFloat(cueDiv.style.fontSize);
cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
cueDiv.style.height = 'auto';
cueDiv.style.top = 'auto';
cueDiv.style.bottom = '2px';
}
if (overrides.fontFamily && overrides.fontFamily !== 'default') {
if (overrides.fontFamily === 'small-caps') {
cueDiv.firstChild.style.fontVariant = 'small-caps';
} else {
cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
}
}
}
}
}]);
return TextTrackDisplay;
})(_Component3['default']);
// Add cue HTML to display
function constructColor(color, opacity) {
return 'rgba(' +
// color looks like "#f0e"
parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')';
}
function tryUpdateStyle(el, style, rule) {
// some style changes will throw an error, particularly in IE8. Those should be noops.
try {
el.style[style] = rule;
} catch (e) {}
}
_Component3['default'].registerComponent('TextTrackDisplay', TextTrackDisplay);
exports['default'] = TextTrackDisplay;
module.exports = exports['default'];
},{"../component":7,"../lib.js":46,"../menu/menu-button.js":49,"../menu/menu-item.js":50,"../menu/menu.js":51,"global/document":1,"global/window":2}],66:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
*
* enum TextTrackMode { "disabled", "hidden", "showing" };
*/
var TextTrackMode = {
disabled: 'disabled',
hidden: 'hidden',
showing: 'showing'
};
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackkind
*
* enum TextTrackKind { "subtitles", "captions", "descriptions", "chapters", "metadata" };
*/
var TextTrackKind = {
subtitles: 'subtitles',
captions: 'captions',
descriptions: 'descriptions',
chapters: 'chapters',
metadata: 'metadata'
};
exports.TextTrackMode = TextTrackMode;
exports.TextTrackKind = TextTrackKind;
},{}],67:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _EventEmitter = _dereq_('../event-emitter');
var _EventEmitter2 = _interopRequireWildcard(_EventEmitter);
var _import = _dereq_('../lib');
var Lib = _interopRequireWildcard(_import);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist
*
* interface TextTrackList : EventTarget {
* readonly attribute unsigned long length;
* getter TextTrack (unsigned long index);
* TextTrack? getTrackById(DOMString id);
*
* attribute EventHandler onchange;
* attribute EventHandler onaddtrack;
* attribute EventHandler onremovetrack;
* };
*/
var TextTrackList = (function (_TextTrackList) {
function TextTrackList(_x) {
return _TextTrackList.apply(this, arguments);
}
TextTrackList.toString = function () {
return TextTrackList.toString();
};
return TextTrackList;
})(function (tracks) {
var list = this;
if (Lib.IS_IE8) {
list = _document2['default'].createElement('custom');
for (var prop in TextTrackList.prototype) {
list[prop] = TextTrackList.prototype[prop];
}
}
tracks = tracks || [];
list.tracks_ = [];
Object.defineProperty(list, 'length', {
get: function get() {
return this.tracks_.length;
}
});
for (var i = 0; i < tracks.length; i++) {
list.addTrack_(tracks[i]);
}
if (Lib.IS_IE8) {
return list;
}
});
TextTrackList.prototype = Lib.obj.create(_EventEmitter2['default'].prototype);
TextTrackList.prototype.constructor = TextTrackList;
/*
* change - One or more tracks in the track list have been enabled or disabled.
* addtrack - A track has been added to the track list.
* removetrack - A track has been removed from the track list.
*/
TextTrackList.prototype.allowedEvents_ = {
change: 'change',
addtrack: 'addtrack',
removetrack: 'removetrack'
};
// emulate attribute EventHandler support to allow for feature detection
for (var _event in TextTrackList.prototype.allowedEvents_) {
TextTrackList.prototype['on' + _event] = null;
}
TextTrackList.prototype.addTrack_ = function (track) {
var index = this.tracks_.length;
if (!('' + index in this)) {
Object.defineProperty(this, index, {
get: function get() {
return this.tracks_[index];
}
});
}
track.addEventListener('modechange', Lib.bind(this, function () {
this.trigger('change');
}));
this.tracks_.push(track);
this.trigger({
type: 'addtrack',
track: track
});
};
TextTrackList.prototype.removeTrack_ = function (rtrack) {
var result = null;
var track = undefined;
for (var i = 0, l = this.length; i < l; i++) {
track = this[i];
if (track === rtrack) {
this.tracks_.splice(i, 1);
break;
}
}
this.trigger({
type: 'removetrack',
track: track
});
};
TextTrackList.prototype.getTrackById = function (id) {
var result = null;
for (var i = 0, l = this.length; i < l; i++) {
var track = this[i];
if (track.id === id) {
result = track;
break;
}
}
return result;
};
exports['default'] = TextTrackList;
module.exports = exports['default'];
},{"../event-emitter":42,"../lib":46,"global/document":1}],68:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (descriptor.value) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _Component2 = _dereq_('../component');
var _Component3 = _interopRequireWildcard(_Component2);
var _import = _dereq_('../lib');
var Lib = _interopRequireWildcard(_import);
var _import2 = _dereq_('../events');
var Events = _interopRequireWildcard(_import2);
var _safeParseTuple = _dereq_('safe-json-parse/tuple');
var _safeParseTuple2 = _interopRequireWildcard(_safeParseTuple);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
var TextTrackSettings = (function (_Component) {
function TextTrackSettings(player, options) {
_classCallCheck(this, TextTrackSettings);
_get(Object.getPrototypeOf(TextTrackSettings.prototype), 'constructor', this).call(this, player, options);
this.hide();
Events.on(this.el().querySelector('.vjs-done-button'), 'click', Lib.bind(this, function () {
this.saveSettings();
this.hide();
}));
Events.on(this.el().querySelector('.vjs-default-button'), 'click', Lib.bind(this, function () {
this.el().querySelector('.vjs-fg-color > select').selectedIndex = 0;
this.el().querySelector('.vjs-bg-color > select').selectedIndex = 0;
this.el().querySelector('.window-color > select').selectedIndex = 0;
this.el().querySelector('.vjs-text-opacity > select').selectedIndex = 0;
this.el().querySelector('.vjs-bg-opacity > select').selectedIndex = 0;
this.el().querySelector('.vjs-window-opacity > select').selectedIndex = 0;
this.el().querySelector('.vjs-edge-style select').selectedIndex = 0;
this.el().querySelector('.vjs-font-family select').selectedIndex = 0;
this.el().querySelector('.vjs-font-percent select').selectedIndex = 2;
this.updateDisplay();
}));
Events.on(this.el().querySelector('.vjs-fg-color > select'), 'change', Lib.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-bg-color > select'), 'change', Lib.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.window-color > select'), 'change', Lib.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-text-opacity > select'), 'change', Lib.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-bg-opacity > select'), 'change', Lib.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-window-opacity > select'), 'change', Lib.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-font-percent select'), 'change', Lib.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-edge-style select'), 'change', Lib.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-font-family select'), 'change', Lib.bind(this, this.updateDisplay));
if (player.options().persistTextTrackSettings) {
this.restoreSettings();
}
}
_inherits(TextTrackSettings, _Component);
_createClass(TextTrackSettings, [{
key: 'createEl',
value: function createEl() {
return _get(Object.getPrototypeOf(TextTrackSettings.prototype), 'createEl', this).call(this, 'div', {
className: 'vjs-caption-settings vjs-modal-overlay',
innerHTML: captionOptionsMenuTemplate()
});
}
}, {
key: 'getValues',
value: function getValues() {
var el = this.el();
var textEdge = getSelectedOptionValue(el.querySelector('.vjs-edge-style select'));
var fontFamily = getSelectedOptionValue(el.querySelector('.vjs-font-family select'));
var fgColor = getSelectedOptionValue(el.querySelector('.vjs-fg-color > select'));
var textOpacity = getSelectedOptionValue(el.querySelector('.vjs-text-opacity > select'));
var bgColor = getSelectedOptionValue(el.querySelector('.vjs-bg-color > select'));
var bgOpacity = getSelectedOptionValue(el.querySelector('.vjs-bg-opacity > select'));
var windowColor = getSelectedOptionValue(el.querySelector('.window-color > select'));
var windowOpacity = getSelectedOptionValue(el.querySelector('.vjs-window-opacity > select'));
var fontPercent = _window2['default'].parseFloat(getSelectedOptionValue(el.querySelector('.vjs-font-percent > select')));
var result = {
backgroundOpacity: bgOpacity,
textOpacity: textOpacity,
windowOpacity: windowOpacity,
edgeStyle: textEdge,
fontFamily: fontFamily,
color: fgColor,
backgroundColor: bgColor,
windowColor: windowColor,
fontPercent: fontPercent
};
for (var _name in result) {
if (result[_name] === '' || result[_name] === 'none' || _name === 'fontPercent' && result[_name] === 1) {
delete result[_name];
}
}
return result;
}
}, {
key: 'setValues',
value: function setValues(values) {
var el = this.el();
setSelectedOption(el.querySelector('.vjs-edge-style select'), values.edgeStyle);
setSelectedOption(el.querySelector('.vjs-font-family select'), values.fontFamily);
setSelectedOption(el.querySelector('.vjs-fg-color > select'), values.color);
setSelectedOption(el.querySelector('.vjs-text-opacity > select'), values.textOpacity);
setSelectedOption(el.querySelector('.vjs-bg-color > select'), values.backgroundColor);
setSelectedOption(el.querySelector('.vjs-bg-opacity > select'), values.backgroundOpacity);
setSelectedOption(el.querySelector('.window-color > select'), values.windowColor);
setSelectedOption(el.querySelector('.vjs-window-opacity > select'), values.windowOpacity);
var fontPercent = values.fontPercent;
if (fontPercent) {
fontPercent = fontPercent.toFixed(2);
}
setSelectedOption(el.querySelector('.vjs-font-percent > select'), fontPercent);
}
}, {
key: 'restoreSettings',
value: function restoreSettings() {
var values = undefined;
try {
values = _safeParseTuple2['default'](_window2['default'].localStorage.getItem('vjs-text-track-settings'))[1];
} catch (e) {}
if (values) {
this.setValues(values);
}
}
}, {
key: 'saveSettings',
value: function saveSettings() {
if (!this.player_.options().persistTextTrackSettings) {
return;
}
var values = this.getValues();
try {
if (!Lib.isEmpty(values)) {
_window2['default'].localStorage.setItem('vjs-text-track-settings', JSON.stringify(values));
} else {
_window2['default'].localStorage.removeItem('vjs-text-track-settings');
}
} catch (e) {}
}
}, {
key: 'updateDisplay',
value: function updateDisplay() {
var ttDisplay = this.player_.getChild('textTrackDisplay');
if (ttDisplay) {
ttDisplay.updateDisplay();
}
}
}]);
return TextTrackSettings;
})(_Component3['default']);
_Component3['default'].registerComponent('TextTrackSettings', TextTrackSettings);
function getSelectedOptionValue(target) {
var selectedOption = undefined;
// not all browsers support selectedOptions, so, fallback to options
if (target.selectedOptions) {
selectedOption = target.selectedOptions[0];
} else if (target.options) {
selectedOption = target.options[target.options.selectedIndex];
}
return selectedOption.value;
}
function setSelectedOption(target, value) {
if (!value) {
return;
}
var i = undefined;
for (i = 0; i < target.options.length; i++) {
var option = target.options[i];
if (option.value === value) {
break;
}
}
target.selectedIndex = i;
}
function captionOptionsMenuTemplate() {
var template = '<div class="vjs-tracksettings">\n <div class="vjs-tracksettings-colors">\n <div class="vjs-fg-color vjs-tracksetting">\n <label class="vjs-label">Foreground</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-text-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Opaque</option>\n </select>\n </span>\n </div> <!-- vjs-fg-color -->\n <div class="vjs-bg-color vjs-tracksetting">\n <label class="vjs-label">Background</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-bg-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-bg-color -->\n <div class="window-color vjs-tracksetting">\n <label class="vjs-label">Window</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-window-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-window-color -->\n </div> <!-- vjs-tracksettings -->\n <div class="vjs-tracksettings-font">\n <div class="vjs-font-percent vjs-tracksetting">\n <label class="vjs-label">Font Size</label>\n <select>\n <option value="0.50">50%</option>\n <option value="0.75">75%</option>\n <option value="1.00" selected>100%</option>\n <option value="1.25">125%</option>\n <option value="1.50">150%</option>\n <option value="1.75">175%</option>\n <option value="2.00">200%</option>\n <option value="3.00">300%</option>\n <option value="4.00">400%</option>\n </select>\n </div> <!-- vjs-font-percent -->\n <div class="vjs-edge-style vjs-tracksetting">\n <label class="vjs-label">Text Edge Style</label>\n <select>\n <option value="none">None</option>\n <option value="raised">Raised</option>\n <option value="depressed">Depressed</option>\n <option value="uniform">Uniform</option>\n <option value="dropshadow">Dropshadow</option>\n </select>\n </div> <!-- vjs-edge-style -->\n <div class="vjs-font-family vjs-tracksetting">\n <label class="vjs-label">Font Family</label>\n <select>\n <option value="">Default</option>\n <option value="monospaceSerif">Monospace Serif</option>\n <option value="proportionalSerif">Proportional Serif</option>\n <option value="monospaceSansSerif">Monospace Sans-Serif</option>\n <option value="proportionalSansSerif">Proportional Sans-Serif</option>\n <option value="casual">Casual</option>\n <option value="script">Script</option>\n <option value="small-caps">Small Caps</option>\n </select>\n </div> <!-- vjs-font-family -->\n </div>\n </div>\n <div class="vjs-tracksettings-controls">\n <button class="vjs-default-button">Defaults</button>\n <button class="vjs-done-button">Done</button>\n </div>';
return template;
}
exports['default'] = TextTrackSettings;
module.exports = exports['default'];
},{"../component":7,"../events":43,"../lib":46,"global/window":2,"safe-json-parse/tuple":4}],69:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _TextTrackCueList = _dereq_('./text-track-cue-list');
var _TextTrackCueList2 = _interopRequireWildcard(_TextTrackCueList);
var _import = _dereq_('../lib');
var Lib = _interopRequireWildcard(_import);
var _import2 = _dereq_('./text-track-enums');
var TextTrackEnum = _interopRequireWildcard(_import2);
var _EventEmitter = _dereq_('../event-emitter');
var _EventEmitter2 = _interopRequireWildcard(_EventEmitter);
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
var _XHR = _dereq_('../xhr.js');
var _XHR2 = _interopRequireWildcard(_XHR);
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack
*
* interface TextTrack : EventTarget {
* readonly attribute TextTrackKind kind;
* readonly attribute DOMString label;
* readonly attribute DOMString language;
*
* readonly attribute DOMString id;
* readonly attribute DOMString inBandMetadataTrackDispatchType;
*
* attribute TextTrackMode mode;
*
* readonly attribute TextTrackCueList? cues;
* readonly attribute TextTrackCueList? activeCues;
*
* void addCue(TextTrackCue cue);
* void removeCue(TextTrackCue cue);
*
* attribute EventHandler oncuechange;
* };
*/
var TextTrack = (function (_TextTrack) {
function TextTrack() {
return _TextTrack.apply(this, arguments);
}
TextTrack.toString = function () {
return TextTrack.toString();
};
return TextTrack;
})(function () {
var options = arguments[0] === undefined ? {} : arguments[0];
if (!options.player) {
throw new Error('A player was not provided.');
}
var tt = this;
if (Lib.IS_IE8) {
tt = _document2['default'].createElement('custom');
for (var prop in TextTrack.prototype) {
tt[prop] = TextTrack.prototype[prop];
}
}
tt.player_ = options.player;
var mode = TextTrackEnum.TextTrackMode[options.mode] || 'disabled';
var kind = TextTrackEnum.TextTrackKind[options.kind] || 'subtitles';
var label = options.label || '';
var language = options.language || options.srclang || '';
var id = options.id || 'vjs_text_track_' + Lib.guid++;
if (kind === 'metadata' || kind === 'chapters') {
mode = 'hidden';
}
tt.cues_ = [];
tt.activeCues_ = [];
var cues = new _TextTrackCueList2['default'](tt.cues_);
var activeCues = new _TextTrackCueList2['default'](tt.activeCues_);
var changed = false;
var timeupdateHandler = Lib.bind(tt, function () {
this.activeCues;
if (changed) {
this.trigger('cuechange');
changed = false;
}
});
if (mode !== 'disabled') {
tt.player_.on('timeupdate', timeupdateHandler);
}
Object.defineProperty(tt, 'kind', {
get: function get() {
return kind;
},
set: Function.prototype
});
Object.defineProperty(tt, 'label', {
get: function get() {
return label;
},
set: Function.prototype
});
Object.defineProperty(tt, 'language', {
get: function get() {
return language;
},
set: Function.prototype
});
Object.defineProperty(tt, 'id', {
get: function get() {
return id;
},
set: Function.prototype
});
Object.defineProperty(tt, 'mode', {
get: function get() {
return mode;
},
set: function set(newMode) {
if (!TextTrackEnum.TextTrackMode[newMode]) {
return;
}
mode = newMode;
if (mode === 'showing') {
this.player_.on('timeupdate', timeupdateHandler);
}
this.trigger('modechange');
}
});
Object.defineProperty(tt, 'cues', {
get: function get() {
if (!this.loaded_) {
return null;
}
return cues;
},
set: Function.prototype
});
Object.defineProperty(tt, 'activeCues', {
get: function get() {
if (!this.loaded_) {
return null;
}
if (this.cues.length === 0) {
return activeCues; // nothing to do
}
var ct = this.player_.currentTime();
var active = [];
for (var i = 0, l = this.cues.length; i < l; i++) {
var cue = this.cues[i];
if (cue.startTime <= ct && cue.endTime >= ct) {
active.push(cue);
} else if (cue.startTime === cue.endTime && cue.startTime <= ct && cue.startTime + 0.5 >= ct) {
active.push(cue);
}
}
changed = false;
if (active.length !== this.activeCues_.length) {
changed = true;
} else {
for (var i = 0; i < active.length; i++) {
if (indexOf.call(this.activeCues_, active[i]) === -1) {
changed = true;
}
}
}
this.activeCues_ = active;
activeCues.setCues_(this.activeCues_);
return activeCues;
},
set: Function.prototype
});
if (options.src) {
loadTrack(options.src, tt);
} else {
tt.loaded_ = true;
}
if (Lib.IS_IE8) {
return tt;
}
});
TextTrack.prototype = Lib.obj.create(_EventEmitter2['default'].prototype);
TextTrack.prototype.constructor = TextTrack;
/*
* cuechange - One or more cues in the track have become active or stopped being active.
*/
TextTrack.prototype.allowedEvents_ = {
cuechange: 'cuechange'
};
TextTrack.prototype.addCue = function (cue) {
var tracks = this.player_.textTracks();
if (tracks) {
for (var i = 0; i < tracks.length; i++) {
if (tracks[i] !== this) {
tracks[i].removeCue(cue);
}
}
}
this.cues_.push(cue);
this.cues.setCues_(this.cues_);
};
TextTrack.prototype.removeCue = function (removeCue) {
var removed = false;
for (var i = 0, l = this.cues_.length; i < l; i++) {
var cue = this.cues_[i];
if (cue === removeCue) {
this.cues_.splice(i, 1);
removed = true;
}
}
if (removed) {
this.cues.setCues_(this.cues_);
}
};
/*
* Downloading stuff happens below this point
*/
var parseCues = (function (_parseCues) {
function parseCues(_x, _x2) {
return _parseCues.apply(this, arguments);
}
parseCues.toString = function () {
return parseCues.toString();
};
return parseCues;
})(function (srcContent, track) {
if (typeof _window2['default'].WebVTT !== 'function') {
//try again a bit later
return _window2['default'].setTimeout(function () {
parseCues(srcContent, track);
}, 25);
}
var parser = new _window2['default'].WebVTT.Parser(_window2['default'], _window2['default'].vttjs, _window2['default'].WebVTT.StringDecoder());
parser.oncue = function (cue) {
track.addCue(cue);
};
parser.onparsingerror = function (error) {
Lib.log.error(error);
};
parser.parse(srcContent);
parser.flush();
});
var loadTrack = function loadTrack(src, track) {
_XHR2['default'](src, Lib.bind(this, function (err, response, responseBody) {
if (err) {
return Lib.log.error(err);
}
track.loaded_ = true;
parseCues(responseBody, track);
}));
};
var indexOf = function indexOf(searchElement, fromIndex) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
exports['default'] = TextTrack;
module.exports = exports['default'];
},{"../event-emitter":42,"../lib":46,"../xhr.js":72,"./text-track-cue-list":64,"./text-track-enums":66,"global/document":1,"global/window":2}],70:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _obj = _dereq_('./lib');
/**
* Utility functions namespace
* @namespace
* @type {Object}
*/
var util = {};
/**
* Merge two options objects, recursively merging any plain object properties as
* well. Previously `deepMerge`
*
* @param {Object} obj1 Object to override values in
* @param {Object} obj2 Overriding object
* @return {Object} New object -- obj1 and obj2 will be untouched
*/
var mergeOptions = (function (_mergeOptions) {
function mergeOptions(_x, _x2) {
return _mergeOptions.apply(this, arguments);
}
mergeOptions.toString = function () {
return mergeOptions.toString();
};
return mergeOptions;
})(function (obj1, obj2) {
var key, val1, val2;
// make a copy of obj1 so we're not overwriting original values.
// like prototype.options_ and all sub options objects
obj1 = _obj.obj.copy(obj1);
for (key in obj2) {
if (obj2.hasOwnProperty(key)) {
val1 = obj1[key];
val2 = obj2[key];
// Check if both properties are pure objects and do a deep merge if so
if (_obj.obj.isPlain(val1) && _obj.obj.isPlain(val2)) {
obj1[key] = mergeOptions(val1, val2);
} else {
obj1[key] = obj2[key];
}
}
}
return obj1;
});
exports.mergeOptions = mergeOptions;
},{"./lib":46}],71:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _document = _dereq_('global/document');
var _document2 = _interopRequireWildcard(_document);
var _MediaLoader = _dereq_('./tech/loader.js');
var _MediaLoader2 = _interopRequireWildcard(_MediaLoader);
var _Html5 = _dereq_('./tech/html5.js');
var _Html52 = _interopRequireWildcard(_Html5);
var _Flash = _dereq_('./tech/flash.js');
var _Flash2 = _interopRequireWildcard(_Flash);
var _PosterImage = _dereq_('./poster-image.js');
var _PosterImage2 = _interopRequireWildcard(_PosterImage);
var _TextTrackDisplay = _dereq_('./tracks/text-track-display.js');
var _TextTrackDisplay2 = _interopRequireWildcard(_TextTrackDisplay);
var _LoadingSpinner = _dereq_('./loading-spinner.js');
var _LoadingSpinner2 = _interopRequireWildcard(_LoadingSpinner);
var _BigPlayButton = _dereq_('./big-play-button.js');
var _BigPlayButton2 = _interopRequireWildcard(_BigPlayButton);
var _ControlBar = _dereq_('./control-bar/control-bar.js');
var _ControlBar2 = _interopRequireWildcard(_ControlBar);
var _ErrorDisplay = _dereq_('./error-display.js');
var _ErrorDisplay2 = _interopRequireWildcard(_ErrorDisplay);
var _videojs = _dereq_('./core');
var _videojs2 = _interopRequireWildcard(_videojs);
var _import = _dereq_('./setup');
var setup = _interopRequireWildcard(_import);
var _Component = _dereq_('./component');
var _Component2 = _interopRequireWildcard(_Component);
var _import2 = _dereq_('./lib');
var Lib = _interopRequireWildcard(_import2);
var _import3 = _dereq_('./util.js');
var Util = _interopRequireWildcard(_import3);
var _Player = _dereq_('./player');
var _Player2 = _interopRequireWildcard(_Player);
var _extendsFn = _dereq_('./extends.js');
var _extendsFn2 = _interopRequireWildcard(_extendsFn);
if (typeof HTMLVideoElement === 'undefined') {
_document2['default'].createElement('video');
_document2['default'].createElement('audio');
_document2['default'].createElement('track');
}
// Run Auto-load players
// You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version)
setup.autoSetupTimeout(1, _videojs2['default']);
_videojs2['default'].getComponent = _Component2['default'].getComponent;
_videojs2['default'].registerComponent = _Component2['default'].registerComponent;
// APIs that will be removed with 5.0, but need them to get tests passing
// in ES6 transition
_videojs2['default'].TOUCH_ENABLED = Lib.TOUCH_ENABLED;
_videojs2['default'].util = Util;
// Probably want to keep this one for 5.0?
_videojs2['default'].players = _Player2['default'].players;
_videojs2['default']['extends'] = _extendsFn2['default'];
// REMOVING: We probably should not include this in 5.0 thought it would make it
// more backwards compatible
// // Expose but deprecate the window[componentName] method for accessing components
// Lib.obj.each(Component.components, function(name, component){
// // A deprecation warning as the constuctor
// module.exports[name] = function(player, options, ready){
// Lib.log.warn('Using videojs.'+name+' to access the '+name+' component has been deprecated. Please use videojs.getComponent("componentName")');
//
// return new Component(player, options, ready);
// };
//
// // Allow the prototype and class methods to be accessible still this way
// // Though anything that attempts to override class methods will no longer work
// Lib.obj.merge(module.exports[name], component);
// });
exports['default'] = _videojs2['default'];
module.exports = exports['default'];
},{"./big-play-button.js":5,"./component":7,"./control-bar/control-bar.js":8,"./core":40,"./error-display.js":41,"./extends.js":44,"./lib":46,"./loading-spinner.js":47,"./player":53,"./poster-image.js":55,"./setup":56,"./tech/flash.js":60,"./tech/html5.js":61,"./tech/loader.js":62,"./tracks/text-track-display.js":65,"./util.js":70,"global/document":1}],72:[function(_dereq_,module,exports){
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _import = _dereq_('./util');
var VjsUtils = _interopRequireWildcard(_import);
var _import2 = _dereq_('./lib');
var Lib = _interopRequireWildcard(_import2);
var _window = _dereq_('global/window');
var _window2 = _interopRequireWildcard(_window);
/**
* Simple http request for retrieving external files (e.g. text tracks)
*
* ##### Example
*
* // using url string
* videojs.xhr('http://example.com/myfile.vtt', function(error, response, responseBody){});
*
* // or options block
* videojs.xhr({
* uri: 'http://example.com/myfile.vtt',
* method: 'GET',
* responseType: 'text'
* }, function(error, response, responseBody){
* if (error) {
* // log the error
* } else {
* // successful, do something with the response
* }
* });
*
*
* API is modeled after the Raynos/xhr, which we hope to use after
* getting browserify implemented.
* https://github.com/Raynos/xhr/blob/master/index.js
*
* @param {Object|String} options Options block or URL string
* @param {Function} callback The callback function
* @returns {Object} The request
*/
var xhr = function xhr(options, callback) {
var abortTimeout = undefined;
// If options is a string it's the url
if (typeof options === 'string') {
options = {
uri: options
};
}
// Merge with default options
VjsUtils.mergeOptions({
method: 'GET',
timeout: 45 * 1000
}, options);
callback = callback || function () {};
var XHR = _window2['default'].XMLHttpRequest;
if (typeof XHR === 'undefined') {
// Shim XMLHttpRequest for older IEs
XHR = function () {
try {
return new _window2['default'].ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch (e) {}
try {
return new _window2['default'].ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch (f) {}
try {
return new _window2['default'].ActiveXObject('Msxml2.XMLHTTP');
} catch (g) {}
throw new Error('This browser does not support XMLHttpRequest.');
};
}
var request = new XHR();
// Store a reference to the url on the request instance
request.uri = options.uri;
var urlInfo = Lib.parseUrl(options.uri);
var winLoc = _window2['default'].location;
var successHandler = function successHandler() {
_window2['default'].clearTimeout(abortTimeout);
callback(null, request, request.response || request.responseText);
};
var errorHandler = function errorHandler(err) {
_window2['default'].clearTimeout(abortTimeout);
if (!err || typeof err === 'string') {
err = new Error(err);
}
callback(err, request);
};
// Check if url is for another domain/origin
// IE8 doesn't know location.origin, so we won't rely on it here
var crossOrigin = urlInfo.protocol + urlInfo.host !== winLoc.protocol + winLoc.host;
// XDomainRequest -- Use for IE if XMLHTTPRequest2 isn't available
// 'withCredentials' is only available in XMLHTTPRequest2
// Also XDomainRequest has a lot of gotchas, so only use if cross domain
if (crossOrigin && _window2['default'].XDomainRequest && !('withCredentials' in request)) {
request = new _window2['default'].XDomainRequest();
request.onload = successHandler;
request.onerror = errorHandler;
// These blank handlers need to be set to fix ie9
// http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/
request.onprogress = function () {};
request.ontimeout = function () {};
// XMLHTTPRequest
} else {
(function () {
var fileUrl = urlInfo.protocol == 'file:' || winLoc.protocol == 'file:';
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.timedout) {
return errorHandler('timeout');
}
if (request.status === 200 || fileUrl && request.status === 0) {
successHandler();
} else {
errorHandler();
}
}
};
if (options.timeout) {
abortTimeout = _window2['default'].setTimeout(function () {
if (request.readyState !== 4) {
request.timedout = true;
request.abort();
}
}, options.timeout);
}
})();
}
// open the connection
try {
// Third arg is async, or ignored by XDomainRequest
request.open(options.method || 'GET', options.uri, true);
} catch (err) {
return errorHandler(err);
}
// withCredentials only supported by XMLHttpRequest2
if (options.withCredentials) {
request.withCredentials = true;
}
if (options.responseType) {
request.responseType = options.responseType;
}
// send the request
try {
request.send();
} catch (err) {
return errorHandler(err);
}
return request;
};
exports['default'] = xhr;
module.exports = exports['default'];
},{"./lib":46,"./util":70,"global/window":2}]},{},[71])(71)
});
/* vtt.js - v0.11.11 (https://github.com/mozilla/vtt.js) built on 22-01-2015 */
(function(root) {
var vttjs = root.vttjs = {};
var cueShim = vttjs.VTTCue;
var regionShim = vttjs.VTTRegion;
var oldVTTCue = root.VTTCue;
var oldVTTRegion = root.VTTRegion;
vttjs.shim = function() {
vttjs.VTTCue = cueShim;
vttjs.VTTRegion = regionShim;
};
vttjs.restore = function() {
vttjs.VTTCue = oldVTTCue;
vttjs.VTTRegion = oldVTTRegion;
};
}(this));
/**
* Copyright 2013 vtt.js Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(root, vttjs) {
var autoKeyword = "auto";
var directionSetting = {
"": true,
"lr": true,
"rl": true
};
var alignSetting = {
"start": true,
"middle": true,
"end": true,
"left": true,
"right": true
};
function findDirectionSetting(value) {
if (typeof value !== "string") {
return false;
}
var dir = directionSetting[value.toLowerCase()];
return dir ? value.toLowerCase() : false;
}
function findAlignSetting(value) {
if (typeof value !== "string") {
return false;
}
var align = alignSetting[value.toLowerCase()];
return align ? value.toLowerCase() : false;
}
function extend(obj) {
var i = 1;
for (; i < arguments.length; i++) {
var cobj = arguments[i];
for (var p in cobj) {
obj[p] = cobj[p];
}
}
return obj;
}
function VTTCue(startTime, endTime, text) {
var cue = this;
var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
var baseObj = {};
if (isIE8) {
cue = document.createElement('custom');
} else {
baseObj.enumerable = true;
}
/**
* Shim implementation specific properties. These properties are not in
* the spec.
*/
// Lets us know when the VTTCue's data has changed in such a way that we need
// to recompute its display state. This lets us compute its display state
// lazily.
cue.hasBeenReset = false;
/**
* VTTCue and TextTrackCue properties
* http://dev.w3.org/html5/webvtt/#vttcue-interface
*/
var _id = "";
var _pauseOnExit = false;
var _startTime = startTime;
var _endTime = endTime;
var _text = text;
var _region = null;
var _vertical = "";
var _snapToLines = true;
var _line = "auto";
var _lineAlign = "start";
var _position = 50;
var _positionAlign = "middle";
var _size = 50;
var _align = "middle";
Object.defineProperty(cue,
"id", extend({}, baseObj, {
get: function() {
return _id;
},
set: function(value) {
_id = "" + value;
}
}));
Object.defineProperty(cue,
"pauseOnExit", extend({}, baseObj, {
get: function() {
return _pauseOnExit;
},
set: function(value) {
_pauseOnExit = !!value;
}
}));
Object.defineProperty(cue,
"startTime", extend({}, baseObj, {
get: function() {
return _startTime;
},
set: function(value) {
if (typeof value !== "number") {
throw new TypeError("Start time must be set to a number.");
}
_startTime = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"endTime", extend({}, baseObj, {
get: function() {
return _endTime;
},
set: function(value) {
if (typeof value !== "number") {
throw new TypeError("End time must be set to a number.");
}
_endTime = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"text", extend({}, baseObj, {
get: function() {
return _text;
},
set: function(value) {
_text = "" + value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"region", extend({}, baseObj, {
get: function() {
return _region;
},
set: function(value) {
_region = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"vertical", extend({}, baseObj, {
get: function() {
return _vertical;
},
set: function(value) {
var setting = findDirectionSetting(value);
// Have to check for false because the setting an be an empty string.
if (setting === false) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_vertical = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"snapToLines", extend({}, baseObj, {
get: function() {
return _snapToLines;
},
set: function(value) {
_snapToLines = !!value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"line", extend({}, baseObj, {
get: function() {
return _line;
},
set: function(value) {
if (typeof value !== "number" && value !== autoKeyword) {
throw new SyntaxError("An invalid number or illegal string was specified.");
}
_line = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"lineAlign", extend({}, baseObj, {
get: function() {
return _lineAlign;
},
set: function(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_lineAlign = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"position", extend({}, baseObj, {
get: function() {
return _position;
},
set: function(value) {
if (value < 0 || value > 100) {
throw new Error("Position must be between 0 and 100.");
}
_position = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"positionAlign", extend({}, baseObj, {
get: function() {
return _positionAlign;
},
set: function(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_positionAlign = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"size", extend({}, baseObj, {
get: function() {
return _size;
},
set: function(value) {
if (value < 0 || value > 100) {
throw new Error("Size must be between 0 and 100.");
}
_size = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"align", extend({}, baseObj, {
get: function() {
return _align;
},
set: function(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_align = setting;
this.hasBeenReset = true;
}
}));
/**
* Other <track> spec defined properties
*/
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
cue.displayState = undefined;
if (isIE8) {
return cue;
}
}
/**
* VTTCue methods
*/
VTTCue.prototype.getCueAsHTML = function() {
// Assume WebVTT.convertCueToDOMTree is on the global.
return WebVTT.convertCueToDOMTree(window, this.text);
};
root.VTTCue = root.VTTCue || VTTCue;
vttjs.VTTCue = VTTCue;
}(this, (this.vttjs || {})));
/**
* Copyright 2013 vtt.js Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(root, vttjs) {
var scrollSetting = {
"": true,
"up": true,
};
function findScrollSetting(value) {
if (typeof value !== "string") {
return false;
}
var scroll = scrollSetting[value.toLowerCase()];
return scroll ? value.toLowerCase() : false;
}
function isValidPercentValue(value) {
return typeof value === "number" && (value >= 0 && value <= 100);
}
// VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface
function VTTRegion() {
var _width = 100;
var _lines = 3;
var _regionAnchorX = 0;
var _regionAnchorY = 100;
var _viewportAnchorX = 0;
var _viewportAnchorY = 100;
var _scroll = "";
Object.defineProperties(this, {
"width": {
enumerable: true,
get: function() {
return _width;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("Width must be between 0 and 100.");
}
_width = value;
}
},
"lines": {
enumerable: true,
get: function() {
return _lines;
},
set: function(value) {
if (typeof value !== "number") {
throw new TypeError("Lines must be set to a number.");
}
_lines = value;
}
},
"regionAnchorY": {
enumerable: true,
get: function() {
return _regionAnchorY;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("RegionAnchorX must be between 0 and 100.");
}
_regionAnchorY = value;
}
},
"regionAnchorX": {
enumerable: true,
get: function() {
return _regionAnchorX;
},
set: function(value) {
if(!isValidPercentValue(value)) {
throw new Error("RegionAnchorY must be between 0 and 100.");
}
_regionAnchorX = value;
}
},
"viewportAnchorY": {
enumerable: true,
get: function() {
return _viewportAnchorY;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("ViewportAnchorY must be between 0 and 100.");
}
_viewportAnchorY = value;
}
},
"viewportAnchorX": {
enumerable: true,
get: function() {
return _viewportAnchorX;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("ViewportAnchorX must be between 0 and 100.");
}
_viewportAnchorX = value;
}
},
"scroll": {
enumerable: true,
get: function() {
return _scroll;
},
set: function(value) {
var setting = findScrollSetting(value);
// Have to check for false as an empty string is a legal value.
if (setting === false) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_scroll = setting;
}
}
});
}
root.VTTRegion = root.VTTRegion || VTTRegion;
vttjs.VTTRegion = VTTRegion;
}(this, (this.vttjs || {})));
/**
* Copyright 2013 vtt.js Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
(function(global) {
var _objCreate = Object.create || (function() {
function F() {}
return function(o) {
if (arguments.length !== 1) {
throw new Error('Object.create shim only accepts one parameter.');
}
F.prototype = o;
return new F();
};
})();
// Creates a new ParserError object from an errorData object. The errorData
// object should have default code and message properties. The default message
// property can be overriden by passing in a message parameter.
// See ParsingError.Errors below for acceptable errors.
function ParsingError(errorData, message) {
this.name = "ParsingError";
this.code = errorData.code;
this.message = message || errorData.message;
}
ParsingError.prototype = _objCreate(Error.prototype);
ParsingError.prototype.constructor = ParsingError;
// ParsingError metadata for acceptable ParsingErrors.
ParsingError.Errors = {
BadSignature: {
code: 0,
message: "Malformed WebVTT signature."
},
BadTimeStamp: {
code: 1,
message: "Malformed time stamp."
}
};
// Try to parse input as a time stamp.
function parseTimeStamp(input) {
function computeSeconds(h, m, s, f) {
return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
}
var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
if (!m) {
return null;
}
if (m[3]) {
// Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
} else if (m[1] > 59) {
// Timestamp takes the form of [hours]:[minutes].[milliseconds]
// First position is hours as it's over 59.
return computeSeconds(m[1], m[2], 0, m[4]);
} else {
// Timestamp takes the form of [minutes]:[seconds].[milliseconds]
return computeSeconds(0, m[1], m[2], m[4]);
}
}
// A settings object holds key/value pairs and will ignore anything but the first
// assignment to a specific key.
function Settings() {
this.values = _objCreate(null);
}
Settings.prototype = {
// Only accept the first assignment to any key.
set: function(k, v) {
if (!this.get(k) && v !== "") {
this.values[k] = v;
}
},
// Return the value for a key, or a default value.
// If 'defaultKey' is passed then 'dflt' is assumed to be an object with
// a number of possible default values as properties where 'defaultKey' is
// the key of the property that will be chosen; otherwise it's assumed to be
// a single value.
get: function(k, dflt, defaultKey) {
if (defaultKey) {
return this.has(k) ? this.values[k] : dflt[defaultKey];
}
return this.has(k) ? this.values[k] : dflt;
},
// Check whether we have a value for a key.
has: function(k) {
return k in this.values;
},
// Accept a setting if its one of the given alternatives.
alt: function(k, v, a) {
for (var n = 0; n < a.length; ++n) {
if (v === a[n]) {
this.set(k, v);
break;
}
}
},
// Accept a setting if its a valid (signed) integer.
integer: function(k, v) {
if (/^-?\d+$/.test(v)) { // integer
this.set(k, parseInt(v, 10));
}
},
// Accept a setting if its a valid percentage.
percent: function(k, v) {
var m;
if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) {
v = parseFloat(v);
if (v >= 0 && v <= 100) {
this.set(k, v);
return true;
}
}
return false;
}
};
// Helper function to parse input into groups separated by 'groupDelim', and
// interprete each group as a key/value pair separated by 'keyValueDelim'.
function parseOptions(input, callback, keyValueDelim, groupDelim) {
var groups = groupDelim ? input.split(groupDelim) : [input];
for (var i in groups) {
if (typeof groups[i] !== "string") {
continue;
}
var kv = groups[i].split(keyValueDelim);
if (kv.length !== 2) {
continue;
}
var k = kv[0];
var v = kv[1];
callback(k, v);
}
}
function parseCue(input, cue, regionList) {
// Remember the original input if we need to throw an error.
var oInput = input;
// 4.1 WebVTT timestamp
function consumeTimeStamp() {
var ts = parseTimeStamp(input);
if (ts === null) {
throw new ParsingError(ParsingError.Errors.BadTimeStamp,
"Malformed timestamp: " + oInput);
}
// Remove time stamp from input.
input = input.replace(/^[^\sa-zA-Z-]+/, "");
return ts;
}
// 4.4.2 WebVTT cue settings
function consumeCueSettings(input, cue) {
var settings = new Settings();
parseOptions(input, function (k, v) {
switch (k) {
case "region":
// Find the last region we parsed with the same region id.
for (var i = regionList.length - 1; i >= 0; i--) {
if (regionList[i].id === v) {
settings.set(k, regionList[i].region);
break;
}
}
break;
case "vertical":
settings.alt(k, v, ["rl", "lr"]);
break;
case "line":
var vals = v.split(","),
vals0 = vals[0];
settings.integer(k, vals0);
settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
settings.alt(k, vals0, ["auto"]);
if (vals.length === 2) {
settings.alt("lineAlign", vals[1], ["start", "middle", "end"]);
}
break;
case "position":
vals = v.split(",");
settings.percent(k, vals[0]);
if (vals.length === 2) {
settings.alt("positionAlign", vals[1], ["start", "middle", "end"]);
}
break;
case "size":
settings.percent(k, v);
break;
case "align":
settings.alt(k, v, ["start", "middle", "end", "left", "right"]);
break;
}
}, /:/, /\s/);
// Apply default values for any missing fields.
cue.region = settings.get("region", null);
cue.vertical = settings.get("vertical", "");
cue.line = settings.get("line", "auto");
cue.lineAlign = settings.get("lineAlign", "start");
cue.snapToLines = settings.get("snapToLines", true);
cue.size = settings.get("size", 100);
cue.align = settings.get("align", "middle");
cue.position = settings.get("position", {
start: 0,
left: 0,
middle: 50,
end: 100,
right: 100
}, cue.align);
cue.positionAlign = settings.get("positionAlign", {
start: "start",
left: "start",
middle: "middle",
end: "end",
right: "end"
}, cue.align);
}
function skipWhitespace() {
input = input.replace(/^\s+/, "");
}
// 4.1 WebVTT cue timings.
skipWhitespace();
cue.startTime = consumeTimeStamp(); // (1) collect cue start time
skipWhitespace();
if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->"
throw new ParsingError(ParsingError.Errors.BadTimeStamp,
"Malformed time stamp (time stamps must be separated by '-->'): " +
oInput);
}
input = input.substr(3);
skipWhitespace();
cue.endTime = consumeTimeStamp(); // (5) collect cue end time
// 4.1 WebVTT cue settings list.
skipWhitespace();
consumeCueSettings(input, cue);
}
var ESCAPE = {
"&": "&",
"<": "<",
">": ">",
"‎": "\u200e",
"‏": "\u200f",
" ": "\u00a0"
};
var TAG_NAME = {
c: "span",
i: "i",
b: "b",
u: "u",
ruby: "ruby",
rt: "rt",
v: "span",
lang: "span"
};
var TAG_ANNOTATION = {
v: "title",
lang: "lang"
};
var NEEDS_PARENT = {
rt: "ruby"
};
// Parse content into a document fragment.
function parseContent(window, input) {
function nextToken() {
// Check for end-of-string.
if (!input) {
return null;
}
// Consume 'n' characters from the input.
function consume(result) {
input = input.substr(result.length);
return result;
}
var m = input.match(/^([^<]*)(<[^>]+>?)?/);
// If there is some text before the next tag, return it, otherwise return
// the tag.
return consume(m[1] ? m[1] : m[2]);
}
// Unescape a string 's'.
function unescape1(e) {
return ESCAPE[e];
}
function unescape(s) {
while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) {
s = s.replace(m[0], unescape1);
}
return s;
}
function shouldAdd(current, element) {
return !NEEDS_PARENT[element.localName] ||
NEEDS_PARENT[element.localName] === current.localName;
}
// Create an element for this tag.
function createElement(type, annotation) {
var tagName = TAG_NAME[type];
if (!tagName) {
return null;
}
var element = window.document.createElement(tagName);
element.localName = tagName;
var name = TAG_ANNOTATION[type];
if (name && annotation) {
element[name] = annotation.trim();
}
return element;
}
var rootDiv = window.document.createElement("div"),
current = rootDiv,
t,
tagStack = [];
while ((t = nextToken()) !== null) {
if (t[0] === '<') {
if (t[1] === "/") {
// If the closing tag matches, move back up to the parent node.
if (tagStack.length &&
tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) {
tagStack.pop();
current = current.parentNode;
}
// Otherwise just ignore the end tag.
continue;
}
var ts = parseTimeStamp(t.substr(1, t.length - 2));
var node;
if (ts) {
// Timestamps are lead nodes as well.
node = window.document.createProcessingInstruction("timestamp", ts);
current.appendChild(node);
continue;
}
var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);
// If we can't parse the tag, skip to the next tag.
if (!m) {
continue;
}
// Try to construct an element, and ignore the tag if we couldn't.
node = createElement(m[1], m[3]);
if (!node) {
continue;
}
// Determine if the tag should be added based on the context of where it
// is placed in the cuetext.
if (!shouldAdd(current, node)) {
continue;
}
// Set the class list (as a list of classes, separated by space).
if (m[2]) {
node.className = m[2].substr(1).replace('.', ' ');
}
// Append the node to the current node, and enter the scope of the new
// node.
tagStack.push(m[1]);
current.appendChild(node);
current = node;
continue;
}
// Text nodes are leaf nodes.
current.appendChild(window.document.createTextNode(unescape(t)));
}
return rootDiv;
}
// This is a list of all the Unicode characters that have a strong
// right-to-left category. What this means is that these characters are
// written right-to-left for sure. It was generated by pulling all the strong
// right-to-left characters out of the Unicode data table. That table can
// found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
var strongRTLChars = [0x05BE, 0x05C0, 0x05C3, 0x05C6, 0x05D0, 0x05D1,
0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA,
0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3,
0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0x05F0, 0x05F1,
0x05F2, 0x05F3, 0x05F4, 0x0608, 0x060B, 0x060D, 0x061B, 0x061E, 0x061F,
0x0620, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, 0x0628,
0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631,
0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, 0x0638, 0x0639, 0x063A,
0x063B, 0x063C, 0x063D, 0x063E, 0x063F, 0x0640, 0x0641, 0x0642, 0x0643,
0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A, 0x066D, 0x066E,
0x066F, 0x0671, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0x0677, 0x0678,
0x0679, 0x067A, 0x067B, 0x067C, 0x067D, 0x067E, 0x067F, 0x0680, 0x0681,
0x0682, 0x0683, 0x0684, 0x0685, 0x0686, 0x0687, 0x0688, 0x0689, 0x068A,
0x068B, 0x068C, 0x068D, 0x068E, 0x068F, 0x0690, 0x0691, 0x0692, 0x0693,
0x0694, 0x0695, 0x0696, 0x0697, 0x0698, 0x0699, 0x069A, 0x069B, 0x069C,
0x069D, 0x069E, 0x069F, 0x06A0, 0x06A1, 0x06A2, 0x06A3, 0x06A4, 0x06A5,
0x06A6, 0x06A7, 0x06A8, 0x06A9, 0x06AA, 0x06AB, 0x06AC, 0x06AD, 0x06AE,
0x06AF, 0x06B0, 0x06B1, 0x06B2, 0x06B3, 0x06B4, 0x06B5, 0x06B6, 0x06B7,
0x06B8, 0x06B9, 0x06BA, 0x06BB, 0x06BC, 0x06BD, 0x06BE, 0x06BF, 0x06C0,
0x06C1, 0x06C2, 0x06C3, 0x06C4, 0x06C5, 0x06C6, 0x06C7, 0x06C8, 0x06C9,
0x06CA, 0x06CB, 0x06CC, 0x06CD, 0x06CE, 0x06CF, 0x06D0, 0x06D1, 0x06D2,
0x06D3, 0x06D4, 0x06D5, 0x06E5, 0x06E6, 0x06EE, 0x06EF, 0x06FA, 0x06FB,
0x06FC, 0x06FD, 0x06FE, 0x06FF, 0x0700, 0x0701, 0x0702, 0x0703, 0x0704,
0x0705, 0x0706, 0x0707, 0x0708, 0x0709, 0x070A, 0x070B, 0x070C, 0x070D,
0x070F, 0x0710, 0x0712, 0x0713, 0x0714, 0x0715, 0x0716, 0x0717, 0x0718,
0x0719, 0x071A, 0x071B, 0x071C, 0x071D, 0x071E, 0x071F, 0x0720, 0x0721,
0x0722, 0x0723, 0x0724, 0x0725, 0x0726, 0x0727, 0x0728, 0x0729, 0x072A,
0x072B, 0x072C, 0x072D, 0x072E, 0x072F, 0x074D, 0x074E, 0x074F, 0x0750,
0x0751, 0x0752, 0x0753, 0x0754, 0x0755, 0x0756, 0x0757, 0x0758, 0x0759,
0x075A, 0x075B, 0x075C, 0x075D, 0x075E, 0x075F, 0x0760, 0x0761, 0x0762,
0x0763, 0x0764, 0x0765, 0x0766, 0x0767, 0x0768, 0x0769, 0x076A, 0x076B,
0x076C, 0x076D, 0x076E, 0x076F, 0x0770, 0x0771, 0x0772, 0x0773, 0x0774,
0x0775, 0x0776, 0x0777, 0x0778, 0x0779, 0x077A, 0x077B, 0x077C, 0x077D,
0x077E, 0x077F, 0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0786,
0x0787, 0x0788, 0x0789, 0x078A, 0x078B, 0x078C, 0x078D, 0x078E, 0x078F,
0x0790, 0x0791, 0x0792, 0x0793, 0x0794, 0x0795, 0x0796, 0x0797, 0x0798,
0x0799, 0x079A, 0x079B, 0x079C, 0x079D, 0x079E, 0x079F, 0x07A0, 0x07A1,
0x07A2, 0x07A3, 0x07A4, 0x07A5, 0x07B1, 0x07C0, 0x07C1, 0x07C2, 0x07C3,
0x07C4, 0x07C5, 0x07C6, 0x07C7, 0x07C8, 0x07C9, 0x07CA, 0x07CB, 0x07CC,
0x07CD, 0x07CE, 0x07CF, 0x07D0, 0x07D1, 0x07D2, 0x07D3, 0x07D4, 0x07D5,
0x07D6, 0x07D7, 0x07D8, 0x07D9, 0x07DA, 0x07DB, 0x07DC, 0x07DD, 0x07DE,
0x07DF, 0x07E0, 0x07E1, 0x07E2, 0x07E3, 0x07E4, 0x07E5, 0x07E6, 0x07E7,
0x07E8, 0x07E9, 0x07EA, 0x07F4, 0x07F5, 0x07FA, 0x0800, 0x0801, 0x0802,
0x0803, 0x0804, 0x0805, 0x0806, 0x0807, 0x0808, 0x0809, 0x080A, 0x080B,
0x080C, 0x080D, 0x080E, 0x080F, 0x0810, 0x0811, 0x0812, 0x0813, 0x0814,
0x0815, 0x081A, 0x0824, 0x0828, 0x0830, 0x0831, 0x0832, 0x0833, 0x0834,
0x0835, 0x0836, 0x0837, 0x0838, 0x0839, 0x083A, 0x083B, 0x083C, 0x083D,
0x083E, 0x0840, 0x0841, 0x0842, 0x0843, 0x0844, 0x0845, 0x0846, 0x0847,
0x0848, 0x0849, 0x084A, 0x084B, 0x084C, 0x084D, 0x084E, 0x084F, 0x0850,
0x0851, 0x0852, 0x0853, 0x0854, 0x0855, 0x0856, 0x0857, 0x0858, 0x085E,
0x08A0, 0x08A2, 0x08A3, 0x08A4, 0x08A5, 0x08A6, 0x08A7, 0x08A8, 0x08A9,
0x08AA, 0x08AB, 0x08AC, 0x200F, 0xFB1D, 0xFB1F, 0xFB20, 0xFB21, 0xFB22,
0xFB23, 0xFB24, 0xFB25, 0xFB26, 0xFB27, 0xFB28, 0xFB2A, 0xFB2B, 0xFB2C,
0xFB2D, 0xFB2E, 0xFB2F, 0xFB30, 0xFB31, 0xFB32, 0xFB33, 0xFB34, 0xFB35,
0xFB36, 0xFB38, 0xFB39, 0xFB3A, 0xFB3B, 0xFB3C, 0xFB3E, 0xFB40, 0xFB41,
0xFB43, 0xFB44, 0xFB46, 0xFB47, 0xFB48, 0xFB49, 0xFB4A, 0xFB4B, 0xFB4C,
0xFB4D, 0xFB4E, 0xFB4F, 0xFB50, 0xFB51, 0xFB52, 0xFB53, 0xFB54, 0xFB55,
0xFB56, 0xFB57, 0xFB58, 0xFB59, 0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D, 0xFB5E,
0xFB5F, 0xFB60, 0xFB61, 0xFB62, 0xFB63, 0xFB64, 0xFB65, 0xFB66, 0xFB67,
0xFB68, 0xFB69, 0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D, 0xFB6E, 0xFB6F, 0xFB70,
0xFB71, 0xFB72, 0xFB73, 0xFB74, 0xFB75, 0xFB76, 0xFB77, 0xFB78, 0xFB79,
0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D, 0xFB7E, 0xFB7F, 0xFB80, 0xFB81, 0xFB82,
0xFB83, 0xFB84, 0xFB85, 0xFB86, 0xFB87, 0xFB88, 0xFB89, 0xFB8A, 0xFB8B,
0xFB8C, 0xFB8D, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91, 0xFB92, 0xFB93, 0xFB94,
0xFB95, 0xFB96, 0xFB97, 0xFB98, 0xFB99, 0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D,
0xFB9E, 0xFB9F, 0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3, 0xFBA4, 0xFBA5, 0xFBA6,
0xFBA7, 0xFBA8, 0xFBA9, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD, 0xFBAE, 0xFBAF,
0xFBB0, 0xFBB1, 0xFBB2, 0xFBB3, 0xFBB4, 0xFBB5, 0xFBB6, 0xFBB7, 0xFBB8,
0xFBB9, 0xFBBA, 0xFBBB, 0xFBBC, 0xFBBD, 0xFBBE, 0xFBBF, 0xFBC0, 0xFBC1,
0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6, 0xFBD7, 0xFBD8, 0xFBD9, 0xFBDA, 0xFBDB,
0xFBDC, 0xFBDD, 0xFBDE, 0xFBDF, 0xFBE0, 0xFBE1, 0xFBE2, 0xFBE3, 0xFBE4,
0xFBE5, 0xFBE6, 0xFBE7, 0xFBE8, 0xFBE9, 0xFBEA, 0xFBEB, 0xFBEC, 0xFBED,
0xFBEE, 0xFBEF, 0xFBF0, 0xFBF1, 0xFBF2, 0xFBF3, 0xFBF4, 0xFBF5, 0xFBF6,
0xFBF7, 0xFBF8, 0xFBF9, 0xFBFA, 0xFBFB, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF,
0xFC00, 0xFC01, 0xFC02, 0xFC03, 0xFC04, 0xFC05, 0xFC06, 0xFC07, 0xFC08,
0xFC09, 0xFC0A, 0xFC0B, 0xFC0C, 0xFC0D, 0xFC0E, 0xFC0F, 0xFC10, 0xFC11,
0xFC12, 0xFC13, 0xFC14, 0xFC15, 0xFC16, 0xFC17, 0xFC18, 0xFC19, 0xFC1A,
0xFC1B, 0xFC1C, 0xFC1D, 0xFC1E, 0xFC1F, 0xFC20, 0xFC21, 0xFC22, 0xFC23,
0xFC24, 0xFC25, 0xFC26, 0xFC27, 0xFC28, 0xFC29, 0xFC2A, 0xFC2B, 0xFC2C,
0xFC2D, 0xFC2E, 0xFC2F, 0xFC30, 0xFC31, 0xFC32, 0xFC33, 0xFC34, 0xFC35,
0xFC36, 0xFC37, 0xFC38, 0xFC39, 0xFC3A, 0xFC3B, 0xFC3C, 0xFC3D, 0xFC3E,
0xFC3F, 0xFC40, 0xFC41, 0xFC42, 0xFC43, 0xFC44, 0xFC45, 0xFC46, 0xFC47,
0xFC48, 0xFC49, 0xFC4A, 0xFC4B, 0xFC4C, 0xFC4D, 0xFC4E, 0xFC4F, 0xFC50,
0xFC51, 0xFC52, 0xFC53, 0xFC54, 0xFC55, 0xFC56, 0xFC57, 0xFC58, 0xFC59,
0xFC5A, 0xFC5B, 0xFC5C, 0xFC5D, 0xFC5E, 0xFC5F, 0xFC60, 0xFC61, 0xFC62,
0xFC63, 0xFC64, 0xFC65, 0xFC66, 0xFC67, 0xFC68, 0xFC69, 0xFC6A, 0xFC6B,
0xFC6C, 0xFC6D, 0xFC6E, 0xFC6F, 0xFC70, 0xFC71, 0xFC72, 0xFC73, 0xFC74,
0xFC75, 0xFC76, 0xFC77, 0xFC78, 0xFC79, 0xFC7A, 0xFC7B, 0xFC7C, 0xFC7D,
0xFC7E, 0xFC7F, 0xFC80, 0xFC81, 0xFC82, 0xFC83, 0xFC84, 0xFC85, 0xFC86,
0xFC87, 0xFC88, 0xFC89, 0xFC8A, 0xFC8B, 0xFC8C, 0xFC8D, 0xFC8E, 0xFC8F,
0xFC90, 0xFC91, 0xFC92, 0xFC93, 0xFC94, 0xFC95, 0xFC96, 0xFC97, 0xFC98,
0xFC99, 0xFC9A, 0xFC9B, 0xFC9C, 0xFC9D, 0xFC9E, 0xFC9F, 0xFCA0, 0xFCA1,
0xFCA2, 0xFCA3, 0xFCA4, 0xFCA5, 0xFCA6, 0xFCA7, 0xFCA8, 0xFCA9, 0xFCAA,
0xFCAB, 0xFCAC, 0xFCAD, 0xFCAE, 0xFCAF, 0xFCB0, 0xFCB1, 0xFCB2, 0xFCB3,
0xFCB4, 0xFCB5, 0xFCB6, 0xFCB7, 0xFCB8, 0xFCB9, 0xFCBA, 0xFCBB, 0xFCBC,
0xFCBD, 0xFCBE, 0xFCBF, 0xFCC0, 0xFCC1, 0xFCC2, 0xFCC3, 0xFCC4, 0xFCC5,
0xFCC6, 0xFCC7, 0xFCC8, 0xFCC9, 0xFCCA, 0xFCCB, 0xFCCC, 0xFCCD, 0xFCCE,
0xFCCF, 0xFCD0, 0xFCD1, 0xFCD2, 0xFCD3, 0xFCD4, 0xFCD5, 0xFCD6, 0xFCD7,
0xFCD8, 0xFCD9, 0xFCDA, 0xFCDB, 0xFCDC, 0xFCDD, 0xFCDE, 0xFCDF, 0xFCE0,
0xFCE1, 0xFCE2, 0xFCE3, 0xFCE4, 0xFCE5, 0xFCE6, 0xFCE7, 0xFCE8, 0xFCE9,
0xFCEA, 0xFCEB, 0xFCEC, 0xFCED, 0xFCEE, 0xFCEF, 0xFCF0, 0xFCF1, 0xFCF2,
0xFCF3, 0xFCF4, 0xFCF5, 0xFCF6, 0xFCF7, 0xFCF8, 0xFCF9, 0xFCFA, 0xFCFB,
0xFCFC, 0xFCFD, 0xFCFE, 0xFCFF, 0xFD00, 0xFD01, 0xFD02, 0xFD03, 0xFD04,
0xFD05, 0xFD06, 0xFD07, 0xFD08, 0xFD09, 0xFD0A, 0xFD0B, 0xFD0C, 0xFD0D,
0xFD0E, 0xFD0F, 0xFD10, 0xFD11, 0xFD12, 0xFD13, 0xFD14, 0xFD15, 0xFD16,
0xFD17, 0xFD18, 0xFD19, 0xFD1A, 0xFD1B, 0xFD1C, 0xFD1D, 0xFD1E, 0xFD1F,
0xFD20, 0xFD21, 0xFD22, 0xFD23, 0xFD24, 0xFD25, 0xFD26, 0xFD27, 0xFD28,
0xFD29, 0xFD2A, 0xFD2B, 0xFD2C, 0xFD2D, 0xFD2E, 0xFD2F, 0xFD30, 0xFD31,
0xFD32, 0xFD33, 0xFD34, 0xFD35, 0xFD36, 0xFD37, 0xFD38, 0xFD39, 0xFD3A,
0xFD3B, 0xFD3C, 0xFD3D, 0xFD50, 0xFD51, 0xFD52, 0xFD53, 0xFD54, 0xFD55,
0xFD56, 0xFD57, 0xFD58, 0xFD59, 0xFD5A, 0xFD5B, 0xFD5C, 0xFD5D, 0xFD5E,
0xFD5F, 0xFD60, 0xFD61, 0xFD62, 0xFD63, 0xFD64, 0xFD65, 0xFD66, 0xFD67,
0xFD68, 0xFD69, 0xFD6A, 0xFD6B, 0xFD6C, 0xFD6D, 0xFD6E, 0xFD6F, 0xFD70,
0xFD71, 0xFD72, 0xFD73, 0xFD74, 0xFD75, 0xFD76, 0xFD77, 0xFD78, 0xFD79,
0xFD7A, 0xFD7B, 0xFD7C, 0xFD7D, 0xFD7E, 0xFD7F, 0xFD80, 0xFD81, 0xFD82,
0xFD83, 0xFD84, 0xFD85, 0xFD86, 0xFD87, 0xFD88, 0xFD89, 0xFD8A, 0xFD8B,
0xFD8C, 0xFD8D, 0xFD8E, 0xFD8F, 0xFD92, 0xFD93, 0xFD94, 0xFD95, 0xFD96,
0xFD97, 0xFD98, 0xFD99, 0xFD9A, 0xFD9B, 0xFD9C, 0xFD9D, 0xFD9E, 0xFD9F,
0xFDA0, 0xFDA1, 0xFDA2, 0xFDA3, 0xFDA4, 0xFDA5, 0xFDA6, 0xFDA7, 0xFDA8,
0xFDA9, 0xFDAA, 0xFDAB, 0xFDAC, 0xFDAD, 0xFDAE, 0xFDAF, 0xFDB0, 0xFDB1,
0xFDB2, 0xFDB3, 0xFDB4, 0xFDB5, 0xFDB6, 0xFDB7, 0xFDB8, 0xFDB9, 0xFDBA,
0xFDBB, 0xFDBC, 0xFDBD, 0xFDBE, 0xFDBF, 0xFDC0, 0xFDC1, 0xFDC2, 0xFDC3,
0xFDC4, 0xFDC5, 0xFDC6, 0xFDC7, 0xFDF0, 0xFDF1, 0xFDF2, 0xFDF3, 0xFDF4,
0xFDF5, 0xFDF6, 0xFDF7, 0xFDF8, 0xFDF9, 0xFDFA, 0xFDFB, 0xFDFC, 0xFE70,
0xFE71, 0xFE72, 0xFE73, 0xFE74, 0xFE76, 0xFE77, 0xFE78, 0xFE79, 0xFE7A,
0xFE7B, 0xFE7C, 0xFE7D, 0xFE7E, 0xFE7F, 0xFE80, 0xFE81, 0xFE82, 0xFE83,
0xFE84, 0xFE85, 0xFE86, 0xFE87, 0xFE88, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C,
0xFE8D, 0xFE8E, 0xFE8F, 0xFE90, 0xFE91, 0xFE92, 0xFE93, 0xFE94, 0xFE95,
0xFE96, 0xFE97, 0xFE98, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C, 0xFE9D, 0xFE9E,
0xFE9F, 0xFEA0, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4, 0xFEA5, 0xFEA6, 0xFEA7,
0xFEA8, 0xFEA9, 0xFEAA, 0xFEAB, 0xFEAC, 0xFEAD, 0xFEAE, 0xFEAF, 0xFEB0,
0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8, 0xFEB9,
0xFEBA, 0xFEBB, 0xFEBC, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0, 0xFEC1, 0xFEC2,
0xFEC3, 0xFEC4, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8, 0xFEC9, 0xFECA, 0xFECB,
0xFECC, 0xFECD, 0xFECE, 0xFECF, 0xFED0, 0xFED1, 0xFED2, 0xFED3, 0xFED4,
0xFED5, 0xFED6, 0xFED7, 0xFED8, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC, 0xFEDD,
0xFEDE, 0xFEDF, 0xFEE0, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4, 0xFEE5, 0xFEE6,
0xFEE7, 0xFEE8, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC, 0xFEED, 0xFEEE, 0xFEEF,
0xFEF0, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4, 0xFEF5, 0xFEF6, 0xFEF7, 0xFEF8,
0xFEF9, 0xFEFA, 0xFEFB, 0xFEFC, 0x10800, 0x10801, 0x10802, 0x10803,
0x10804, 0x10805, 0x10808, 0x1080A, 0x1080B, 0x1080C, 0x1080D, 0x1080E,
0x1080F, 0x10810, 0x10811, 0x10812, 0x10813, 0x10814, 0x10815, 0x10816,
0x10817, 0x10818, 0x10819, 0x1081A, 0x1081B, 0x1081C, 0x1081D, 0x1081E,
0x1081F, 0x10820, 0x10821, 0x10822, 0x10823, 0x10824, 0x10825, 0x10826,
0x10827, 0x10828, 0x10829, 0x1082A, 0x1082B, 0x1082C, 0x1082D, 0x1082E,
0x1082F, 0x10830, 0x10831, 0x10832, 0x10833, 0x10834, 0x10835, 0x10837,
0x10838, 0x1083C, 0x1083F, 0x10840, 0x10841, 0x10842, 0x10843, 0x10844,
0x10845, 0x10846, 0x10847, 0x10848, 0x10849, 0x1084A, 0x1084B, 0x1084C,
0x1084D, 0x1084E, 0x1084F, 0x10850, 0x10851, 0x10852, 0x10853, 0x10854,
0x10855, 0x10857, 0x10858, 0x10859, 0x1085A, 0x1085B, 0x1085C, 0x1085D,
0x1085E, 0x1085F, 0x10900, 0x10901, 0x10902, 0x10903, 0x10904, 0x10905,
0x10906, 0x10907, 0x10908, 0x10909, 0x1090A, 0x1090B, 0x1090C, 0x1090D,
0x1090E, 0x1090F, 0x10910, 0x10911, 0x10912, 0x10913, 0x10914, 0x10915,
0x10916, 0x10917, 0x10918, 0x10919, 0x1091A, 0x1091B, 0x10920, 0x10921,
0x10922, 0x10923, 0x10924, 0x10925, 0x10926, 0x10927, 0x10928, 0x10929,
0x1092A, 0x1092B, 0x1092C, 0x1092D, 0x1092E, 0x1092F, 0x10930, 0x10931,
0x10932, 0x10933, 0x10934, 0x10935, 0x10936, 0x10937, 0x10938, 0x10939,
0x1093F, 0x10980, 0x10981, 0x10982, 0x10983, 0x10984, 0x10985, 0x10986,
0x10987, 0x10988, 0x10989, 0x1098A, 0x1098B, 0x1098C, 0x1098D, 0x1098E,
0x1098F, 0x10990, 0x10991, 0x10992, 0x10993, 0x10994, 0x10995, 0x10996,
0x10997, 0x10998, 0x10999, 0x1099A, 0x1099B, 0x1099C, 0x1099D, 0x1099E,
0x1099F, 0x109A0, 0x109A1, 0x109A2, 0x109A3, 0x109A4, 0x109A5, 0x109A6,
0x109A7, 0x109A8, 0x109A9, 0x109AA, 0x109AB, 0x109AC, 0x109AD, 0x109AE,
0x109AF, 0x109B0, 0x109B1, 0x109B2, 0x109B3, 0x109B4, 0x109B5, 0x109B6,
0x109B7, 0x109BE, 0x109BF, 0x10A00, 0x10A10, 0x10A11, 0x10A12, 0x10A13,
0x10A15, 0x10A16, 0x10A17, 0x10A19, 0x10A1A, 0x10A1B, 0x10A1C, 0x10A1D,
0x10A1E, 0x10A1F, 0x10A20, 0x10A21, 0x10A22, 0x10A23, 0x10A24, 0x10A25,
0x10A26, 0x10A27, 0x10A28, 0x10A29, 0x10A2A, 0x10A2B, 0x10A2C, 0x10A2D,
0x10A2E, 0x10A2F, 0x10A30, 0x10A31, 0x10A32, 0x10A33, 0x10A40, 0x10A41,
0x10A42, 0x10A43, 0x10A44, 0x10A45, 0x10A46, 0x10A47, 0x10A50, 0x10A51,
0x10A52, 0x10A53, 0x10A54, 0x10A55, 0x10A56, 0x10A57, 0x10A58, 0x10A60,
0x10A61, 0x10A62, 0x10A63, 0x10A64, 0x10A65, 0x10A66, 0x10A67, 0x10A68,
0x10A69, 0x10A6A, 0x10A6B, 0x10A6C, 0x10A6D, 0x10A6E, 0x10A6F, 0x10A70,
0x10A71, 0x10A72, 0x10A73, 0x10A74, 0x10A75, 0x10A76, 0x10A77, 0x10A78,
0x10A79, 0x10A7A, 0x10A7B, 0x10A7C, 0x10A7D, 0x10A7E, 0x10A7F, 0x10B00,
0x10B01, 0x10B02, 0x10B03, 0x10B04, 0x10B05, 0x10B06, 0x10B07, 0x10B08,
0x10B09, 0x10B0A, 0x10B0B, 0x10B0C, 0x10B0D, 0x10B0E, 0x10B0F, 0x10B10,
0x10B11, 0x10B12, 0x10B13, 0x10B14, 0x10B15, 0x10B16, 0x10B17, 0x10B18,
0x10B19, 0x10B1A, 0x10B1B, 0x10B1C, 0x10B1D, 0x10B1E, 0x10B1F, 0x10B20,
0x10B21, 0x10B22, 0x10B23, 0x10B24, 0x10B25, 0x10B26, 0x10B27, 0x10B28,
0x10B29, 0x10B2A, 0x10B2B, 0x10B2C, 0x10B2D, 0x10B2E, 0x10B2F, 0x10B30,
0x10B31, 0x10B32, 0x10B33, 0x10B34, 0x10B35, 0x10B40, 0x10B41, 0x10B42,
0x10B43, 0x10B44, 0x10B45, 0x10B46, 0x10B47, 0x10B48, 0x10B49, 0x10B4A,
0x10B4B, 0x10B4C, 0x10B4D, 0x10B4E, 0x10B4F, 0x10B50, 0x10B51, 0x10B52,
0x10B53, 0x10B54, 0x10B55, 0x10B58, 0x10B59, 0x10B5A, 0x10B5B, 0x10B5C,
0x10B5D, 0x10B5E, 0x10B5F, 0x10B60, 0x10B61, 0x10B62, 0x10B63, 0x10B64,
0x10B65, 0x10B66, 0x10B67, 0x10B68, 0x10B69, 0x10B6A, 0x10B6B, 0x10B6C,
0x10B6D, 0x10B6E, 0x10B6F, 0x10B70, 0x10B71, 0x10B72, 0x10B78, 0x10B79,
0x10B7A, 0x10B7B, 0x10B7C, 0x10B7D, 0x10B7E, 0x10B7F, 0x10C00, 0x10C01,
0x10C02, 0x10C03, 0x10C04, 0x10C05, 0x10C06, 0x10C07, 0x10C08, 0x10C09,
0x10C0A, 0x10C0B, 0x10C0C, 0x10C0D, 0x10C0E, 0x10C0F, 0x10C10, 0x10C11,
0x10C12, 0x10C13, 0x10C14, 0x10C15, 0x10C16, 0x10C17, 0x10C18, 0x10C19,
0x10C1A, 0x10C1B, 0x10C1C, 0x10C1D, 0x10C1E, 0x10C1F, 0x10C20, 0x10C21,
0x10C22, 0x10C23, 0x10C24, 0x10C25, 0x10C26, 0x10C27, 0x10C28, 0x10C29,
0x10C2A, 0x10C2B, 0x10C2C, 0x10C2D, 0x10C2E, 0x10C2F, 0x10C30, 0x10C31,
0x10C32, 0x10C33, 0x10C34, 0x10C35, 0x10C36, 0x10C37, 0x10C38, 0x10C39,
0x10C3A, 0x10C3B, 0x10C3C, 0x10C3D, 0x10C3E, 0x10C3F, 0x10C40, 0x10C41,
0x10C42, 0x10C43, 0x10C44, 0x10C45, 0x10C46, 0x10C47, 0x10C48, 0x1EE00,
0x1EE01, 0x1EE02, 0x1EE03, 0x1EE05, 0x1EE06, 0x1EE07, 0x1EE08, 0x1EE09,
0x1EE0A, 0x1EE0B, 0x1EE0C, 0x1EE0D, 0x1EE0E, 0x1EE0F, 0x1EE10, 0x1EE11,
0x1EE12, 0x1EE13, 0x1EE14, 0x1EE15, 0x1EE16, 0x1EE17, 0x1EE18, 0x1EE19,
0x1EE1A, 0x1EE1B, 0x1EE1C, 0x1EE1D, 0x1EE1E, 0x1EE1F, 0x1EE21, 0x1EE22,
0x1EE24, 0x1EE27, 0x1EE29, 0x1EE2A, 0x1EE2B, 0x1EE2C, 0x1EE2D, 0x1EE2E,
0x1EE2F, 0x1EE30, 0x1EE31, 0x1EE32, 0x1EE34, 0x1EE35, 0x1EE36, 0x1EE37,
0x1EE39, 0x1EE3B, 0x1EE42, 0x1EE47, 0x1EE49, 0x1EE4B, 0x1EE4D, 0x1EE4E,
0x1EE4F, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59, 0x1EE5B, 0x1EE5D,
0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE67, 0x1EE68, 0x1EE69, 0x1EE6A,
0x1EE6C, 0x1EE6D, 0x1EE6E, 0x1EE6F, 0x1EE70, 0x1EE71, 0x1EE72, 0x1EE74,
0x1EE75, 0x1EE76, 0x1EE77, 0x1EE79, 0x1EE7A, 0x1EE7B, 0x1EE7C, 0x1EE7E,
0x1EE80, 0x1EE81, 0x1EE82, 0x1EE83, 0x1EE84, 0x1EE85, 0x1EE86, 0x1EE87,
0x1EE88, 0x1EE89, 0x1EE8B, 0x1EE8C, 0x1EE8D, 0x1EE8E, 0x1EE8F, 0x1EE90,
0x1EE91, 0x1EE92, 0x1EE93, 0x1EE94, 0x1EE95, 0x1EE96, 0x1EE97, 0x1EE98,
0x1EE99, 0x1EE9A, 0x1EE9B, 0x1EEA1, 0x1EEA2, 0x1EEA3, 0x1EEA5, 0x1EEA6,
0x1EEA7, 0x1EEA8, 0x1EEA9, 0x1EEAB, 0x1EEAC, 0x1EEAD, 0x1EEAE, 0x1EEAF,
0x1EEB0, 0x1EEB1, 0x1EEB2, 0x1EEB3, 0x1EEB4, 0x1EEB5, 0x1EEB6, 0x1EEB7,
0x1EEB8, 0x1EEB9, 0x1EEBA, 0x1EEBB, 0x10FFFD];
function determineBidi(cueDiv) {
var nodeStack = [],
text = "",
charCode;
if (!cueDiv || !cueDiv.childNodes) {
return "ltr";
}
function pushNodes(nodeStack, node) {
for (var i = node.childNodes.length - 1; i >= 0; i--) {
nodeStack.push(node.childNodes[i]);
}
}
function nextTextNode(nodeStack) {
if (!nodeStack || !nodeStack.length) {
return null;
}
var node = nodeStack.pop(),
text = node.textContent || node.innerText;
if (text) {
// TODO: This should match all unicode type B characters (paragraph
// separator characters). See issue #115.
var m = text.match(/^.*(\n|\r)/);
if (m) {
nodeStack.length = 0;
return m[0];
}
return text;
}
if (node.tagName === "ruby") {
return nextTextNode(nodeStack);
}
if (node.childNodes) {
pushNodes(nodeStack, node);
return nextTextNode(nodeStack);
}
}
pushNodes(nodeStack, cueDiv);
while ((text = nextTextNode(nodeStack))) {
for (var i = 0; i < text.length; i++) {
charCode = text.charCodeAt(i);
for (var j = 0; j < strongRTLChars.length; j++) {
if (strongRTLChars[j] === charCode) {
return "rtl";
}
}
}
}
return "ltr";
}
function computeLinePos(cue) {
if (typeof cue.line === "number" &&
(cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) {
return cue.line;
}
if (!cue.track || !cue.track.textTrackList ||
!cue.track.textTrackList.mediaElement) {
return -1;
}
var track = cue.track,
trackList = track.textTrackList,
count = 0;
for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {
if (trackList[i].mode === "showing") {
count++;
}
}
return ++count * -1;
}
function StyleBox() {
}
// Apply styles to a div. If there is no div passed then it defaults to the
// div on 'this'.
StyleBox.prototype.applyStyles = function(styles, div) {
div = div || this.div;
for (var prop in styles) {
if (styles.hasOwnProperty(prop)) {
div.style[prop] = styles[prop];
}
}
};
StyleBox.prototype.formatStyle = function(val, unit) {
return val === 0 ? 0 : val + unit;
};
// Constructs the computed display state of the cue (a div). Places the div
// into the overlay which should be a block level element (usually a div).
function CueStyleBox(window, cue, styleOptions) {
var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
var color = "rgba(255, 255, 255, 1)";
var backgroundColor = "rgba(0, 0, 0, 0.8)";
if (isIE8) {
color = "rgb(255, 255, 255)";
backgroundColor = "rgb(0, 0, 0)";
}
StyleBox.call(this);
this.cue = cue;
// Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will
// have inline positioning and will function as the cue background box.
this.cueDiv = parseContent(window, cue.text);
var styles = {
color: color,
backgroundColor: backgroundColor,
position: "relative",
left: 0,
right: 0,
top: 0,
bottom: 0,
display: "inline"
};
if (!isIE8) {
styles.writingMode = cue.vertical === "" ? "horizontal-tb"
: cue.vertical === "lr" ? "vertical-lr"
: "vertical-rl";
styles.unicodeBidi = "plaintext";
}
this.applyStyles(styles, this.cueDiv);
// Create an absolutely positioned div that will be used to position the cue
// div. Note, all WebVTT cue-setting alignments are equivalent to the CSS
// mirrors of them except "middle" which is "center" in CSS.
this.div = window.document.createElement("div");
styles = {
textAlign: cue.align === "middle" ? "center" : cue.align,
font: styleOptions.font,
whiteSpace: "pre-line",
position: "absolute"
};
if (!isIE8) {
styles.direction = determineBidi(this.cueDiv);
styles.writingMode = cue.vertical === "" ? "horizontal-tb"
: cue.vertical === "lr" ? "vertical-lr"
: "vertical-rl".
stylesunicodeBidi = "plaintext";
}
this.applyStyles(styles);
this.div.appendChild(this.cueDiv);
// Calculate the distance from the reference edge of the viewport to the text
// position of the cue box. The reference edge will be resolved later when
// the box orientation styles are applied.
var textPos = 0;
switch (cue.positionAlign) {
case "start":
textPos = cue.position;
break;
case "middle":
textPos = cue.position - (cue.size / 2);
break;
case "end":
textPos = cue.position - cue.size;
break;
}
// Horizontal box orientation; textPos is the distance from the left edge of the
// area to the left edge of the box and cue.size is the distance extending to
// the right from there.
if (cue.vertical === "") {
this.applyStyles({
left: this.formatStyle(textPos, "%"),
width: this.formatStyle(cue.size, "%"),
});
// Vertical box orientation; textPos is the distance from the top edge of the
// area to the top edge of the box and cue.size is the height extending
// downwards from there.
} else {
this.applyStyles({
top: this.formatStyle(textPos, "%"),
height: this.formatStyle(cue.size, "%")
});
}
this.move = function(box) {
this.applyStyles({
top: this.formatStyle(box.top, "px"),
bottom: this.formatStyle(box.bottom, "px"),
left: this.formatStyle(box.left, "px"),
right: this.formatStyle(box.right, "px"),
height: this.formatStyle(box.height, "px"),
width: this.formatStyle(box.width, "px"),
});
};
}
CueStyleBox.prototype = _objCreate(StyleBox.prototype);
CueStyleBox.prototype.constructor = CueStyleBox;
// Represents the co-ordinates of an Element in a way that we can easily
// compute things with such as if it overlaps or intersects with another Element.
// Can initialize it with either a StyleBox or another BoxPosition.
function BoxPosition(obj) {
var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
// Either a BoxPosition was passed in and we need to copy it, or a StyleBox
// was passed in and we need to copy the results of 'getBoundingClientRect'
// as the object returned is readonly. All co-ordinate values are in reference
// to the viewport origin (top left).
var lh, height, width, top;
if (obj.div) {
height = obj.div.offsetHeight;
width = obj.div.offsetWidth;
top = obj.div.offsetTop;
var rects = (rects = obj.div.childNodes) && (rects = rects[0]) &&
rects.getClientRects && rects.getClientRects();
obj = obj.div.getBoundingClientRect();
// In certain cases the outter div will be slightly larger then the sum of
// the inner div's lines. This could be due to bold text, etc, on some platforms.
// In this case we should get the average line height and use that. This will
// result in the desired behaviour.
lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length)
: 0;
}
this.left = obj.left;
this.right = obj.right;
this.top = obj.top || top;
this.height = obj.height || height;
this.bottom = obj.bottom || (top + (obj.height || height));
this.width = obj.width || width;
this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
if (isIE8 && !this.lineHeight) {
this.lineHeight = 13;
}
}
// Move the box along a particular axis. Optionally pass in an amount to move
// the box. If no amount is passed then the default is the line height of the
// box.
BoxPosition.prototype.move = function(axis, toMove) {
toMove = toMove !== undefined ? toMove : this.lineHeight;
switch (axis) {
case "+x":
this.left += toMove;
this.right += toMove;
break;
case "-x":
this.left -= toMove;
this.right -= toMove;
break;
case "+y":
this.top += toMove;
this.bottom += toMove;
break;
case "-y":
this.top -= toMove;
this.bottom -= toMove;
break;
}
};
// Check if this box overlaps another box, b2.
BoxPosition.prototype.overlaps = function(b2) {
return this.left < b2.right &&
this.right > b2.left &&
this.top < b2.bottom &&
this.bottom > b2.top;
};
// Check if this box overlaps any other boxes in boxes.
BoxPosition.prototype.overlapsAny = function(boxes) {
for (var i = 0; i < boxes.length; i++) {
if (this.overlaps(boxes[i])) {
return true;
}
}
return false;
};
// Check if this box is within another box.
BoxPosition.prototype.within = function(container) {
return this.top >= container.top &&
this.bottom <= container.bottom &&
this.left >= container.left &&
this.right <= container.right;
};
// Check if this box is entirely within the container or it is overlapping
// on the edge opposite of the axis direction passed. For example, if "+x" is
// passed and the box is overlapping on the left edge of the container, then
// return true.
BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) {
switch (axis) {
case "+x":
return this.left < container.left;
case "-x":
return this.right > container.right;
case "+y":
return this.top < container.top;
case "-y":
return this.bottom > container.bottom;
}
};
// Find the percentage of the area that this box is overlapping with another
// box.
BoxPosition.prototype.intersectPercentage = function(b2) {
var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
intersectArea = x * y;
return intersectArea / (this.height * this.width);
};
// Convert the positions from this box to CSS compatible positions using
// the reference container's positions. This has to be done because this
// box's positions are in reference to the viewport origin, whereas, CSS
// values are in referecne to their respective edges.
BoxPosition.prototype.toCSSCompatValues = function(reference) {
return {
top: this.top - reference.top,
bottom: reference.bottom - this.bottom,
left: this.left - reference.left,
right: reference.right - this.right,
height: this.height,
width: this.width
};
};
// Get an object that represents the box's position without anything extra.
// Can pass a StyleBox, HTMLElement, or another BoxPositon.
BoxPosition.getSimpleBoxPosition = function(obj) {
var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
obj = obj.div ? obj.div.getBoundingClientRect() :
obj.tagName ? obj.getBoundingClientRect() : obj;
var ret = {
left: obj.left,
right: obj.right,
top: obj.top || top,
height: obj.height || height,
bottom: obj.bottom || (top + (obj.height || height)),
width: obj.width || width
};
return ret;
};
// Move a StyleBox to its specified, or next best, position. The containerBox
// is the box that contains the StyleBox, such as a div. boxPositions are
// a list of other boxes that the styleBox can't overlap with.
function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
// Find the best position for a cue box, b, on the video. The axis parameter
// is a list of axis, the order of which, it will move the box along. For example:
// Passing ["+x", "-x"] will move the box first along the x axis in the positive
// direction. If it doesn't find a good position for it there it will then move
// it along the x axis in the negative direction.
function findBestPosition(b, axis) {
var bestPosition,
specifiedPosition = new BoxPosition(b),
percentage = 1; // Highest possible so the first thing we get is better.
for (var i = 0; i < axis.length; i++) {
while (b.overlapsOppositeAxis(containerBox, axis[i]) ||
(b.within(containerBox) && b.overlapsAny(boxPositions))) {
b.move(axis[i]);
}
// We found a spot where we aren't overlapping anything. This is our
// best position.
if (b.within(containerBox)) {
return b;
}
var p = b.intersectPercentage(containerBox);
// If we're outside the container box less then we were on our last try
// then remember this position as the best position.
if (percentage > p) {
bestPosition = new BoxPosition(b);
percentage = p;
}
// Reset the box position to the specified position.
b = new BoxPosition(specifiedPosition);
}
return bestPosition || specifiedPosition;
}
var boxPosition = new BoxPosition(styleBox),
cue = styleBox.cue,
linePos = computeLinePos(cue),
axis = [];
// If we have a line number to align the cue to.
if (cue.snapToLines) {
var size;
switch (cue.vertical) {
case "":
axis = [ "+y", "-y" ];
size = "height";
break;
case "rl":
axis = [ "+x", "-x" ];
size = "width";
break;
case "lr":
axis = [ "-x", "+x" ];
size = "width";
break;
}
var step = boxPosition.lineHeight,
position = step * Math.round(linePos),
maxPosition = containerBox[size] + step,
initialAxis = axis[0];
// If the specified intial position is greater then the max position then
// clamp the box to the amount of steps it would take for the box to
// reach the max position.
if (Math.abs(position) > maxPosition) {
position = position < 0 ? -1 : 1;
position *= Math.ceil(maxPosition / step) * step;
}
// If computed line position returns negative then line numbers are
// relative to the bottom of the video instead of the top. Therefore, we
// need to increase our initial position by the length or width of the
// video, depending on the writing direction, and reverse our axis directions.
if (linePos < 0) {
position += cue.vertical === "" ? containerBox.height : containerBox.width;
axis = axis.reverse();
}
// Move the box to the specified position. This may not be its best
// position.
boxPosition.move(initialAxis, position);
} else {
// If we have a percentage line value for the cue.
var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100;
switch (cue.lineAlign) {
case "middle":
linePos -= (calculatedPercentage / 2);
break;
case "end":
linePos -= calculatedPercentage;
break;
}
// Apply initial line position to the cue box.
switch (cue.vertical) {
case "":
styleBox.applyStyles({
top: styleBox.formatStyle(linePos, "%")
});
break;
case "rl":
styleBox.applyStyles({
left: styleBox.formatStyle(linePos, "%")
});
break;
case "lr":
styleBox.applyStyles({
right: styleBox.formatStyle(linePos, "%")
});
break;
}
axis = [ "+y", "-x", "+x", "-y" ];
// Get the box position again after we've applied the specified positioning
// to it.
boxPosition = new BoxPosition(styleBox);
}
var bestPosition = findBestPosition(boxPosition, axis);
styleBox.move(bestPosition.toCSSCompatValues(containerBox));
}
function WebVTT() {
// Nothing
}
// Helper to allow strings to be decoded instead of the default binary utf8 data.
WebVTT.StringDecoder = function() {
return {
decode: function(data) {
if (!data) {
return "";
}
if (typeof data !== "string") {
throw new Error("Error - expected string data.");
}
return decodeURIComponent(encodeURIComponent(data));
}
};
};
WebVTT.convertCueToDOMTree = function(window, cuetext) {
if (!window || !cuetext) {
return null;
}
return parseContent(window, cuetext);
};
var FONT_SIZE_PERCENT = 0.05;
var FONT_STYLE = "sans-serif";
var CUE_BACKGROUND_PADDING = "1.5%";
// Runs the processing model over the cues and regions passed to it.
// @param overlay A block level element (usually a div) that the computed cues
// and regions will be placed into.
WebVTT.processCues = function(window, cues, overlay) {
if (!window || !cues || !overlay) {
return null;
}
// Remove all previous children.
while (overlay.firstChild) {
overlay.removeChild(overlay.firstChild);
}
var paddedOverlay = window.document.createElement("div");
paddedOverlay.style.position = "absolute";
paddedOverlay.style.left = "0";
paddedOverlay.style.right = "0";
paddedOverlay.style.top = "0";
paddedOverlay.style.bottom = "0";
paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
overlay.appendChild(paddedOverlay);
// Determine if we need to compute the display states of the cues. This could
// be the case if a cue's state has been changed since the last computation or
// if it has not been computed yet.
function shouldCompute(cues) {
for (var i = 0; i < cues.length; i++) {
if (cues[i].hasBeenReset || !cues[i].displayState) {
return true;
}
}
return false;
}
// We don't need to recompute the cues' display states. Just reuse them.
if (!shouldCompute(cues)) {
for (var i = 0; i < cues.length; i++) {
paddedOverlay.appendChild(cues[i].displayState);
}
return;
}
var boxPositions = [],
containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),
fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
var styleOptions = {
font: fontSize + "px " + FONT_STYLE
};
(function() {
var styleBox, cue;
for (var i = 0; i < cues.length; i++) {
cue = cues[i];
// Compute the intial position and styles of the cue div.
styleBox = new CueStyleBox(window, cue, styleOptions);
paddedOverlay.appendChild(styleBox.div);
// Move the cue div to it's correct line position.
moveBoxToLinePosition(window, styleBox, containerBox, boxPositions);
// Remember the computed div so that we don't have to recompute it later
// if we don't have too.
cue.displayState = styleBox.div;
boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
}
})();
};
WebVTT.Parser = function(window, vttjs, decoder) {
if (!decoder) {
decoder = vttjs;
vttjs = {};
}
if (!vttjs) {
vttjs = {};
}
this.window = window;
this.vttjs = vttjs;
this.state = "INITIAL";
this.buffer = "";
this.decoder = decoder || new TextDecoder("utf8");
this.regionList = [];
};
WebVTT.Parser.prototype = {
// If the error is a ParsingError then report it to the consumer if
// possible. If it's not a ParsingError then throw it like normal.
reportOrThrowError: function(e) {
if (e instanceof ParsingError) {
this.onparsingerror && this.onparsingerror(e);
} else {
throw e;
}
},
parse: function (data) {
var self = this;
// If there is no data then we won't decode it, but will just try to parse
// whatever is in buffer already. This may occur in circumstances, for
// example when flush() is called.
if (data) {
// Try to decode the data that we received.
self.buffer += self.decoder.decode(data, {stream: true});
}
function collectNextLine() {
var buffer = self.buffer;
var pos = 0;
while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
++pos;
}
var line = buffer.substr(0, pos);
// Advance the buffer early in case we fail below.
if (buffer[pos] === '\r') {
++pos;
}
if (buffer[pos] === '\n') {
++pos;
}
self.buffer = buffer.substr(pos);
return line;
}
// 3.4 WebVTT region and WebVTT region settings syntax
function parseRegion(input) {
var settings = new Settings();
parseOptions(input, function (k, v) {
switch (k) {
case "id":
settings.set(k, v);
break;
case "width":
settings.percent(k, v);
break;
case "lines":
settings.integer(k, v);
break;
case "regionanchor":
case "viewportanchor":
var xy = v.split(',');
if (xy.length !== 2) {
break;
}
// We have to make sure both x and y parse, so use a temporary
// settings object here.
var anchor = new Settings();
anchor.percent("x", xy[0]);
anchor.percent("y", xy[1]);
if (!anchor.has("x") || !anchor.has("y")) {
break;
}
settings.set(k + "X", anchor.get("x"));
settings.set(k + "Y", anchor.get("y"));
break;
case "scroll":
settings.alt(k, v, ["up"]);
break;
}
}, /=/, /\s/);
// Create the region, using default values for any values that were not
// specified.
if (settings.has("id")) {
var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();
region.width = settings.get("width", 100);
region.lines = settings.get("lines", 3);
region.regionAnchorX = settings.get("regionanchorX", 0);
region.regionAnchorY = settings.get("regionanchorY", 100);
region.viewportAnchorX = settings.get("viewportanchorX", 0);
region.viewportAnchorY = settings.get("viewportanchorY", 100);
region.scroll = settings.get("scroll", "");
// Register the region.
self.onregion && self.onregion(region);
// Remember the VTTRegion for later in case we parse any VTTCues that
// reference it.
self.regionList.push({
id: settings.get("id"),
region: region
});
}
}
// 3.2 WebVTT metadata header syntax
function parseHeader(input) {
parseOptions(input, function (k, v) {
switch (k) {
case "Region":
// 3.3 WebVTT region metadata header syntax
parseRegion(v);
break;
}
}, /:/);
}
// 5.1 WebVTT file parsing.
try {
var line;
if (self.state === "INITIAL") {
// We can't start parsing until we have the first line.
if (!/\r\n|\n/.test(self.buffer)) {
return this;
}
line = collectNextLine();
var m = line.match(/^WEBVTT([ \t].*)?$/);
if (!m || !m[0]) {
throw new ParsingError(ParsingError.Errors.BadSignature);
}
self.state = "HEADER";
}
var alreadyCollectedLine = false;
while (self.buffer) {
// We can't parse a line until we have the full line.
if (!/\r\n|\n/.test(self.buffer)) {
return this;
}
if (!alreadyCollectedLine) {
line = collectNextLine();
} else {
alreadyCollectedLine = false;
}
switch (self.state) {
case "HEADER":
// 13-18 - Allow a header (metadata) under the WEBVTT line.
if (/:/.test(line)) {
parseHeader(line);
} else if (!line) {
// An empty line terminates the header and starts the body (cues).
self.state = "ID";
}
continue;
case "NOTE":
// Ignore NOTE blocks.
if (!line) {
self.state = "ID";
}
continue;
case "ID":
// Check for the start of NOTE blocks.
if (/^NOTE($|[ \t])/.test(line)) {
self.state = "NOTE";
break;
}
// 19-29 - Allow any number of line terminators, then initialize new cue values.
if (!line) {
continue;
}
self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, "");
self.state = "CUE";
// 30-39 - Check if self line contains an optional identifier or timing data.
if (line.indexOf("-->") === -1) {
self.cue.id = line;
continue;
}
// Process line as start of a cue.
/*falls through*/
case "CUE":
// 40 - Collect cue timings and settings.
try {
parseCue(line, self.cue, self.regionList);
} catch (e) {
self.reportOrThrowError(e);
// In case of an error ignore rest of the cue.
self.cue = null;
self.state = "BADCUE";
continue;
}
self.state = "CUETEXT";
continue;
case "CUETEXT":
var hasSubstring = line.indexOf("-->") !== -1;
// 34 - If we have an empty line then report the cue.
// 35 - If we have the special substring '-->' then report the cue,
// but do not collect the line as we need to process the current
// one as a new cue.
if (!line || hasSubstring && (alreadyCollectedLine = true)) {
// We are done parsing self cue.
self.oncue && self.oncue(self.cue);
self.cue = null;
self.state = "ID";
continue;
}
if (self.cue.text) {
self.cue.text += "\n";
}
self.cue.text += line;
continue;
case "BADCUE": // BADCUE
// 54-62 - Collect and discard the remaining cue.
if (!line) {
self.state = "ID";
}
continue;
}
}
} catch (e) {
self.reportOrThrowError(e);
// If we are currently parsing a cue, report what we have.
if (self.state === "CUETEXT" && self.cue && self.oncue) {
self.oncue(self.cue);
}
self.cue = null;
// Enter BADWEBVTT state if header was not parsed correctly otherwise
// another exception occurred so enter BADCUE state.
self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
}
return this;
},
flush: function () {
var self = this;
try {
// Finish decoding the stream.
self.buffer += self.decoder.decode();
// Synthesize the end of the current cue or region.
if (self.cue || self.state === "HEADER") {
self.buffer += "\n\n";
self.parse();
}
// If we've flushed, parsed, and we're still on the INITIAL state then
// that means we don't have enough of the stream to parse the first
// line.
if (self.state === "INITIAL") {
throw new ParsingError(ParsingError.Errors.BadSignature);
}
} catch(e) {
self.reportOrThrowError(e);
}
self.onflush && self.onflush();
return this;
}
};
global.WebVTT = WebVTT;
}(this, (this.vttjs || {})));
//# sourceMappingURL=video.js.map |
blueocean-material-icons/src/js/components/svg-icons/editor/format-shapes.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const EditorFormatShapes = (props) => (
<SvgIcon {...props}>
<path d="M23 7V1h-6v2H7V1H1v6h2v10H1v6h6v-2h10v2h6v-6h-2V7h2zM3 3h2v2H3V3zm2 18H3v-2h2v2zm12-2H7v-2H5V7h2V5h10v2h2v10h-2v2zm4 2h-2v-2h2v2zM19 5V3h2v2h-2zm-5.27 9h-3.49l-.73 2H7.89l3.4-9h1.4l3.41 9h-1.63l-.74-2zm-3.04-1.26h2.61L12 8.91l-1.31 3.83z"/>
</SvgIcon>
);
EditorFormatShapes.displayName = 'EditorFormatShapes';
EditorFormatShapes.muiName = 'SvgIcon';
export default EditorFormatShapes;
|
ajax/libs/react/0.13.0/react-with-addons.min.js | ColinEberhardt/cdnjs | /**
* React (with addons) v0.13.0
*
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.React=e()}}(function(){return function e(t,n,r){function o(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(e,t){"use strict";var n=e(25),r=e(31),o=e(42),i=e(34),a=e(67),s=e(95),u=e(97),l=e(124),c=e(119),p=e(165);r.addons={CSSTransitionGroup:i,LinkedStateMixin:n,PureRenderMixin:o,TransitionGroup:s,batchedUpdates:u.batchedUpdates,classSet:l,cloneWithProps:c,createFragment:a.create,update:p},t.exports=r},{119:119,124:124,165:165,25:25,31:31,34:34,42:42,67:67,95:95,97:97}],2:[function(e,t){"use strict";var n=e(131),r={componentDidMount:function(){this.props.autoFocus&&n(this.getDOMNode())}};t.exports=r},{131:131}],3:[function(e,t){"use strict";function n(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function r(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function o(e){switch(e){case N.topCompositionStart:return P.compositionStart;case N.topCompositionEnd:return P.compositionEnd;case N.topCompositionUpdate:return P.compositionUpdate}}function i(e,t){return e===N.topKeyDown&&t.keyCode===E}function a(e,t){switch(e){case N.topKeyUp:return-1!==C.indexOf(t.keyCode);case N.topKeyDown:return t.keyCode!==E;case N.topKeyPress:case N.topMouseDown:case N.topBlur:return!0;default:return!1}}function s(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function u(e,t,n,r){var u,l;if(b?u=o(e):R?a(e,r)&&(u=P.compositionEnd):i(e,r)&&(u=P.compositionStart),!u)return null;D&&(R||u!==P.compositionStart?u===P.compositionEnd&&R&&(l=R.getData()):R=m.getPooled(t));var c=v.getPooled(u,n,r);if(l)c.data=l;else{var p=s(r);null!==p&&(c.data=p)}return f.accumulateTwoPhaseDispatches(c),c}function l(e,t){switch(e){case N.topCompositionEnd:return s(t);case N.topKeyPress:var n=t.which;return n!==M?null:(I=!0,T);case N.topTextInput:var r=t.data;return r===T&&I?null:r;default:return null}}function c(e,t){if(R){if(e===N.topCompositionEnd||a(e,t)){var n=R.getData();return m.release(R),R=null,n}return null}switch(e){case N.topPaste:return null;case N.topKeyPress:return t.which&&!r(t)?String.fromCharCode(t.which):null;case N.topCompositionEnd:return D?null:t.data;default:return null}}function p(e,t,n,r){var o;if(o=x?l(e,r):c(e,r),!o)return null;var i=g.getPooled(P.beforeInput,n,r);return i.data=o,f.accumulateTwoPhaseDispatches(i),i}var d=e(16),f=e(21),h=e(22),m=e(23),v=e(103),g=e(107),y=e(154),C=[9,13,27,32],E=229,b=h.canUseDOM&&"CompositionEvent"in window,_=null;h.canUseDOM&&"documentMode"in document&&(_=document.documentMode);var x=h.canUseDOM&&"TextEvent"in window&&!_&&!n(),D=h.canUseDOM&&(!b||_&&_>8&&11>=_),M=32,T=String.fromCharCode(M),N=d.topLevelTypes,P={beforeInput:{phasedRegistrationNames:{bubbled:y({onBeforeInput:null}),captured:y({onBeforeInputCapture:null})},dependencies:[N.topCompositionEnd,N.topKeyPress,N.topTextInput,N.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:y({onCompositionEnd:null}),captured:y({onCompositionEndCapture:null})},dependencies:[N.topBlur,N.topCompositionEnd,N.topKeyDown,N.topKeyPress,N.topKeyUp,N.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:y({onCompositionStart:null}),captured:y({onCompositionStartCapture:null})},dependencies:[N.topBlur,N.topCompositionStart,N.topKeyDown,N.topKeyPress,N.topKeyUp,N.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:y({onCompositionUpdate:null}),captured:y({onCompositionUpdateCapture:null})},dependencies:[N.topBlur,N.topCompositionUpdate,N.topKeyDown,N.topKeyPress,N.topKeyUp,N.topMouseDown]}},I=!1,R=null,w={eventTypes:P,extractEvents:function(e,t,n,r){return[u(e,t,n,r),p(e,t,n,r)]}};t.exports=w},{103:103,107:107,154:154,16:16,21:21,22:22,23:23}],4:[function(e,t){var n=e(147),r={addClass:function(e,t){return n(!/\s/.test(t)),t&&(e.classList?e.classList.add(t):r.hasClass(e,t)||(e.className=e.className+" "+t)),e},removeClass:function(e,t){return n(!/\s/.test(t)),t&&(e.classList?e.classList.remove(t):r.hasClass(e,t)&&(e.className=e.className.replace(new RegExp("(^|\\s)"+t+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,""))),e},conditionClass:function(e,t,n){return(n?r.addClass:r.removeClass)(e,t)},hasClass:function(e,t){return n(!/\s/.test(t)),e.classList?!!t&&e.classList.contains(t):(" "+e.className+" ").indexOf(" "+t+" ")>-1}};t.exports=r},{147:147}],5:[function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var r={boxFlex:!0,boxFlexGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,strokeOpacity:!0},o=["Webkit","ms","Moz","O"];Object.keys(r).forEach(function(e){o.forEach(function(t){r[n(t,e)]=r[e]})});var i={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0}},a={isUnitlessNumber:r,shorthandPropertyExpansions:i};t.exports=a},{}],6:[function(e,t){"use strict";var n=e(5),r=e(22),o=(e(118),e(125)),i=e(145),a=e(156),s=(e(166),a(function(e){return i(e)})),u="cssFloat";r.canUseDOM&&void 0===document.documentElement.style.cssFloat&&(u="styleFloat");var l={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];null!=r&&(t+=s(n)+":",t+=o(n,r)+";")}return t||null},setValueForStyles:function(e,t){var r=e.style;for(var i in t)if(t.hasOwnProperty(i)){var a=o(i,t[i]);if("float"===i&&(i=u),a)r[i]=a;else{var s=n.shorthandPropertyExpansions[i];if(s)for(var l in s)r[l]="";else r[i]=""}}}};t.exports=l},{118:118,125:125,145:145,156:156,166:166,22:22,5:5}],7:[function(e,t){"use strict";function n(){this._callbacks=null,this._contexts=null}var r=e(30),o=e(29),i=e(147);o(n.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){i(e.length===t.length),this._callbacks=null,this._contexts=null;for(var n=0,r=e.length;r>n;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n},{147:147,29:29,30:30}],8:[function(e,t){"use strict";function n(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function r(e){var t=_.getPooled(N.change,I,e);C.accumulateTwoPhaseDispatches(t),b.batchedUpdates(o,t)}function o(e){y.enqueueEvents(e),y.processEventQueue()}function i(e,t){P=e,I=t,P.attachEvent("onchange",r)}function a(){P&&(P.detachEvent("onchange",r),P=null,I=null)}function s(e,t,n){return e===T.topChange?n:void 0}function u(e,t,n){e===T.topFocus?(a(),i(t,n)):e===T.topBlur&&a()}function l(e,t){P=e,I=t,R=e.value,w=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(P,"value",A),P.attachEvent("onpropertychange",p)}function c(){P&&(delete P.value,P.detachEvent("onpropertychange",p),P=null,I=null,R=null,w=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==R&&(R=t,r(e))}}function d(e,t,n){return e===T.topInput?n:void 0}function f(e,t,n){e===T.topFocus?(c(),l(t,n)):e===T.topBlur&&c()}function h(e){return e!==T.topSelectionChange&&e!==T.topKeyUp&&e!==T.topKeyDown||!P||P.value===R?void 0:(R=P.value,I)}function m(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function v(e,t,n){return e===T.topClick?n:void 0}var g=e(16),y=e(18),C=e(21),E=e(22),b=e(97),_=e(105),x=e(148),D=e(150),M=e(154),T=g.topLevelTypes,N={change:{phasedRegistrationNames:{bubbled:M({onChange:null}),captured:M({onChangeCapture:null})},dependencies:[T.topBlur,T.topChange,T.topClick,T.topFocus,T.topInput,T.topKeyDown,T.topKeyUp,T.topSelectionChange]}},P=null,I=null,R=null,w=null,O=!1;E.canUseDOM&&(O=x("change")&&(!("documentMode"in document)||document.documentMode>8));var S=!1;E.canUseDOM&&(S=x("input")&&(!("documentMode"in document)||document.documentMode>9));var A={get:function(){return w.get.call(this)},set:function(e){R=""+e,w.set.call(this,e)}},k={eventTypes:N,extractEvents:function(e,t,r,o){var i,a;if(n(t)?O?i=s:a=u:D(t)?S?i=d:(i=h,a=f):m(t)&&(i=v),i){var l=i(e,t,r);if(l){var c=_.getPooled(N.change,l,o);return C.accumulateTwoPhaseDispatches(c),c}}a&&a(e,t,r)}};t.exports=k},{105:105,148:148,150:150,154:154,16:16,18:18,21:21,22:22,97:97}],9:[function(e,t){"use strict";var n=0,r={createReactRootIndex:function(){return n++}};t.exports=r},{}],10:[function(e,t){"use strict";function n(e,t,n){e.insertBefore(t,e.childNodes[n]||null)}var r=e(13),o=e(77),i=e(160),a=e(147),s={dangerouslyReplaceNodeWithMarkup:r.dangerouslyReplaceNodeWithMarkup,updateTextContent:i,processUpdates:function(e,t){for(var s,u=null,l=null,c=0;c<e.length;c++)if(s=e[c],s.type===o.MOVE_EXISTING||s.type===o.REMOVE_NODE){var p=s.fromIndex,d=s.parentNode.childNodes[p],f=s.parentID;a(d),u=u||{},u[f]=u[f]||[],u[f][p]=d,l=l||[],l.push(d)}var h=r.dangerouslyRenderMarkup(t);if(l)for(var m=0;m<l.length;m++)l[m].parentNode.removeChild(l[m]);for(var v=0;v<e.length;v++)switch(s=e[v],s.type){case o.INSERT_MARKUP:n(s.parentNode,h[s.markupIndex],s.toIndex);break;case o.MOVE_EXISTING:n(s.parentNode,u[s.parentID][s.fromIndex],s.toIndex);break;case o.TEXT_CONTENT:i(s.parentNode,s.textContent);break;case o.REMOVE_NODE:}}};t.exports=s},{13:13,147:147,160:160,77:77}],11:[function(e,t){"use strict";function n(e,t){return(e&t)===t}var r=e(147),o={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=e.Properties||{},i=e.DOMAttributeNames||{},s=e.DOMPropertyNames||{},u=e.DOMMutationMethods||{};e.isCustomAttribute&&a._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var l in t){r(!a.isStandardName.hasOwnProperty(l)),a.isStandardName[l]=!0;var c=l.toLowerCase();if(a.getPossibleStandardName[c]=l,i.hasOwnProperty(l)){var p=i[l];a.getPossibleStandardName[p]=l,a.getAttributeName[l]=p}else a.getAttributeName[l]=c;a.getPropertyName[l]=s.hasOwnProperty(l)?s[l]:l,a.getMutationMethod[l]=u.hasOwnProperty(l)?u[l]:null;var d=t[l];a.mustUseAttribute[l]=n(d,o.MUST_USE_ATTRIBUTE),a.mustUseProperty[l]=n(d,o.MUST_USE_PROPERTY),a.hasSideEffects[l]=n(d,o.HAS_SIDE_EFFECTS),a.hasBooleanValue[l]=n(d,o.HAS_BOOLEAN_VALUE),a.hasNumericValue[l]=n(d,o.HAS_NUMERIC_VALUE),a.hasPositiveNumericValue[l]=n(d,o.HAS_POSITIVE_NUMERIC_VALUE),a.hasOverloadedBooleanValue[l]=n(d,o.HAS_OVERLOADED_BOOLEAN_VALUE),r(!a.mustUseAttribute[l]||!a.mustUseProperty[l]),r(a.mustUseProperty[l]||!a.hasSideEffects[l]),r(!!a.hasBooleanValue[l]+!!a.hasNumericValue[l]+!!a.hasOverloadedBooleanValue[l]<=1)}}},i={},a={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasNumericValue:{},hasPositiveNumericValue:{},hasOverloadedBooleanValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<a._isCustomAttributeFunctions.length;t++){var n=a._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=i[e];return r||(i[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:o};t.exports=a},{147:147}],12:[function(e,t){"use strict";function n(e,t){return null==t||r.hasBooleanValue[e]&&!t||r.hasNumericValue[e]&&isNaN(t)||r.hasPositiveNumericValue[e]&&1>t||r.hasOverloadedBooleanValue[e]&&t===!1}var r=e(11),o=e(158),i=(e(166),{createMarkupForID:function(e){return r.ID_ATTRIBUTE_NAME+"="+o(e)},createMarkupForProperty:function(e,t){if(r.isStandardName.hasOwnProperty(e)&&r.isStandardName[e]){if(n(e,t))return"";var i=r.getAttributeName[e];return r.hasBooleanValue[e]||r.hasOverloadedBooleanValue[e]&&t===!0?i:i+"="+o(t)}return r.isCustomAttribute(e)?null==t?"":e+"="+o(t):null},setValueForProperty:function(e,t,o){if(r.isStandardName.hasOwnProperty(t)&&r.isStandardName[t]){var i=r.getMutationMethod[t];if(i)i(e,o);else if(n(t,o))this.deleteValueForProperty(e,t);else if(r.mustUseAttribute[t])e.setAttribute(r.getAttributeName[t],""+o);else{var a=r.getPropertyName[t];r.hasSideEffects[t]&&""+e[a]==""+o||(e[a]=o)}}else r.isCustomAttribute(t)&&(null==o?e.removeAttribute(t):e.setAttribute(t,""+o))},deleteValueForProperty:function(e,t){if(r.isStandardName.hasOwnProperty(t)&&r.isStandardName[t]){var n=r.getMutationMethod[t];if(n)n(e,void 0);else if(r.mustUseAttribute[t])e.removeAttribute(r.getAttributeName[t]);else{var o=r.getPropertyName[t],i=r.getDefaultValueForProperty(e.nodeName,o);r.hasSideEffects[t]&&""+e[o]===i||(e[o]=i)}}else r.isCustomAttribute(t)&&e.removeAttribute(t)}});t.exports=i},{11:11,158:158,166:166}],13:[function(e,t){"use strict";function n(e){return e.substring(1,e.indexOf(" "))}var r=e(22),o=e(123),i=e(126),a=e(139),s=e(147),u=/^(<[^ \/>]+)/,l="data-danger-index",c={dangerouslyRenderMarkup:function(e){s(r.canUseDOM);for(var t,c={},p=0;p<e.length;p++)s(e[p]),t=n(e[p]),t=a(t)?t:"*",c[t]=c[t]||[],c[t][p]=e[p];var d=[],f=0;for(t in c)if(c.hasOwnProperty(t)){var h,m=c[t];for(h in m)if(m.hasOwnProperty(h)){var v=m[h];m[h]=v.replace(u,"$1 "+l+'="'+h+'" ')}for(var g=o(m.join(""),i),y=0;y<g.length;++y){var C=g[y];C.hasAttribute&&C.hasAttribute(l)&&(h=+C.getAttribute(l),C.removeAttribute(l),s(!d.hasOwnProperty(h)),d[h]=C,f+=1)}}return s(f===d.length),s(d.length===e.length),d},dangerouslyReplaceNodeWithMarkup:function(e,t){s(r.canUseDOM),s(t),s("html"!==e.tagName.toLowerCase());var n=o(t,i)[0];e.parentNode.replaceChild(n,e)}};t.exports=c},{123:123,126:126,139:139,147:147,22:22}],14:[function(e,t){"use strict";var n=e(154),r=[n({ResponderEventPlugin:null}),n({SimpleEventPlugin:null}),n({TapEventPlugin:null}),n({EnterLeaveEventPlugin:null}),n({ChangeEventPlugin:null}),n({SelectEventPlugin:null}),n({BeforeInputEventPlugin:null}),n({AnalyticsEventPlugin:null}),n({MobileSafariClickEventPlugin:null})];t.exports=r},{154:154}],15:[function(e,t){"use strict";var n=e(16),r=e(21),o=e(109),i=e(75),a=e(154),s=n.topLevelTypes,u=i.getFirstReactDOM,l={mouseEnter:{registrationName:a({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:a({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},c=[null,null],p={eventTypes:l,extractEvents:function(e,t,n,a){if(e===s.topMouseOver&&(a.relatedTarget||a.fromElement))return null;if(e!==s.topMouseOut&&e!==s.topMouseOver)return null;var p;if(t.window===t)p=t;else{var d=t.ownerDocument;p=d?d.defaultView||d.parentWindow:window}var f,h;if(e===s.topMouseOut?(f=t,h=u(a.relatedTarget||a.toElement)||p):(f=p,h=t),f===h)return null;var m=f?i.getID(f):"",v=h?i.getID(h):"",g=o.getPooled(l.mouseLeave,m,a);g.type="mouseleave",g.target=f,g.relatedTarget=h;var y=o.getPooled(l.mouseEnter,v,a);return y.type="mouseenter",y.target=h,y.relatedTarget=f,r.accumulateEnterLeaveDispatches(g,y,m,v),c[0]=g,c[1]=y,c}};t.exports=p},{109:109,154:154,16:16,21:21,75:75}],16:[function(e,t){"use strict";var n=e(153),r=n({bubbled:null,captured:null}),o=n({topBlur:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topReset:null,topScroll:null,topSelectionChange:null,topSubmit:null,topTextInput:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),i={topLevelTypes:o,PropagationPhases:r};t.exports=i},{153:153}],17:[function(e,t){var n=e(126),r={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,r){return e.addEventListener?(e.addEventListener(t,r,!0),{remove:function(){e.removeEventListener(t,r,!0)}}):{remove:n}},registerDefault:function(){}};t.exports=r},{126:126}],18:[function(e,t){"use strict";var n=e(19),r=e(20),o=e(115),i=e(132),a=e(147),s={},u=null,l=function(e){if(e){var t=r.executeDispatch,o=n.getPluginModuleForEvent(e);o&&o.executeDispatch&&(t=o.executeDispatch),r.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},c=null,p={injection:{injectMount:r.injection.injectMount,injectInstanceHandle:function(e){c=e},getInstanceHandle:function(){return c},injectEventPluginOrder:n.injectEventPluginOrder,injectEventPluginsByName:n.injectEventPluginsByName},eventNameDispatchConfigs:n.eventNameDispatchConfigs,registrationNameModules:n.registrationNameModules,putListener:function(e,t,n){a(!n||"function"==typeof n);var r=s[t]||(s[t]={});r[e]=n},getListener:function(e,t){var n=s[t];return n&&n[e]},deleteListener:function(e,t){var n=s[t];n&&delete n[e]},deleteAllListeners:function(e){for(var t in s)delete s[t][e]},extractEvents:function(e,t,r,i){for(var a,s=n.plugins,u=0,l=s.length;l>u;u++){var c=s[u];if(c){var p=c.extractEvents(e,t,r,i);p&&(a=o(a,p))}}return a},enqueueEvents:function(e){e&&(u=o(u,e))},processEventQueue:function(){var e=u;u=null,i(e,l),a(!u)},__purge:function(){s={}},__getListenerBank:function(){return s}};t.exports=p},{115:115,132:132,147:147,19:19,20:20}],19:[function(e,t){"use strict";function n(){if(a)for(var e in s){var t=s[e],n=a.indexOf(e);if(i(n>-1),!u.plugins[n]){i(t.extractEvents),u.plugins[n]=t;var o=t.eventTypes;for(var l in o)i(r(o[l],t,l))}}}function r(e,t,n){i(!u.eventNameDispatchConfigs.hasOwnProperty(n)),u.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var a in r)if(r.hasOwnProperty(a)){var s=r[a];o(s,t,n)}return!0}return e.registrationName?(o(e.registrationName,t,n),!0):!1}function o(e,t,n){i(!u.registrationNameModules[e]),u.registrationNameModules[e]=t,u.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var i=e(147),a=null,s={},u={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){i(!a),a=Array.prototype.slice.call(e),n()},injectEventPluginsByName:function(e){var t=!1;for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];s.hasOwnProperty(r)&&s[r]===o||(i(!s[r]),s[r]=o,t=!0)}t&&n()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return u.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=u.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){a=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];u.plugins.length=0;var t=u.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=u.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};t.exports=u},{147:147}],20:[function(e,t){"use strict";function n(e){return e===m.topMouseUp||e===m.topTouchEnd||e===m.topTouchCancel}function r(e){return e===m.topMouseMove||e===m.topTouchMove}function o(e){return e===m.topMouseDown||e===m.topTouchStart}function i(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)t(e,n[o],r[o]);else n&&t(e,n,r)}function a(e,t,n){e.currentTarget=h.Mount.getNode(n);var r=t(e,n);return e.currentTarget=null,r}function s(e,t){i(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function u(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function l(e){var t=u(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function c(e){var t=e._dispatchListeners,n=e._dispatchIDs;f(!Array.isArray(t));var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function p(e){return!!e._dispatchListeners}var d=e(16),f=e(147),h={Mount:null,injectMount:function(e){h.Mount=e}},m=d.topLevelTypes,v={isEndish:n,isMoveish:r,isStartish:o,executeDirectDispatch:c,executeDispatch:a,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:l,hasDispatches:p,injection:h,useTouchEvents:!1};t.exports=v},{147:147,16:16}],21:[function(e,t){"use strict";function n(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return m(e,r)}function r(e,t,r){var o=t?h.bubbled:h.captured,i=n(e,r,o);i&&(r._dispatchListeners=d(r._dispatchListeners,i),r._dispatchIDs=d(r._dispatchIDs,e))}function o(e){e&&e.dispatchConfig.phasedRegistrationNames&&p.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,r,e)}function i(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=m(e,r);o&&(n._dispatchListeners=d(n._dispatchListeners,o),n._dispatchIDs=d(n._dispatchIDs,e))}}function a(e){e&&e.dispatchConfig.registrationName&&i(e.dispatchMarker,null,e)}function s(e){f(e,o)}function u(e,t,n,r){p.injection.getInstanceHandle().traverseEnterLeave(n,r,i,e,t)}function l(e){f(e,a)}var c=e(16),p=e(18),d=e(115),f=e(132),h=c.PropagationPhases,m=p.getListener,v={accumulateTwoPhaseDispatches:s,accumulateDirectDispatches:l,accumulateEnterLeaveDispatches:u};t.exports=v},{115:115,132:132,16:16,18:18}],22:[function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),r={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};t.exports=r},{}],23:[function(e,t){"use strict";function n(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var r=e(30),o=e(29),i=e(142);o(n.prototype,{getText:function(){return"value"in this._root?this._root.value:this._root[i()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),i=o.length;for(e=0;r>e&&n[e]===o[e];e++);var a=r-e;for(t=1;a>=t&&n[r-t]===o[i-t];t++);var s=t>1?1-t:void 0;return this._fallbackText=o.slice(e,s),this._fallbackText}}),r.addPoolingTo(n),t.exports=n},{142:142,29:29,30:30}],24:[function(e,t){"use strict";var n,r=e(11),o=e(22),i=r.injection.MUST_USE_ATTRIBUTE,a=r.injection.MUST_USE_PROPERTY,s=r.injection.HAS_BOOLEAN_VALUE,u=r.injection.HAS_SIDE_EFFECTS,l=r.injection.HAS_NUMERIC_VALUE,c=r.injection.HAS_POSITIVE_NUMERIC_VALUE,p=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(o.canUseDOM){var d=document.implementation;n=d&&d.hasFeature&&d.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var f={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:i|s,allowTransparency:i,alt:null,async:s,autoComplete:null,autoPlay:s,cellPadding:null,cellSpacing:null,charSet:i,checked:a|s,classID:i,className:n?i:a,cols:i|c,colSpan:null,content:null,contentEditable:null,contextMenu:i,controls:a|s,coords:null,crossOrigin:null,data:null,dateTime:i,defer:s,dir:null,disabled:i|s,download:p,draggable:null,encType:null,form:i,formAction:i,formEncType:i,formMethod:i,formNoValidate:s,formTarget:i,frameBorder:i,headers:null,height:i,hidden:i|s,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:a,label:null,lang:null,list:i,loop:a|s,manifest:i,marginHeight:null,marginWidth:null,max:null,maxLength:i,media:i,mediaGroup:null,method:null,min:null,multiple:a|s,muted:a|s,name:null,noValidate:s,open:s,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:a|s,rel:null,required:s,role:i,rows:i|c,rowSpan:null,sandbox:null,scope:null,scrolling:null,seamless:i|s,selected:a|s,shape:null,size:i|c,sizes:i,span:c,spellCheck:null,src:null,srcDoc:a,srcSet:i,start:l,step:null,style:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:a|u,width:i,wmode:i,autoCapitalize:null,autoCorrect:null,itemProp:i,itemScope:i|s,itemType:i,itemID:i,itemRef:i,property:null},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};t.exports=f},{11:11,22:22}],25:[function(e,t){"use strict";var n=e(73),r=e(92),o={linkState:function(e){return new n(this.state[e],r.createStateKeySetter(this,e))}};t.exports=o},{73:73,92:92}],26:[function(e,t){"use strict";function n(e){u(null==e.props.checkedLink||null==e.props.valueLink)}function r(e){n(e),u(null==e.props.value&&null==e.props.onChange)}function o(e){n(e),u(null==e.props.checked&&null==e.props.onChange)}function i(e){this.props.valueLink.requestChange(e.target.value)}function a(e){this.props.checkedLink.requestChange(e.target.checked)}var s=e(84),u=e(147),l={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},c={Mixin:{propTypes:{value:function(e,t){return!e[t]||l[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:s.func}},getValue:function(e){return e.props.valueLink?(r(e),e.props.valueLink.value):e.props.value},getChecked:function(e){return e.props.checkedLink?(o(e),e.props.checkedLink.value):e.props.checked},getOnChange:function(e){return e.props.valueLink?(r(e),i):e.props.checkedLink?(o(e),a):e.props.onChange}};t.exports=c},{147:147,84:84}],27:[function(e,t){"use strict";function n(e){e.remove()}var r=e(33),o=e(115),i=e(132),a=e(147),s={trapBubbledEvent:function(e,t){a(this.isMounted());var n=this.getDOMNode();a(n);var i=r.trapBubbledEvent(e,t,n);this._localEventListeners=o(this._localEventListeners,i)},componentWillUnmount:function(){this._localEventListeners&&i(this._localEventListeners,n)}};t.exports=s},{115:115,132:132,147:147,33:33}],28:[function(e,t){"use strict";var n=e(16),r=e(126),o=n.topLevelTypes,i={eventTypes:null,extractEvents:function(e,t,n,i){if(e===o.topTouchStart){var a=i.target;a&&!a.onclick&&(a.onclick=r)}}};t.exports=i},{126:126,16:16}],29:[function(e,t){"use strict";function n(e){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var t=Object(e),n=Object.prototype.hasOwnProperty,r=1;r<arguments.length;r++){var o=arguments[r];if(null!=o){var i=Object(o);for(var a in i)n.call(i,a)&&(t[a]=i[a])}}return t}t.exports=n},{}],30:[function(e,t){"use strict";var n=e(147),r=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},o=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},i=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},a=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},s=function(e){var t=this;n(e instanceof t),e.destructor&&e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},u=10,l=r,c=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||l,n.poolSize||(n.poolSize=u),n.release=s,n},p={addPoolingTo:c,oneArgumentPooler:r,twoArgumentPooler:o,threeArgumentPooler:i,fiveArgumentPooler:a};t.exports=p},{147:147}],31:[function(e,t){"use strict";var n=e(20),r=e(37),o=e(39),i=e(38),a=e(44),s=e(45),u=e(61),l=(e(62),e(46)),c=e(57),p=e(60),d=e(70),f=e(75),h=e(80),m=e(84),v=e(87),g=e(90),y=e(29),C=e(129),E=e(157);p.inject();var b=u.createElement,_=u.createFactory,x=u.cloneElement,D=h.measure("React","render",f.render),M={Children:{map:r.map,forEach:r.forEach,count:r.count,only:E},Component:o,DOM:l,PropTypes:m,initializeTouchEvents:function(e){n.useTouchEvents=e},createClass:i.createClass,createElement:b,cloneElement:x,createFactory:_,createMixin:function(e){return e},constructAndRenderComponent:f.constructAndRenderComponent,constructAndRenderComponentByID:f.constructAndRenderComponentByID,findDOMNode:C,render:D,renderToString:g.renderToString,renderToStaticMarkup:g.renderToStaticMarkup,unmountComponentAtNode:f.unmountComponentAtNode,isValidElement:u.isValidElement,withContext:a.withContext,__spread:y};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({CurrentOwner:s,InstanceHandles:d,Mount:f,Reconciler:v,TextComponent:c});M.version="0.13.0",t.exports=M},{129:129,157:157,20:20,29:29,37:37,38:38,39:39,44:44,45:45,46:46,57:57,60:60,61:61,62:62,70:70,75:75,80:80,84:84,87:87,90:90}],32:[function(e,t){"use strict";var n=e(129),r={getDOMNode:function(){return n(this)}};t.exports=r},{129:129}],33:[function(e,t){"use strict";function n(e){return Object.prototype.hasOwnProperty.call(e,h)||(e[h]=d++,c[e[h]]={}),c[e[h]]}var r=e(16),o=e(18),i=e(19),a=e(65),s=e(114),u=e(29),l=e(148),c={},p=!1,d=0,f={topBlur:"blur",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topScroll:"scroll",topSelectionChange:"selectionchange",topTextInput:"textInput",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topWheel:"wheel"},h="_reactListenersID"+String(Math.random()).slice(2),m=u({},a,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(m.handleTopLevel),m.ReactEventListener=e}},setEnabled:function(e){m.ReactEventListener&&m.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!m.ReactEventListener||!m.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var o=t,a=n(o),s=i.registrationNameDependencies[e],u=r.topLevelTypes,c=0,p=s.length;p>c;c++){var d=s[c];
a.hasOwnProperty(d)&&a[d]||(d===u.topWheel?l("wheel")?m.ReactEventListener.trapBubbledEvent(u.topWheel,"wheel",o):l("mousewheel")?m.ReactEventListener.trapBubbledEvent(u.topWheel,"mousewheel",o):m.ReactEventListener.trapBubbledEvent(u.topWheel,"DOMMouseScroll",o):d===u.topScroll?l("scroll",!0)?m.ReactEventListener.trapCapturedEvent(u.topScroll,"scroll",o):m.ReactEventListener.trapBubbledEvent(u.topScroll,"scroll",m.ReactEventListener.WINDOW_HANDLE):d===u.topFocus||d===u.topBlur?(l("focus",!0)?(m.ReactEventListener.trapCapturedEvent(u.topFocus,"focus",o),m.ReactEventListener.trapCapturedEvent(u.topBlur,"blur",o)):l("focusin")&&(m.ReactEventListener.trapBubbledEvent(u.topFocus,"focusin",o),m.ReactEventListener.trapBubbledEvent(u.topBlur,"focusout",o)),a[u.topBlur]=!0,a[u.topFocus]=!0):f.hasOwnProperty(d)&&m.ReactEventListener.trapBubbledEvent(d,f[d],o),a[d]=!0)}},trapBubbledEvent:function(e,t,n){return m.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return m.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!p){var e=s.refreshScrollValues;m.ReactEventListener.monitorScrollValue(e),p=!0}},eventNameDispatchConfigs:o.eventNameDispatchConfigs,registrationNameModules:o.registrationNameModules,putListener:o.putListener,getListener:o.getListener,deleteListener:o.deleteListener,deleteAllListeners:o.deleteAllListeners});t.exports=m},{114:114,148:148,16:16,18:18,19:19,29:29,65:65}],34:[function(e,t){"use strict";var n=e(31),r=e(29),o=n.createFactory(e(95)),i=n.createFactory(e(35)),a=n.createClass({displayName:"ReactCSSTransitionGroup",propTypes:{transitionName:n.PropTypes.string.isRequired,transitionAppear:n.PropTypes.bool,transitionEnter:n.PropTypes.bool,transitionLeave:n.PropTypes.bool},getDefaultProps:function(){return{transitionAppear:!1,transitionEnter:!0,transitionLeave:!0}},_wrapChild:function(e){return i({name:this.props.transitionName,appear:this.props.transitionAppear,enter:this.props.transitionEnter,leave:this.props.transitionLeave},e)},render:function(){return o(r({},this.props,{childFactory:this._wrapChild}))}});t.exports=a},{29:29,31:31,35:35,95:95}],35:[function(e,t){"use strict";var n=e(31),r=e(4),o=e(94),i=e(157),a=(e(166),17),s=n.createClass({displayName:"ReactCSSTransitionGroupChild",transition:function(e,t){var n=this.getDOMNode(),i=this.props.name+"-"+e,a=i+"-active",s=function(e){e&&e.target!==n||(r.removeClass(n,i),r.removeClass(n,a),o.removeEndEventListener(n,s),t&&t())};o.addEndEventListener(n,s),r.addClass(n,i),this.queueClass(a)},queueClass:function(e){this.classNameQueue.push(e),this.timeout||(this.timeout=setTimeout(this.flushClassNameQueue,a))},flushClassNameQueue:function(){this.isMounted()&&this.classNameQueue.forEach(r.addClass.bind(r,this.getDOMNode())),this.classNameQueue.length=0,this.timeout=null},componentWillMount:function(){this.classNameQueue=[]},componentWillUnmount:function(){this.timeout&&clearTimeout(this.timeout)},componentWillAppear:function(e){this.props.appear?this.transition("appear",e):e()},componentWillEnter:function(e){this.props.enter?this.transition("enter",e):e()},componentWillLeave:function(e){this.props.leave?this.transition("leave",e):e()},render:function(){return i(this.props.children)}});t.exports=s},{157:157,166:166,31:31,4:4,94:94}],36:[function(e,t){"use strict";var n=e(87),r=e(130),o=e(146),i=e(162),a={instantiateChildren:function(e){var t=r(e);for(var n in t)if(t.hasOwnProperty(n)){var i=t[n],a=o(i,null);t[n]=a}return t},updateChildren:function(e,t,a,s){var u=r(t);if(!u&&!e)return null;var l;for(l in u)if(u.hasOwnProperty(l)){var c=e&&e[l],p=c&&c._currentElement,d=u[l];if(i(p,d))n.receiveComponent(c,d,a,s),u[l]=c;else{c&&n.unmountComponent(c,l);var f=o(d,null);u[l]=f}}for(l in e)!e.hasOwnProperty(l)||u&&u.hasOwnProperty(l)||n.unmountComponent(e[l]);return u},unmountChildren:function(e){for(var t in e){var r=e[t];n.unmountComponent(r)}}};t.exports=a},{130:130,146:146,162:162,87:87}],37:[function(e,t){"use strict";function n(e,t){this.forEachFunction=e,this.forEachContext=t}function r(e,t,n,r){var o=e;o.forEachFunction.call(o.forEachContext,t,r)}function o(e,t,o){if(null==e)return e;var i=n.getPooled(t,o);d(e,r,i),n.release(i)}function i(e,t,n){this.mapResult=e,this.mapFunction=t,this.mapContext=n}function a(e,t,n,r){var o=e,i=o.mapResult,a=!i.hasOwnProperty(n);if(a){var s=o.mapFunction.call(o.mapContext,t,r);i[n]=s}}function s(e,t,n){if(null==e)return e;var r={},o=i.getPooled(r,t,n);return d(e,a,o),i.release(o),p.create(r)}function u(){return null}function l(e){return d(e,u,null)}var c=e(30),p=e(67),d=e(164),f=(e(166),c.twoArgumentPooler),h=c.threeArgumentPooler;c.addPoolingTo(n,f),c.addPoolingTo(i,h);var m={forEach:o,map:s,count:l};t.exports=m},{164:164,166:166,30:30,67:67}],38:[function(e,t){"use strict";function n(e,t){var n=x.hasOwnProperty(t)?x[t]:null;M.hasOwnProperty(t)&&g(n===b.OVERRIDE_BASE),e.hasOwnProperty(t)&&g(n===b.DEFINE_MANY||n===b.DEFINE_MANY_MERGED)}function r(e,t){if(t){g("function"!=typeof t),g(!p.isValidElement(t));var r=e.prototype;t.hasOwnProperty(E)&&D.mixins(e,t.mixins);for(var o in t)if(t.hasOwnProperty(o)&&o!==E){var i=t[o];if(n(r,o),D.hasOwnProperty(o))D[o](e,i);else{var u=x.hasOwnProperty(o),l=r.hasOwnProperty(o),c=i&&i.__reactDontBind,d="function"==typeof i,f=d&&!u&&!l&&!c;if(f)r.__reactAutoBindMap||(r.__reactAutoBindMap={}),r.__reactAutoBindMap[o]=i,r[o]=i;else if(l){var h=x[o];g(u&&(h===b.DEFINE_MANY_MERGED||h===b.DEFINE_MANY)),h===b.DEFINE_MANY_MERGED?r[o]=a(r[o],i):h===b.DEFINE_MANY&&(r[o]=s(r[o],i))}else r[o]=i}}}}function o(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in D;g(!o);var i=n in e;g(!i),e[n]=r}}}function i(e,t){g(e&&t&&"object"==typeof e&&"object"==typeof t);for(var n in t)t.hasOwnProperty(n)&&(g(void 0===e[n]),e[n]=t[n]);return e}function a(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return i(o,n),i(o,r),o}}function s(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function u(e,t){var n=t.bind(e);return n}function l(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var n=e.__reactAutoBindMap[t];e[t]=u(e,d.guard(n,e.constructor.displayName+"."+t))}}var c=e(39),p=(e(45),e(61)),d=e(64),f=e(71),h=e(72),m=(e(83),e(82),e(96)),v=e(29),g=e(147),y=e(153),C=e(154),E=(e(166),C({mixins:null})),b=y({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),_=[],x={mixins:b.DEFINE_MANY,statics:b.DEFINE_MANY,propTypes:b.DEFINE_MANY,contextTypes:b.DEFINE_MANY,childContextTypes:b.DEFINE_MANY,getDefaultProps:b.DEFINE_MANY_MERGED,getInitialState:b.DEFINE_MANY_MERGED,getChildContext:b.DEFINE_MANY_MERGED,render:b.DEFINE_ONCE,componentWillMount:b.DEFINE_MANY,componentDidMount:b.DEFINE_MANY,componentWillReceiveProps:b.DEFINE_MANY,shouldComponentUpdate:b.DEFINE_ONCE,componentWillUpdate:b.DEFINE_MANY,componentDidUpdate:b.DEFINE_MANY,componentWillUnmount:b.DEFINE_MANY,updateComponent:b.OVERRIDE_BASE},D={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)r(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=v({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=v({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps=e.getDefaultProps?a(e.getDefaultProps,t):t},propTypes:function(e,t){e.propTypes=v({},e.propTypes,t)},statics:function(e,t){o(e,t)}},M={replaceState:function(e,t){m.enqueueReplaceState(this,e),t&&m.enqueueCallback(this,t)},isMounted:function(){var e=f.get(this);return e&&e!==h.currentlyMountingInstance},setProps:function(e,t){m.enqueueSetProps(this,e),t&&m.enqueueCallback(this,t)},replaceProps:function(e,t){m.enqueueReplaceProps(this,e),t&&m.enqueueCallback(this,t)}},T=function(){};v(T.prototype,c.prototype,M);var N={createClass:function(e){var t=function(e,t){this.__reactAutoBindMap&&l(this),this.props=e,this.context=t,this.state=null;var n=this.getInitialState?this.getInitialState():null;g("object"==typeof n&&!Array.isArray(n)),this.state=n};t.prototype=new T,t.prototype.constructor=t,_.forEach(r.bind(null,t)),r(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),g(t.prototype.render);for(var n in x)t.prototype[n]||(t.prototype[n]=null);return t.type=t,t},injection:{injectMixin:function(e){_.push(e)}}};t.exports=N},{147:147,153:153,154:154,166:166,29:29,39:39,45:45,61:61,64:64,71:71,72:72,82:82,83:83,96:96}],39:[function(e,t){"use strict";function n(e,t){this.props=e,this.context=t}{var r=e(96),o=e(147);e(166)}n.prototype.setState=function(e,t){o("object"==typeof e||"function"==typeof e||null==e),r.enqueueSetState(this,e),t&&r.enqueueCallback(this,t)},n.prototype.forceUpdate=function(e){r.enqueueForceUpdate(this),e&&r.enqueueCallback(this,e)};t.exports=n},{147:147,166:166,96:96}],40:[function(e,t){"use strict";var n=e(50),r=e(75),o={processChildrenUpdates:n.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:n.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){r.purgeID(e)}};t.exports=o},{50:50,75:75}],41:[function(e,t){"use strict";var n=e(147),r=!1,o={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){n(!r),o.unmountIDFromEnvironment=e.unmountIDFromEnvironment,o.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,o.processChildrenUpdates=e.processChildrenUpdates,r=!0}}};t.exports=o},{147:147}],42:[function(e,t){"use strict";var n=e(161),r={shouldComponentUpdate:function(e,t){return!n(this.props,e)||!n(this.state,t)}};t.exports=r},{161:161}],43:[function(e,t){"use strict";function n(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}var r=e(41),o=e(44),i=e(45),a=e(61),s=(e(62),e(71)),u=e(72),l=e(78),c=e(80),p=e(83),d=(e(82),e(87)),f=e(97),h=e(29),m=e(127),v=e(147),g=e(162),y=(e(166),1),C={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._isTopLevel=!1,this._pendingCallbacks=null},mountComponent:function(e,t,n){this._context=n,this._mountOrder=y++,this._rootNodeID=e;var r=this._processProps(this._currentElement.props),o=this._processContext(this._currentElement._context),i=l.getComponentClassForElement(this._currentElement),a=new i(r,o);a.props=r,a.context=o,a.refs=m,this._instance=a,s.set(a,this);var c=a.state;void 0===c&&(a.state=c=null),v("object"==typeof c&&!Array.isArray(c)),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var p,f=u.currentlyMountingInstance;u.currentlyMountingInstance=this;try{a.componentWillMount&&(a.componentWillMount(),this._pendingStateQueue&&(a.state=this._processPendingState(a.props,a.context))),p=this._renderValidatedComponent()}finally{u.currentlyMountingInstance=f}this._renderedComponent=this._instantiateReactComponent(p,this._currentElement.type);var h=d.mountComponent(this._renderedComponent,e,t,this._processChildContext(n));return a.componentDidMount&&t.getReactMountReady().enqueue(a.componentDidMount,a),h},unmountComponent:function(){var e=this._instance;if(e.componentWillUnmount){var t=u.currentlyUnmountingInstance;u.currentlyUnmountingInstance=this;try{e.componentWillUnmount()}finally{u.currentlyUnmountingInstance=t}}d.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,s.remove(e)},_setPropsInternal:function(e,t){var n=this._pendingElement||this._currentElement;this._pendingElement=a.cloneAndReplaceProps(n,h({},n.props,e)),f.enqueueUpdate(this,t)},_maskContext:function(e){var t=null;if("string"==typeof this._currentElement.type)return m;var n=this._currentElement.type.contextTypes;if(!n)return m;t={};for(var r in n)t[r]=e[r];return t},_processContext:function(e){var t=this._maskContext(e);return t},_processChildContext:function(e){var t=this._instance,n=t.getChildContext&&t.getChildContext();if(n){v("object"==typeof t.constructor.childContextTypes);for(var r in n)v(r in t.constructor.childContextTypes);return h({},e,n)}return e},_processProps:function(e){return e},_checkPropTypes:function(e,t,r){var o=this.getName();for(var i in e)if(e.hasOwnProperty(i)){var a;try{v("function"==typeof e[i]),a=e[i](t,i,o,r)}catch(s){a=s}a instanceof Error&&(n(this),r===p.prop)}},receiveComponent:function(e,t,n){var r=this._currentElement,o=this._context;this._pendingElement=null,this.updateComponent(t,r,e,o,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&d.receiveComponent(this,this._pendingElement||this._currentElement,e,this._context),(null!==this._pendingStateQueue||this._pendingForceUpdate)&&this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context)},_warnIfContextsDiffer:function(e,t){e=this._maskContext(e),t=this._maskContext(t);for(var n=Object.keys(t).sort(),r=(this.getName()||"ReactCompositeComponent",0);r<n.length;r++)n[r]},updateComponent:function(e,t,n,r,o){var i=this._instance,a=i.context,s=i.props;t!==n&&(a=this._processContext(n._context),s=this._processProps(n.props),i.componentWillReceiveProps&&i.componentWillReceiveProps(s,a));var u=this._processPendingState(s,a),l=this._pendingForceUpdate||!i.shouldComponentUpdate||i.shouldComponentUpdate(s,u,a);l?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,s,u,a,e,o)):(this._currentElement=n,this._context=o,i.props=s,i.state=u,i.context=a)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,o=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;for(var i=h({},o?r[0]:n.state),a=o?1:0;a<r.length;a++){var s=r[a];h(i,"function"==typeof s?s.call(n,i,e,t):s)}return i},_performComponentUpdate:function(e,t,n,r,o,i){var a=this._instance,s=a.props,u=a.state,l=a.context;a.componentWillUpdate&&a.componentWillUpdate(t,n,r),this._currentElement=e,this._context=i,a.props=t,a.state=n,a.context=r,this._updateRenderedComponent(o,i),a.componentDidUpdate&&o.getReactMountReady().enqueue(a.componentDidUpdate.bind(a,s,u,l),a)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent();if(g(r,o))d.receiveComponent(n,o,e,this._processChildContext(t));else{var i=this._rootNodeID,a=n._rootNodeID;d.unmountComponent(n),this._renderedComponent=this._instantiateReactComponent(o,this._currentElement.type);var s=d.mountComponent(this._renderedComponent,i,e,t);this._replaceNodeWithMarkupByID(a,s)}},_replaceNodeWithMarkupByID:function(e,t){r.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,t=e.render();return t},_renderValidatedComponent:function(){var e,t=o.current;o.current=this._processChildContext(this._currentElement._context),i.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{o.current=t,i.current=null}return v(null===e||e===!1||a.isValidElement(e)),e},attachRef:function(e,t){var n=this.getPublicInstance(),r=n.refs===m?n.refs={}:n.refs;r[e]=t.getPublicInstance()},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){return this._instance},_instantiateReactComponent:null};c.measureMethods(C,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var E={Mixin:C};t.exports=E},{127:127,147:147,162:162,166:166,29:29,41:41,44:44,45:45,61:61,62:62,71:71,72:72,78:78,80:80,82:82,83:83,87:87,97:97}],44:[function(e,t){"use strict";var n=e(29),r=e(127),o=(e(166),{current:r,withContext:function(e,t){var r,i=o.current;o.current=n({},i,e);try{r=t()}finally{o.current=i}return r}});t.exports=o},{127:127,166:166,29:29}],45:[function(e,t){"use strict";var n={current:null};t.exports=n},{}],46:[function(e,t){"use strict";function n(e){return r.createFactory(e)}var r=e(61),o=(e(62),e(155)),i=o({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta",meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script",section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong",style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time",title:"title",tr:"tr",track:"track",u:"u",ul:"ul","var":"var",video:"video",wbr:"wbr",circle:"circle",defs:"defs",ellipse:"ellipse",g:"g",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},n);t.exports=i},{155:155,61:61,62:62}],47:[function(e,t){"use strict";var n=e(2),r=e(32),o=e(38),i=e(61),a=e(153),s=i.createFactory("button"),u=a({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),l=o.createClass({displayName:"ReactDOMButton",tagName:"BUTTON",mixins:[n,r],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&u[t]||(e[t]=this.props[t]);return s(e,this.props.children)}});t.exports=l},{153:153,2:2,32:32,38:38,61:61}],48:[function(e,t){"use strict";function n(e){e&&(null!=e.dangerouslySetInnerHTML&&(v(null==e.children),v(null!=e.dangerouslySetInnerHTML.__html)),v(null==e.style||"object"==typeof e.style))}function r(e,t,n,r){var o=p.findReactContainerForID(e);if(o){var i=o.nodeType===x?o.ownerDocument:o;C(t,i)}r.getPutListenerQueue().enqueuePutListener(e,t,n)}function o(e){P.call(N,e)||(v(T.test(e)),N[e]=!0)}function i(e){o(e),this._tag=e,this._renderedChildren=null,this._previousStyleCopy=null,this._rootNodeID=null}var a=e(6),s=e(11),u=e(12),l=e(33),c=e(40),p=e(75),d=e(76),f=e(80),h=e(29),m=e(128),v=e(147),g=(e(148),e(154)),y=(e(166),l.deleteListener),C=l.listenTo,E=l.registrationNameModules,b={string:!0,number:!0},_=g({style:null}),x=1,D=null,M={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},T=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,N={},P={}.hasOwnProperty;i.displayName="ReactDOMComponent",i.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,t,r){this._rootNodeID=e,n(this._currentElement.props);var o=M[this._tag]?"":"</"+this._tag+">";return this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t,r)+o},_createOpenTagMarkupAndPutListeners:function(e){var t=this._currentElement.props,n="<"+this._tag;for(var o in t)if(t.hasOwnProperty(o)){var i=t[o];if(null!=i)if(E.hasOwnProperty(o))r(this._rootNodeID,o,i,e);else{o===_&&(i&&(i=this._previousStyleCopy=h({},t.style)),i=a.createMarkupForStyles(i));var s=u.createMarkupForProperty(o,i);s&&(n+=" "+s)}}if(e.renderToStaticMarkup)return n+">";var l=u.createMarkupForID(this._rootNodeID);return n+" "+l+">"},_createContentMarkup:function(e,t){var n="";("listing"===this._tag||"pre"===this._tag||"textarea"===this._tag)&&(n="\n");var r=this._currentElement.props,o=r.dangerouslySetInnerHTML;if(null!=o){if(null!=o.__html)return n+o.__html}else{var i=b[typeof r.children]?r.children:null,a=null!=i?null:r.children;if(null!=i)return n+m(i);if(null!=a){var s=this.mountChildren(a,e,t);return n+s.join("")}}return n},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,r,o){n(this._currentElement.props),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e,o)},_updateDOMProperties:function(e,t){var n,o,i,a=this._currentElement.props;for(n in e)if(!a.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===_){var u=this._previousStyleCopy;for(o in u)u.hasOwnProperty(o)&&(i=i||{},i[o]="")}else E.hasOwnProperty(n)?y(this._rootNodeID,n):(s.isStandardName[n]||s.isCustomAttribute(n))&&D.deletePropertyByID(this._rootNodeID,n);for(n in a){var l=a[n],c=n===_?this._previousStyleCopy:e[n];if(a.hasOwnProperty(n)&&l!==c)if(n===_)if(l&&(l=this._previousStyleCopy=h({},l)),c){for(o in c)!c.hasOwnProperty(o)||l&&l.hasOwnProperty(o)||(i=i||{},i[o]="");for(o in l)l.hasOwnProperty(o)&&c[o]!==l[o]&&(i=i||{},i[o]=l[o])}else i=l;else E.hasOwnProperty(n)?r(this._rootNodeID,n,l,t):(s.isStandardName[n]||s.isCustomAttribute(n))&&D.updatePropertyByID(this._rootNodeID,n,l)}i&&D.updateStylesByID(this._rootNodeID,i)},_updateDOMChildren:function(e,t,n){var r=this._currentElement.props,o=b[typeof e.children]?e.children:null,i=b[typeof r.children]?r.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,s=r.dangerouslySetInnerHTML&&r.dangerouslySetInnerHTML.__html,u=null!=o?null:e.children,l=null!=i?null:r.children,c=null!=o||null!=a,p=null!=i||null!=s;null!=u&&null==l?this.updateChildren(null,t,n):c&&!p&&this.updateTextContent(""),null!=i?o!==i&&this.updateTextContent(""+i):null!=s?a!==s&&D.updateInnerHTMLByID(this._rootNodeID,s):null!=l&&this.updateChildren(l,t,n)},unmountComponent:function(){this.unmountChildren(),l.deleteAllListeners(this._rootNodeID),c.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null}},f.measureMethods(i,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),h(i.prototype,i.Mixin,d.Mixin),i.injection={injectIDOperations:function(e){i.BackendIDOperations=D=e}},t.exports=i},{11:11,12:12,128:128,147:147,148:148,154:154,166:166,29:29,33:33,40:40,6:6,75:75,76:76,80:80}],49:[function(e,t){"use strict";var n=e(16),r=e(27),o=e(32),i=e(38),a=e(61),s=a.createFactory("form"),u=i.createClass({displayName:"ReactDOMForm",tagName:"FORM",mixins:[o,r],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topReset,"reset"),this.trapBubbledEvent(n.topLevelTypes.topSubmit,"submit")}});t.exports=u},{16:16,27:27,32:32,38:38,61:61}],50:[function(e,t){"use strict";var n=e(6),r=e(10),o=e(12),i=e(75),a=e(80),s=e(147),u=e(159),l={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},c={updatePropertyByID:function(e,t,n){var r=i.getNode(e);s(!l.hasOwnProperty(t)),null!=n?o.setValueForProperty(r,t,n):o.deleteValueForProperty(r,t)},deletePropertyByID:function(e,t,n){var r=i.getNode(e);s(!l.hasOwnProperty(t)),o.deleteValueForProperty(r,t,n)},updateStylesByID:function(e,t){var r=i.getNode(e);n.setValueForStyles(r,t)},updateInnerHTMLByID:function(e,t){var n=i.getNode(e);u(n,t)},updateTextContentByID:function(e,t){var n=i.getNode(e);r.updateTextContent(n,t)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=i.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=i.getNode(e[n].parentID);r.processUpdates(e,t)}};a.measureMethods(c,"ReactDOMIDOperations",{updatePropertyByID:"updatePropertyByID",deletePropertyByID:"deletePropertyByID",updateStylesByID:"updateStylesByID",updateInnerHTMLByID:"updateInnerHTMLByID",updateTextContentByID:"updateTextContentByID",dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),t.exports=c},{10:10,12:12,147:147,159:159,6:6,75:75,80:80}],51:[function(e,t){"use strict";var n=e(16),r=e(27),o=e(32),i=e(38),a=e(61),s=a.createFactory("iframe"),u=i.createClass({displayName:"ReactDOMIframe",tagName:"IFRAME",mixins:[o,r],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topLoad,"load")}});t.exports=u},{16:16,27:27,32:32,38:38,61:61}],52:[function(e,t){"use strict";var n=e(16),r=e(27),o=e(32),i=e(38),a=e(61),s=a.createFactory("img"),u=i.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[o,r],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topLoad,"load"),this.trapBubbledEvent(n.topLevelTypes.topError,"error")}});t.exports=u},{16:16,27:27,32:32,38:38,61:61}],53:[function(e,t){"use strict";function n(){this.isMounted()&&this.forceUpdate()}var r=e(2),o=e(12),i=e(26),a=e(32),s=e(38),u=e(61),l=e(75),c=e(97),p=e(29),d=e(147),f=u.createFactory("input"),h={},m=s.createClass({displayName:"ReactDOMInput",tagName:"INPUT",mixins:[r,i.Mixin,a],getInitialState:function(){var e=this.props.defaultValue;return{initialChecked:this.props.defaultChecked||!1,initialValue:null!=e?e:null}},render:function(){var e=p({},this.props);e.defaultChecked=null,e.defaultValue=null;var t=i.getValue(this);e.value=null!=t?t:this.state.initialValue;var n=i.getChecked(this);return e.checked=null!=n?n:this.state.initialChecked,e.onChange=this._handleChange,f(e,this.props.children)},componentDidMount:function(){var e=l.getID(this.getDOMNode());h[e]=this},componentWillUnmount:function(){var e=this.getDOMNode(),t=l.getID(e);delete h[t]},componentDidUpdate:function(){var e=this.getDOMNode();null!=this.props.checked&&o.setValueForProperty(e,"checked",this.props.checked||!1);var t=i.getValue(this);null!=t&&o.setValueForProperty(e,"value",""+t)},_handleChange:function(e){var t,r=i.getOnChange(this);r&&(t=r.call(this,e)),c.asap(n,this);var o=this.props.name;if("radio"===this.props.type&&null!=o){for(var a=this.getDOMNode(),s=a;s.parentNode;)s=s.parentNode;for(var u=s.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),p=0,f=u.length;f>p;p++){var m=u[p];if(m!==a&&m.form===a.form){var v=l.getID(m);d(v);var g=h[v];d(g),c.asap(n,g)}}}return t}});t.exports=m},{12:12,147:147,2:2,26:26,29:29,32:32,38:38,61:61,75:75,97:97}],54:[function(e,t){"use strict";var n=e(32),r=e(38),o=e(61),i=(e(166),o.createFactory("option")),a=r.createClass({displayName:"ReactDOMOption",tagName:"OPTION",mixins:[n],componentWillMount:function(){},render:function(){return i(this.props,this.props.children)}});t.exports=a},{166:166,32:32,38:38,61:61}],55:[function(e,t){"use strict";function n(){if(this._pendingUpdate){this._pendingUpdate=!1;var e=a.getValue(this);null!=e&&this.isMounted()&&o(this,e)}}function r(e,t){if(null==e[t])return null;if(e.multiple){if(!Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be an array if `multiple` is true.")}else if(Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be a scalar value if `multiple` is false.")}function o(e,t){var n,r,o,i=e.getDOMNode().options;if(e.props.multiple){for(n={},r=0,o=t.length;o>r;r++)n[""+t[r]]=!0;for(r=0,o=i.length;o>r;r++){var a=n.hasOwnProperty(i[r].value);i[r].selected!==a&&(i[r].selected=a)}}else{for(n=""+t,r=0,o=i.length;o>r;r++)if(i[r].value===n)return void(i[r].selected=!0);i[0].selected=!0}}var i=e(2),a=e(26),s=e(32),u=e(38),l=e(61),c=e(97),p=e(29),d=l.createFactory("select"),f=u.createClass({displayName:"ReactDOMSelect",tagName:"SELECT",mixins:[i,a.Mixin,s],propTypes:{defaultValue:r,value:r},render:function(){var e=p({},this.props);return e.onChange=this._handleChange,e.value=null,d(e,this.props.children)},componentWillMount:function(){this._pendingUpdate=!1},componentDidMount:function(){var e=a.getValue(this);null!=e?o(this,e):null!=this.props.defaultValue&&o(this,this.props.defaultValue)},componentDidUpdate:function(e){var t=a.getValue(this);null!=t?(this._pendingUpdate=!1,o(this,t)):!e.multiple!=!this.props.multiple&&(null!=this.props.defaultValue?o(this,this.props.defaultValue):o(this,this.props.multiple?[]:""))},_handleChange:function(e){var t,r=a.getOnChange(this);return r&&(t=r.call(this,e)),this._pendingUpdate=!0,c.asap(n,this),t}});t.exports=f},{2:2,26:26,29:29,32:32,38:38,61:61,97:97}],56:[function(e,t){"use strict";function n(e,t,n,r){return e===n&&t===r}function r(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length,a=i+r;return{start:i,end:a}}function o(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var r=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,s=t.getRangeAt(0),u=n(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),l=u?0:s.toString().length,c=s.cloneRange();c.selectNodeContents(e),c.setEnd(s.startContainer,s.startOffset);var p=n(c.startContainer,c.startOffset,c.endContainer,c.endOffset),d=p?0:c.toString().length,f=d+l,h=document.createRange();h.setStart(r,o),h.setEnd(i,a);var m=h.collapsed;return{start:m?f:d,end:m?d:f}}function i(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function a(e,t){if(window.getSelection){var n=window.getSelection(),r=e[l()].length,o=Math.min(t.start,r),i="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var s=u(e,o),c=u(e,i);if(s&&c){var p=document.createRange();p.setStart(s.node,s.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(c.node,c.offset)):(p.setEnd(c.node,c.offset),n.addRange(p))}}}var s=e(22),u=e(140),l=e(142),c=s.canUseDOM&&"selection"in document&&!("getSelection"in window),p={getOffsets:c?r:o,setOffsets:c?i:a};t.exports=p},{140:140,142:142,22:22}],57:[function(e,t){"use strict";var n=e(12),r=e(40),o=e(48),i=e(29),a=e(128),s=function(){};i(s.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,t){this._rootNodeID=e;var r=a(this._stringText);return t.renderToStaticMarkup?r:"<span "+n.createMarkupForID(e)+">"+r+"</span>"},receiveComponent:function(e){if(e!==this._currentElement){this._currentElement=e;var t=""+e;t!==this._stringText&&(this._stringText=t,o.BackendIDOperations.updateTextContentByID(this._rootNodeID,t))}},unmountComponent:function(){r.unmountIDFromEnvironment(this._rootNodeID)}}),t.exports=s},{12:12,128:128,29:29,40:40,48:48}],58:[function(e,t){"use strict";function n(){this.isMounted()&&this.forceUpdate()}var r=e(2),o=e(12),i=e(26),a=e(32),s=e(38),u=e(61),l=e(97),c=e(29),p=e(147),d=(e(166),u.createFactory("textarea")),f=s.createClass({displayName:"ReactDOMTextarea",tagName:"TEXTAREA",mixins:[r,i.Mixin,a],getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;null!=t&&(p(null==e),Array.isArray(t)&&(p(t.length<=1),t=t[0]),e=""+t),null==e&&(e="");var n=i.getValue(this);return{initialValue:""+(null!=n?n:e)}
},render:function(){var e=c({},this.props);return p(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null,e.onChange=this._handleChange,d(e,this.state.initialValue)},componentDidUpdate:function(){var e=i.getValue(this);if(null!=e){var t=this.getDOMNode();o.setValueForProperty(t,"value",""+e)}},_handleChange:function(e){var t,r=i.getOnChange(this);return r&&(t=r.call(this,e)),l.asap(n,this),t}});t.exports=f},{12:12,147:147,166:166,2:2,26:26,29:29,32:32,38:38,61:61,97:97}],59:[function(e,t){"use strict";function n(){this.reinitializeTransaction()}var r=e(97),o=e(113),i=e(29),a=e(126),s={initialize:a,close:function(){p.isBatchingUpdates=!1}},u={initialize:a,close:r.flushBatchedUpdates.bind(r)},l=[u,s];i(n.prototype,o.Mixin,{getTransactionWrappers:function(){return l}});var c=new n,p={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o){var i=p.isBatchingUpdates;p.isBatchingUpdates=!0,i?e(t,n,r,o):c.perform(e,null,t,n,r,o)}};t.exports=p},{113:113,126:126,29:29,97:97}],60:[function(e,t){"use strict";function n(e){return f.createClass({tagName:e.toUpperCase(),render:function(){return new N(e,null,null,null,null,this.props)}})}function r(){I.EventEmitter.injectReactEventListener(P),I.EventPluginHub.injectEventPluginOrder(s),I.EventPluginHub.injectInstanceHandle(R),I.EventPluginHub.injectMount(w),I.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:k,EnterLeaveEventPlugin:u,ChangeEventPlugin:i,MobileSafariClickEventPlugin:p,SelectEventPlugin:S,BeforeInputEventPlugin:o}),I.NativeComponent.injectGenericComponentClass(v),I.NativeComponent.injectTextComponentClass(T),I.NativeComponent.injectAutoWrapper(n),I.Class.injectMixin(d),I.NativeComponent.injectComponentClasses({button:g,form:y,iframe:b,img:C,input:_,option:x,select:D,textarea:M,html:U("html"),head:U("head"),body:U("body")}),I.DOMProperty.injectDOMPropertyConfig(c),I.DOMProperty.injectDOMPropertyConfig(L),I.EmptyComponent.injectEmptyComponent("noscript"),I.Updates.injectReconcileTransaction(O),I.Updates.injectBatchingStrategy(m),I.RootIndex.injectCreateReactRootIndex(l.canUseDOM?a.createReactRootIndex:A.createReactRootIndex),I.Component.injectEnvironment(h),I.DOMComponent.injectIDOperations(E)}var o=e(3),i=e(8),a=e(9),s=e(14),u=e(15),l=e(22),c=e(24),p=e(28),d=e(32),f=e(38),h=e(40),m=e(59),v=e(48),g=e(47),y=e(49),C=e(52),E=e(50),b=e(51),_=e(53),x=e(54),D=e(55),M=e(58),T=e(57),N=e(61),P=e(66),I=e(68),R=e(70),w=e(75),O=e(86),S=e(99),A=e(100),k=e(101),L=e(98),U=e(122);t.exports={inject:r}},{100:100,101:101,122:122,14:14,15:15,22:22,24:24,28:28,3:3,32:32,38:38,40:40,47:47,48:48,49:49,50:50,51:51,52:52,53:53,54:54,55:55,57:57,58:58,59:59,61:61,66:66,68:68,70:70,75:75,8:8,86:86,9:9,98:98,99:99}],61:[function(e,t){"use strict";var n=e(44),r=e(45),o=e(29),i=(e(166),{key:!0,ref:!0}),a=function(e,t,n,r,o,i){this.type=e,this.key=t,this.ref=n,this._owner=r,this._context=o,this.props=i};a.prototype={_isReactElement:!0},a.createElement=function(e,t,o){var s,u={},l=null,c=null;if(null!=t){c=void 0===t.ref?null:t.ref,l=void 0===t.key?null:""+t.key;for(s in t)t.hasOwnProperty(s)&&!i.hasOwnProperty(s)&&(u[s]=t[s])}var p=arguments.length-2;if(1===p)u.children=o;else if(p>1){for(var d=Array(p),f=0;p>f;f++)d[f]=arguments[f+2];u.children=d}if(e&&e.defaultProps){var h=e.defaultProps;for(s in h)"undefined"==typeof u[s]&&(u[s]=h[s])}return new a(e,l,c,r.current,n.current,u)},a.createFactory=function(e){var t=a.createElement.bind(null,e);return t.type=e,t},a.cloneAndReplaceProps=function(e,t){var n=new a(e.type,e.key,e.ref,e._owner,e._context,t);return n},a.cloneElement=function(e,t,n){var s,u=o({},e.props),l=e.key,c=e.ref,p=e._owner;if(null!=t){void 0!==t.ref&&(c=t.ref,p=r.current),void 0!==t.key&&(l=""+t.key);for(s in t)t.hasOwnProperty(s)&&!i.hasOwnProperty(s)&&(u[s]=t[s])}var d=arguments.length-2;if(1===d)u.children=n;else if(d>1){for(var f=Array(d),h=0;d>h;h++)f[h]=arguments[h+2];u.children=f}return new a(e.type,l,c,p,e._context,u)},a.isValidElement=function(e){var t=!(!e||!e._isReactElement);return t},t.exports=a},{166:166,29:29,44:44,45:45}],62:[function(e,t){"use strict";function n(){if(g.current){var e=g.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function r(e){var t=e&&e.getPublicInstance();if(!t)return void 0;var n=t.constructor;return n?n.displayName||n.name||void 0:void 0}function o(){var e=g.current;return e&&r(e)||void 0}function i(e,t){e._store.validated||null!=e.key||(e._store.validated=!0,s('Each child in an array or iterator should have a unique "key" prop.',e,t))}function a(e,t,n){x.test(e)&&s("Child objects should have non-numeric keys so ordering is preserved.",t,n)}function s(e,t,n){var i=o(),a="string"==typeof n?n:n.displayName||n.name,s=i||a,u=b[e]||(b[e]={});if(!u.hasOwnProperty(s)){u[s]=!0;var l="";if(t&&t._owner&&t._owner!==g.current){var c=r(t._owner);l=" It was passed a child from "+c+"."}}}function u(e,t){if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];h.isValidElement(r)&&i(r,t)}else if(h.isValidElement(e))e._store.validated=!0;else if(e){var o=C(e);if(o){if(o!==e.entries)for(var s,u=o.call(e);!(s=u.next()).done;)h.isValidElement(s.value)&&i(s.value,t)}else if("object"==typeof e){var l=m.extractIfFragment(e);for(var c in l)l.hasOwnProperty(c)&&a(c,l[c],t)}}}function l(e,t,r,o){for(var i in t)if(t.hasOwnProperty(i)){var a;try{E("function"==typeof t[i]),a=t[i](r,i,e,o)}catch(s){a=s}a instanceof Error&&!(a.message in _)&&(_[a.message]=!0,n(this))}}function c(e,t){var n=t.type,r="string"==typeof n?n:n.displayName,o=t._owner?t._owner.getPublicInstance().constructor.displayName:null,i=e+"|"+r+"|"+o;if(!D.hasOwnProperty(i)){D[i]=!0;var a="";r&&(a=" <"+r+" />");var s="";o&&(s=" The element was created by "+o+".")}}function p(e,t){return e!==e?t!==t:0===e&&0===t?1/e===1/t:e===t}function d(e){if(e._store){var t=e._store.originalProps,n=e.props;for(var r in n)n.hasOwnProperty(r)&&(t.hasOwnProperty(r)&&p(t[r],n[r])||(c(r,e),t[r]=n[r]))}}function f(e){if(null!=e.type){var t=y.getComponentClassForElement(e),n=t.displayName||t.name;t.propTypes&&l(n,t.propTypes,e.props,v.prop),"function"==typeof t.getDefaultProps}}var h=e(61),m=e(67),v=e(83),g=(e(82),e(45)),y=e(78),C=e(138),E=e(147),b=(e(166),{}),_={},x=/^\d+$/,D={},M={checkAndWarnForMutatedProps:d,createElement:function(e){var t=h.createElement.apply(this,arguments);if(null==t)return t;for(var n=2;n<arguments.length;n++)u(arguments[n],e);return f(t),t},createFactory:function(e){var t=M.createElement.bind(null,e);return t.type=e,t},cloneElement:function(){for(var e=h.cloneElement.apply(this,arguments),t=2;t<arguments.length;t++)u(arguments[t],e.type);return f(e),e}};t.exports=M},{138:138,147:147,166:166,45:45,61:61,67:67,78:78,82:82,83:83}],63:[function(e,t){"use strict";function n(e){l[e]=!0}function r(e){delete l[e]}function o(e){return!!l[e]}var i,a=e(61),s=e(71),u=e(147),l={},c={injectEmptyComponent:function(e){i=a.createFactory(e)}},p=function(){};p.prototype.componentDidMount=function(){var e=s.get(this);e&&n(e._rootNodeID)},p.prototype.componentWillUnmount=function(){var e=s.get(this);e&&r(e._rootNodeID)},p.prototype.render=function(){return u(i),i()};var d=a.createElement(p),f={emptyElement:d,injection:c,isNullComponentID:o};t.exports=f},{147:147,61:61,71:71}],64:[function(e,t){"use strict";var n={guard:function(e){return e}};t.exports=n},{}],65:[function(e,t){"use strict";function n(e){r.enqueueEvents(e),r.processEventQueue()}var r=e(18),o={handleTopLevel:function(e,t,o,i){var a=r.extractEvents(e,t,o,i);n(a)}};t.exports=o},{18:18}],66:[function(e,t){"use strict";function n(e){var t=c.getID(e),n=l.getReactRootIDFromNodeID(t),r=c.findReactContainerForID(n),o=c.getFirstReactDOM(r);return o}function r(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function o(e){for(var t=c.getFirstReactDOM(f(e.nativeEvent))||window,r=t;r;)e.ancestors.push(r),r=n(r);for(var o=0,i=e.ancestors.length;i>o;o++){t=e.ancestors[o];var a=c.getID(t)||"";m._handleTopLevel(e.topLevelType,t,a,e.nativeEvent)}}function i(e){var t=h(window);e(t)}var a=e(17),s=e(22),u=e(30),l=e(70),c=e(75),p=e(97),d=e(29),f=e(137),h=e(143);d(r.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),u.addPoolingTo(r,u.twoArgumentPooler);var m={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:s.canUseDOM?window:null,setHandleTopLevel:function(e){m._handleTopLevel=e},setEnabled:function(e){m._enabled=!!e},isEnabled:function(){return m._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?a.listen(r,t,m.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var r=n;return r?a.capture(r,t,m.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=i.bind(null,e);a.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(m._enabled){var n=r.getPooled(e,t);try{p.batchedUpdates(o,n)}finally{r.release(n)}}}};t.exports=m},{137:137,143:143,17:17,22:22,29:29,30:30,70:70,75:75,97:97}],67:[function(e,t){"use strict";var n=(e(61),e(166),{create:function(e){return e},extract:function(e){return e},extractIfFragment:function(e){return e}});t.exports=n},{166:166,61:61}],68:[function(e,t){"use strict";var n=e(11),r=e(18),o=e(41),i=e(38),a=e(63),s=e(33),u=e(78),l=e(48),c=e(80),p=e(89),d=e(97),f={Component:o.injection,Class:i.injection,DOMComponent:l.injection,DOMProperty:n.injection,EmptyComponent:a.injection,EventPluginHub:r.injection,EventEmitter:s.injection,NativeComponent:u.injection,Perf:c.injection,RootIndex:p.injection,Updates:d.injection};t.exports=f},{11:11,18:18,33:33,38:38,41:41,48:48,63:63,78:78,80:80,89:89,97:97}],69:[function(e,t){"use strict";function n(e){return o(document.documentElement,e)}var r=e(56),o=e(120),i=e(131),a=e(133),s={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=a();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=a(),r=e.focusedElem,o=e.selectionRange;t!==r&&n(r)&&(s.hasSelectionCapabilities(r)&&s.setSelection(r,o),i(r))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&"INPUT"===e.nodeName){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=r.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,o=t.end;if("undefined"==typeof o&&(o=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(o,e.value.length);else if(document.selection&&"INPUT"===e.nodeName){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",o-n),i.select()}else r.setOffsets(e,t)}};t.exports=s},{120:120,131:131,133:133,56:56}],70:[function(e,t){"use strict";function n(e){return d+e.toString(36)}function r(e,t){return e.charAt(t)===d||t===e.length}function o(e){return""===e||e.charAt(0)===d&&e.charAt(e.length-1)!==d}function i(e,t){return 0===t.indexOf(e)&&r(t,e.length)}function a(e){return e?e.substr(0,e.lastIndexOf(d)):""}function s(e,t){if(p(o(e)&&o(t)),p(i(e,t)),e===t)return e;var n,a=e.length+f;for(n=a;n<t.length&&!r(t,n);n++);return t.substr(0,n)}function u(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var i=0,a=0;n>=a;a++)if(r(e,a)&&r(t,a))i=a;else if(e.charAt(a)!==t.charAt(a))break;var s=e.substr(0,i);return p(o(s)),s}function l(e,t,n,r,o,u){e=e||"",t=t||"",p(e!==t);var l=i(t,e);p(l||i(e,t));for(var c=0,d=l?a:s,f=e;;f=d(f,t)){var m;if(o&&f===e||u&&f===t||(m=n(f,l,r)),m===!1||f===t)break;p(c++<h)}}var c=e(89),p=e(147),d=".",f=d.length,h=100,m={createReactRootID:function(){return n(c.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===d&&e.length>1){var t=e.indexOf(d,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,o){var i=u(e,t);i!==e&&l(e,i,n,r,!1,!0),i!==t&&l(i,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(l("",e,t,n,!0,!1),l(e,"",t,n,!1,!0))},traverseAncestors:function(e,t,n){l("",e,t,n,!0,!1)},_getFirstCommonAncestorID:u,_getNextDescendantID:s,isAncestorIDOf:i,SEPARATOR:d};t.exports=m},{147:147,89:89}],71:[function(e,t){"use strict";var n={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};t.exports=n},{}],72:[function(e,t){"use strict";var n={currentlyMountingInstance:null,currentlyUnmountingInstance:null};t.exports=n},{}],73:[function(e,t){"use strict";function n(e,t){this.value=e,this.requestChange=t}function r(e){var t={value:"undefined"==typeof e?o.PropTypes.any.isRequired:e.isRequired,requestChange:o.PropTypes.func.isRequired};return o.PropTypes.shape(t)}var o=e(31);n.PropTypes={link:r},t.exports=n},{31:31}],74:[function(e,t){"use strict";var n=e(116),r={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=n(e);return e.replace(">"," "+r.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var o=t.getAttribute(r.CHECKSUM_ATTR_NAME);o=o&&parseInt(o,10);var i=n(e);return i===o}};t.exports=r},{116:116}],75:[function(e,t){"use strict";function n(e,t){for(var n=Math.min(e.length,t.length),r=0;n>r;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function r(e){var t=P(e);return t&&W.getID(t)}function o(e){var t=i(e);if(t)if(k.hasOwnProperty(t)){var n=k[t];n!==e&&(R(!l(n,t)),k[t]=e)}else k[t]=e;return t}function i(e){return e&&e.getAttribute&&e.getAttribute(A)||""}function a(e,t){var n=i(e);n!==t&&delete k[n],e.setAttribute(A,t),k[t]=e}function s(e){return k.hasOwnProperty(e)&&l(k[e],e)||(k[e]=W.findReactNodeByID(e)),k[e]}function u(e){var t=E.get(e)._rootNodeID;return y.isNullComponentID(t)?null:(k.hasOwnProperty(t)&&l(k[t],t)||(k[t]=W.findReactNodeByID(t)),k[t])}function l(e,t){if(e){R(i(e)===t);var n=W.findReactContainerForID(t);if(n&&N(n,e))return!0}return!1}function c(e){delete k[e]}function p(e){var t=k[e];return t&&l(t,e)?void(V=t):!1}function d(e){V=null,C.traverseAncestors(e,p);var t=V;return V=null,t}function f(e,t,n,r,o){var i=x.mountComponent(e,t,r,T);e._isTopLevel=!0,W._mountImageIntoNode(i,n,o)}function h(e,t,n,r){var o=M.ReactReconcileTransaction.getPooled();o.perform(f,null,e,t,n,o,r),M.ReactReconcileTransaction.release(o)}var m=e(11),v=e(33),g=(e(45),e(61)),y=(e(62),e(63)),C=e(70),E=e(71),b=e(74),_=e(80),x=e(87),D=e(96),M=e(97),T=e(127),N=e(120),P=e(141),I=e(146),R=e(147),w=e(159),O=e(162),S=(e(166),C.SEPARATOR),A=m.ID_ATTRIBUTE_NAME,k={},L=1,U=9,F={},B={},j=[],V=null,W={_instancesByReactRootID:F,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){return W.scrollMonitor(n,function(){D.enqueueElementInternal(e,t),r&&D.enqueueCallbackInternal(e,r)}),e},_registerComponent:function(e,t){R(t&&(t.nodeType===L||t.nodeType===U)),v.ensureScrollValueMonitoring();var n=W.registerContainer(t);return F[n]=e,n},_renderNewRootComponent:function(e,t,n){var r=I(e,null),o=W._registerComponent(r,t);return M.batchedUpdates(h,r,o,t,n),r},render:function(e,t,n){R(g.isValidElement(e));var o=F[r(t)];if(o){var i=o._currentElement;if(O(i,e))return W._updateRootComponent(o,e,t,n).getPublicInstance();W.unmountComponentAtNode(t)}var a=P(t),s=a&&W.isRenderedByReact(a),u=s&&!o,l=W._renderNewRootComponent(e,t,u).getPublicInstance();return n&&n.call(l),l},constructAndRenderComponent:function(e,t,n){var r=g.createElement(e,t);return W.render(r,n)},constructAndRenderComponentByID:function(e,t,n){var r=document.getElementById(n);return R(r),W.constructAndRenderComponent(e,t,r)},registerContainer:function(e){var t=r(e);return t&&(t=C.getReactRootIDFromNodeID(t)),t||(t=C.createReactRootID()),B[t]=e,t},unmountComponentAtNode:function(e){R(e&&(e.nodeType===L||e.nodeType===U));var t=r(e),n=F[t];return n?(W.unmountComponentFromNode(n,e),delete F[t],delete B[t],!0):!1},unmountComponentFromNode:function(e,t){for(x.unmountComponent(e),t.nodeType===U&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)},findReactContainerForID:function(e){var t=C.getReactRootIDFromNodeID(e),n=B[t];return n},findReactNodeByID:function(e){var t=W.findReactContainerForID(e);return W.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=W.getID(e);return t?t.charAt(0)===S:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(W.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){var n=j,r=0,o=d(t)||e;for(n[0]=o.firstChild,n.length=1;r<n.length;){for(var i,a=n[r++];a;){var s=W.getID(a);s?t===s?i=a:C.isAncestorIDOf(s,t)&&(n.length=r=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,R(!1)},_mountImageIntoNode:function(e,t,r){if(R(t&&(t.nodeType===L||t.nodeType===U)),r){var o=P(t);if(b.canReuseMarkup(e,o))return;var i=o.getAttribute(b.CHECKSUM_ATTR_NAME);o.removeAttribute(b.CHECKSUM_ATTR_NAME);var a=o.outerHTML;o.setAttribute(b.CHECKSUM_ATTR_NAME,i);var s=n(e,a);" (client) "+e.substring(s-20,s+20)+"\n (server) "+a.substring(s-20,s+20),R(t.nodeType!==U)}R(t.nodeType!==U),w(t,e)},getReactRootID:r,getID:o,setID:a,getNode:s,getNodeFromInstance:u,purgeID:c};_.measureMethods(W,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),t.exports=W},{11:11,120:120,127:127,141:141,146:146,147:147,159:159,162:162,166:166,33:33,45:45,61:61,62:62,63:63,70:70,71:71,74:74,80:80,87:87,96:96,97:97}],76:[function(e,t){"use strict";function n(e,t,n){f.push({parentID:e,parentNode:null,type:l.INSERT_MARKUP,markupIndex:h.push(t)-1,textContent:null,fromIndex:null,toIndex:n})}function r(e,t,n){f.push({parentID:e,parentNode:null,type:l.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:t,toIndex:n})}function o(e,t){f.push({parentID:e,parentNode:null,type:l.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:t,toIndex:null})}function i(e,t){f.push({parentID:e,parentNode:null,type:l.TEXT_CONTENT,markupIndex:null,textContent:t,fromIndex:null,toIndex:null})}function a(){f.length&&(u.processChildrenUpdates(f,h),s())}function s(){f.length=0,h.length=0}var u=e(41),l=e(77),c=e(87),p=e(36),d=0,f=[],h=[],m={Mixin:{mountChildren:function(e,t,n){var r=p.instantiateChildren(e,t,n);this._renderedChildren=r;var o=[],i=0;for(var a in r)if(r.hasOwnProperty(a)){var s=r[a],u=this._rootNodeID+a,l=c.mountComponent(s,u,t,n);s._mountIndex=i,o.push(l),i++}return o},updateTextContent:function(e){d++;var t=!0;try{var n=this._renderedChildren;p.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setTextContent(e),t=!1}finally{d--,d||(t?s():a())}},updateChildren:function(e,t,n){d++;var r=!0;try{this._updateChildren(e,t,n),r=!1}finally{d--,d||(r?s():a())}},_updateChildren:function(e,t,n){var r=this._renderedChildren,o=p.updateChildren(r,e,t,n);if(this._renderedChildren=o,o||r){var i,a=0,s=0;for(i in o)if(o.hasOwnProperty(i)){var u=r&&r[i],l=o[i];u===l?(this.moveChild(u,s,a),a=Math.max(u._mountIndex,a),u._mountIndex=s):(u&&(a=Math.max(u._mountIndex,a),this._unmountChildByName(u,i)),this._mountChildByNameAtIndex(l,i,s,t,n)),s++}for(i in r)!r.hasOwnProperty(i)||o&&o.hasOwnProperty(i)||this._unmountChildByName(r[i],i)}},unmountChildren:function(){var e=this._renderedChildren;p.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&r(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){n(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){o(this._rootNodeID,e._mountIndex)},setTextContent:function(e){i(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r,o){var i=this._rootNodeID+t,a=c.mountComponent(e,i,r,o);e._mountIndex=n,this.createChild(e,a)},_unmountChildByName:function(e){this.removeChild(e),e._mountIndex=null}}};t.exports=m},{36:36,41:41,77:77,87:87}],77:[function(e,t){"use strict";var n=e(153),r=n({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});t.exports=r},{153:153}],78:[function(e,t){"use strict";function n(e){if("function"==typeof e.type)return e.type;var t=e.type,n=c[t];return null==n&&(c[t]=n=u(t)),n}function r(e){return s(l),new l(e.type,e.props)}function o(e){return new p(e)}function i(e){return e instanceof p}var a=e(29),s=e(147),u=null,l=null,c={},p=null,d={injectGenericComponentClass:function(e){l=e},injectTextComponentClass:function(e){p=e},injectComponentClasses:function(e){a(c,e)},injectAutoWrapper:function(e){u=e}},f={getComponentClassForElement:n,createInternalComponent:r,createInstanceForText:o,isTextComponent:i,injection:d};t.exports=f},{147:147,29:29}],79:[function(e,t){"use strict";var n=e(147),r={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,o){n(r.isValidOwner(o)),o.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,o){n(r.isValidOwner(o)),o.getPublicInstance().refs[t]===e.getPublicInstance()&&o.detachRef(t)}};t.exports=r},{147:147}],80:[function(e,t){"use strict";function n(e,t,n){return n}var r={enableMeasure:!1,storedMeasure:n,measureMethods:function(){},measure:function(e,t,n){return n},injection:{injectMeasure:function(e){r.storedMeasure=e}}};t.exports=r},{}],81:[function(e,t){"use strict";function n(e){return function(t,n,r){t[n]=t.hasOwnProperty(n)?e(t[n],r):r}}function r(e,t){for(var n in t)if(t.hasOwnProperty(n)){var r=u[n];r&&u.hasOwnProperty(n)?r(e,n,t[n]):e.hasOwnProperty(n)||(e[n]=t[n])}return e}var o=e(29),i=e(126),a=e(152),s=n(function(e,t){return o({},t,e)}),u={children:i,className:n(a),style:s},l={mergeProps:function(e,t){return r(o({},e),t)}};t.exports=l},{126:126,152:152,29:29}],82:[function(e,t){"use strict";var n={};t.exports=n},{}],83:[function(e,t){"use strict";var n=e(153),r=n({prop:null,context:null,childContext:null});t.exports=r},{153:153}],84:[function(e,t){"use strict";function n(e){function t(t,n,r,o,i){if(o=o||E,null==n[r]){var a=y[i];return t?new Error("Required "+a+" `"+r+"` was not specified in "+("`"+o+"`.")):null}return e(n,r,o,i)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function r(e){function t(t,n,r,o){var i=t[n],a=h(i);if(a!==e){var s=y[o],u=m(i);return new Error("Invalid "+s+" `"+n+"` of type `"+u+"` "+("supplied to `"+r+"`, expected `"+e+"`."))}return null}return n(t)}function o(){return n(C.thatReturns(null))}function i(e){function t(t,n,r,o){var i=t[n];if(!Array.isArray(i)){var a=y[o],s=h(i);return new Error("Invalid "+a+" `"+n+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an array."))}for(var u=0;u<i.length;u++){var l=e(i,u,r,o);if(l instanceof Error)return l}return null}return n(t)}function a(){function e(e,t,n,r){if(!v.isValidElement(e[t])){var o=y[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactElement."))}return null}return n(e)}function s(e){function t(t,n,r,o){if(!(t[n]instanceof e)){var i=y[o],a=e.name||E;return new Error("Invalid "+i+" `"+n+"` supplied to "+("`"+r+"`, expected instance of `"+a+"`."))}return null}return n(t)}function u(e){function t(t,n,r,o){for(var i=t[n],a=0;a<e.length;a++)if(i===e[a])return null;var s=y[o],u=JSON.stringify(e);return new Error("Invalid "+s+" `"+n+"` of value `"+i+"` "+("supplied to `"+r+"`, expected one of "+u+"."))}return n(t)}function l(e){function t(t,n,r,o){var i=t[n],a=h(i);if("object"!==a){var s=y[o];return new Error("Invalid "+s+" `"+n+"` of type "+("`"+a+"` supplied to `"+r+"`, expected an object."))}for(var u in i)if(i.hasOwnProperty(u)){var l=e(i,u,r,o);if(l instanceof Error)return l}return null}return n(t)}function c(e){function t(t,n,r,o){for(var i=0;i<e.length;i++){var a=e[i];if(null==a(t,n,r,o))return null}var s=y[o];return new Error("Invalid "+s+" `"+n+"` supplied to "+("`"+r+"`."))}return n(t)}function p(){function e(e,t,n,r){if(!f(e[t])){var o=y[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return n(e)}function d(e){function t(t,n,r,o){var i=t[n],a=h(i);if("object"!==a){var s=y[o];return new Error("Invalid "+s+" `"+n+"` of type `"+a+"` "+("supplied to `"+r+"`, expected `object`."))}for(var u in e){var l=e[u];if(l){var c=l(i,u,r,o);if(c)return c}}return null}return n(t)}function f(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(f);if(null===e||v.isValidElement(e))return!0;e=g.extractIfFragment(e);for(var t in e)if(!f(e[t]))return!1;return!0;default:return!1}}function h(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function m(e){var t=h(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}var v=e(61),g=e(67),y=e(82),C=e(126),E="<<anonymous>>",b=a(),_=p(),x={array:r("array"),bool:r("boolean"),func:r("function"),number:r("number"),object:r("object"),string:r("string"),any:o(),arrayOf:i,element:b,instanceOf:s,node:_,objectOf:l,oneOf:u,oneOfType:c,shape:d};t.exports=x},{126:126,61:61,67:67,82:82}],85:[function(e,t){"use strict";function n(){this.listenersToPut=[]}var r=e(30),o=e(33),i=e(29);i(n.prototype,{enqueuePutListener:function(e,t,n){this.listenersToPut.push({rootNodeID:e,propKey:t,propValue:n})},putListeners:function(){for(var e=0;e<this.listenersToPut.length;e++){var t=this.listenersToPut[e];o.putListener(t.rootNodeID,t.propKey,t.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n},{29:29,30:30,33:33}],86:[function(e,t){"use strict";function n(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=r.getPooled(null),this.putListenerQueue=s.getPooled()}var r=e(7),o=e(30),i=e(33),a=e(69),s=e(85),u=e(113),l=e(29),c={initialize:a.getSelectionInformation,close:a.restoreSelection},p={initialize:function(){var e=i.isEnabled();return i.setEnabled(!1),e},close:function(e){i.setEnabled(e)}},d={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},f={initialize:function(){this.putListenerQueue.reset()},close:function(){this.putListenerQueue.putListeners()}},h=[f,c,p,d],m={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){r.release(this.reactMountReady),this.reactMountReady=null,s.release(this.putListenerQueue),this.putListenerQueue=null}};l(n.prototype,u.Mixin,m),o.addPoolingTo(n),t.exports=n},{113:113,29:29,30:30,33:33,69:69,7:7,85:85}],87:[function(e,t){"use strict";function n(){r.attachRefs(this,this._currentElement)}var r=e(88),o=(e(62),{mountComponent:function(e,t,r,o){var i=e.mountComponent(t,r,o);return r.getReactMountReady().enqueue(n,e),i},unmountComponent:function(e){r.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,t,o,i){var a=e._currentElement;if(t!==a||null==t._owner){var s=r.shouldUpdateRefs(a,t);s&&r.detachRefs(e,a),e.receiveComponent(t,o,i),s&&o.getReactMountReady().enqueue(n,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}});t.exports=o},{62:62,88:88}],88:[function(e,t){"use strict";function n(e,t,n){"function"==typeof e?e(t.getPublicInstance()):o.addComponentAsRefTo(t,e,n)}function r(e,t,n){"function"==typeof e?e(null):o.removeComponentAsRefFrom(t,e,n)}var o=e(79),i={};i.attachRefs=function(e,t){var r=t.ref;null!=r&&n(r,e,t._owner)},i.shouldUpdateRefs=function(e,t){return t._owner!==e._owner||t.ref!==e.ref},i.detachRefs=function(e,t){var n=t.ref;null!=n&&r(n,e,t._owner)},t.exports=i},{79:79}],89:[function(e,t){"use strict";var n={injectCreateReactRootIndex:function(e){r.createReactRootIndex=e}},r={createReactRootIndex:null,injection:n};t.exports=r},{}],90:[function(e,t){"use strict";function n(e){c(o.isValidElement(e));var t;try{var n=i.createReactRootID();return t=s.getPooled(!1),t.perform(function(){var r=l(e,null),o=r.mountComponent(n,t,u);return a.addChecksumToMarkup(o)},null)}finally{s.release(t)}}function r(e){c(o.isValidElement(e));var t;try{var n=i.createReactRootID();return t=s.getPooled(!0),t.perform(function(){var r=l(e,null);return r.mountComponent(n,t,u)},null)}finally{s.release(t)}}var o=e(61),i=e(70),a=e(74),s=e(91),u=e(127),l=e(146),c=e(147);t.exports={renderToString:n,renderToStaticMarkup:r}},{127:127,146:146,147:147,61:61,70:70,74:74,91:91}],91:[function(e,t){"use strict";function n(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=o.getPooled(null),this.putListenerQueue=i.getPooled()}var r=e(30),o=e(7),i=e(85),a=e(113),s=e(29),u=e(126),l={initialize:function(){this.reactMountReady.reset()},close:u},c={initialize:function(){this.putListenerQueue.reset()},close:u},p=[c,l],d={getTransactionWrappers:function(){return p},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null,i.release(this.putListenerQueue),this.putListenerQueue=null}};s(n.prototype,a.Mixin,d),r.addPoolingTo(n),t.exports=n},{113:113,126:126,29:29,30:30,7:7,85:85}],92:[function(e,t){"use strict";function n(e,t){var n={};return function(r){n[t]=r,e.setState(n)}}var r={createStateSetter:function(e,t){return function(n,r,o,i,a,s){var u=t.call(e,n,r,o,i,a,s);u&&e.setState(u)}},createStateKeySetter:function(e,t){var r=e.__keySetters||(e.__keySetters={});return r[t]||(r[t]=n(e,t))}};r.Mixin={createStateSetter:function(e){return r.createStateSetter(this,e)},createStateKeySetter:function(e){return r.createStateKeySetter(this,e)}},t.exports=r},{}],93:[function(e,t){"use strict";var n=e(37),r=e(67),o={getChildMapping:function(e){return e?r.extract(n.map(e,function(e){return e})):e},mergeChildMappings:function(e,t){function n(n){return t.hasOwnProperty(n)?t[n]:e[n]}e=e||{},t=t||{};var r={},o=[];for(var i in e)t.hasOwnProperty(i)?o.length&&(r[i]=o,o=[]):o.push(i);var a,s={};for(var u in t){if(r.hasOwnProperty(u))for(a=0;a<r[u].length;a++){var l=r[u][a];s[r[u][a]]=n(l)}s[u]=n(u)}for(a=0;a<o.length;a++)s[o[a]]=n(o[a]);return s}};t.exports=o},{37:37,67:67}],94:[function(e,t){"use strict";function n(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete a.animationend.animation,"TransitionEvent"in window||delete a.transitionend.transition;for(var n in a){var r=a[n];for(var o in r)if(o in t){s.push(r[o]);break}}}function r(e,t,n){e.addEventListener(t,n,!1)}function o(e,t,n){e.removeEventListener(t,n,!1)}var i=e(22),a={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},s=[];i.canUseDOM&&n();var u={addEndEventListener:function(e,t){return 0===s.length?void window.setTimeout(t,0):void s.forEach(function(n){r(e,n,t)})},removeEndEventListener:function(e,t){0!==s.length&&s.forEach(function(n){o(e,n,t)})}};t.exports=u},{22:22}],95:[function(e,t){"use strict";var n=e(31),r=e(93),o=e(29),i=e(119),a=e(126),s=n.createClass({displayName:"ReactTransitionGroup",propTypes:{component:n.PropTypes.any,childFactory:n.PropTypes.func},getDefaultProps:function(){return{component:"span",childFactory:a.thatReturnsArgument}},getInitialState:function(){return{children:r.getChildMapping(this.props.children)}},componentWillMount:function(){this.currentlyTransitioningKeys={},this.keysToEnter=[],this.keysToLeave=[]},componentDidMount:function(){var e=this.state.children;for(var t in e)e[t]&&this.performAppear(t)},componentWillReceiveProps:function(e){var t=r.getChildMapping(e.children),n=this.state.children;
this.setState({children:r.mergeChildMappings(n,t)});var o;for(o in t){var i=n&&n.hasOwnProperty(o);!t[o]||i||this.currentlyTransitioningKeys[o]||this.keysToEnter.push(o)}for(o in n){var a=t&&t.hasOwnProperty(o);!n[o]||a||this.currentlyTransitioningKeys[o]||this.keysToLeave.push(o)}},componentDidUpdate:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)},performAppear:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillAppear?t.componentWillAppear(this._handleDoneAppearing.bind(this,e)):this._handleDoneAppearing(e)},_handleDoneAppearing:function(e){var t=this.refs[e];t.componentDidAppear&&t.componentDidAppear(),delete this.currentlyTransitioningKeys[e];var n=r.getChildMapping(this.props.children);n&&n.hasOwnProperty(e)||this.performLeave(e)},performEnter:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillEnter?t.componentWillEnter(this._handleDoneEntering.bind(this,e)):this._handleDoneEntering(e)},_handleDoneEntering:function(e){var t=this.refs[e];t.componentDidEnter&&t.componentDidEnter(),delete this.currentlyTransitioningKeys[e];var n=r.getChildMapping(this.props.children);n&&n.hasOwnProperty(e)||this.performLeave(e)},performLeave:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillLeave?t.componentWillLeave(this._handleDoneLeaving.bind(this,e)):this._handleDoneLeaving(e)},_handleDoneLeaving:function(e){var t=this.refs[e];t.componentDidLeave&&t.componentDidLeave(),delete this.currentlyTransitioningKeys[e];var n=r.getChildMapping(this.props.children);if(n&&n.hasOwnProperty(e))this.performEnter(e);else{var i=o({},this.state.children);delete i[e],this.setState({children:i})}},render:function(){var e=[];for(var t in this.state.children){var r=this.state.children[t];r&&e.push(i(this.props.childFactory(r),{ref:t,key:t}))}return n.createElement(this.props.component,this.props,e)}});t.exports=s},{119:119,126:126,29:29,31:31,93:93}],96:[function(e,t){"use strict";function n(e){e!==o.currentlyMountingInstance&&u.enqueueUpdate(e)}function r(e){c(null==i.current);var t=s.get(e);return t?t===o.currentlyUnmountingInstance?null:t:null}var o=e(72),i=e(45),a=e(61),s=e(71),u=e(97),l=e(29),c=e(147),p=(e(166),{enqueueCallback:function(e,t){c("function"==typeof t);var i=r(e);return i&&i!==o.currentlyMountingInstance?(i._pendingCallbacks?i._pendingCallbacks.push(t):i._pendingCallbacks=[t],void n(i)):null},enqueueCallbackInternal:function(e,t){c("function"==typeof t),e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],n(e)},enqueueForceUpdate:function(e){var t=r(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,n(t))},enqueueReplaceState:function(e,t){var o=r(e,"replaceState");o&&(o._pendingStateQueue=[t],o._pendingReplaceState=!0,n(o))},enqueueSetState:function(e,t){var o=r(e,"setState");if(o){var i=o._pendingStateQueue||(o._pendingStateQueue=[]);i.push(t),n(o)}},enqueueSetProps:function(e,t){var o=r(e,"setProps");if(o){c(o._isTopLevel);var i=o._pendingElement||o._currentElement,s=l({},i.props,t);o._pendingElement=a.cloneAndReplaceProps(i,s),n(o)}},enqueueReplaceProps:function(e,t){var o=r(e,"replaceProps");if(o){c(o._isTopLevel);var i=o._pendingElement||o._currentElement;o._pendingElement=a.cloneAndReplaceProps(i,t),n(o)}},enqueueElementInternal:function(e,t){e._pendingElement=t,n(e)}});t.exports=p},{147:147,166:166,29:29,45:45,61:61,71:71,72:72,97:97}],97:[function(e,t){"use strict";function n(){m(M.ReactReconcileTransaction&&C)}function r(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=l.getPooled(),this.reconcileTransaction=M.ReactReconcileTransaction.getPooled()}function o(e,t,r,o,i){n(),C.batchedUpdates(e,t,r,o,i)}function i(e,t){return e._mountOrder-t._mountOrder}function a(e){var t=e.dirtyComponentsLength;m(t===v.length),v.sort(i);for(var n=0;t>n;n++){var r=v[n],o=r._pendingCallbacks;if(r._pendingCallbacks=null,d.performUpdateIfNecessary(r,e.reconcileTransaction),o)for(var a=0;a<o.length;a++)e.callbackQueue.enqueue(o[a],r.getPublicInstance())}}function s(e){return n(),C.isBatchingUpdates?void v.push(e):void C.batchedUpdates(s,e)}function u(e,t){m(C.isBatchingUpdates),g.enqueue(e,t),y=!0}var l=e(7),c=e(30),p=(e(45),e(80)),d=e(87),f=e(113),h=e(29),m=e(147),v=(e(166),[]),g=l.getPooled(),y=!1,C=null,E={initialize:function(){this.dirtyComponentsLength=v.length},close:function(){this.dirtyComponentsLength!==v.length?(v.splice(0,this.dirtyComponentsLength),x()):v.length=0}},b={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},_=[E,b];h(r.prototype,f.Mixin,{getTransactionWrappers:function(){return _},destructor:function(){this.dirtyComponentsLength=null,l.release(this.callbackQueue),this.callbackQueue=null,M.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return f.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),c.addPoolingTo(r);var x=function(){for(;v.length||y;){if(v.length){var e=r.getPooled();e.perform(a,null,e),r.release(e)}if(y){y=!1;var t=g;g=l.getPooled(),t.notifyAll(),l.release(t)}}};x=p.measure("ReactUpdates","flushBatchedUpdates",x);var D={injectReconcileTransaction:function(e){m(e),M.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){m(e),m("function"==typeof e.batchedUpdates),m("boolean"==typeof e.isBatchingUpdates),C=e}},M={ReactReconcileTransaction:null,batchedUpdates:o,enqueueUpdate:s,flushBatchedUpdates:x,injection:D,asap:u};t.exports=M},{113:113,147:147,166:166,29:29,30:30,45:45,7:7,80:80,87:87}],98:[function(e,t){"use strict";var n=e(11),r=n.injection.MUST_USE_ATTRIBUTE,o={Properties:{cx:r,cy:r,d:r,dx:r,dy:r,fill:r,fillOpacity:r,fontFamily:r,fontSize:r,fx:r,fy:r,gradientTransform:r,gradientUnits:r,markerEnd:r,markerMid:r,markerStart:r,offset:r,opacity:r,patternContentUnits:r,patternUnits:r,points:r,preserveAspectRatio:r,r:r,rx:r,ry:r,spreadMethod:r,stopColor:r,stopOpacity:r,stroke:r,strokeDasharray:r,strokeLinecap:r,strokeOpacity:r,strokeWidth:r,textAnchor:r,transform:r,version:r,viewBox:r,x1:r,x2:r,x:r,y1:r,y2:r,y:r},DOMAttributeNames:{fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox"}};t.exports=o},{11:11}],99:[function(e,t){"use strict";function n(e){if("selectionStart"in e&&a.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function r(e){if(g||null==h||h!==u())return null;var t=n(h);if(!v||!p(v,t)){v=t;var r=s.getPooled(f.select,m,e);return r.type="select",r.target=h,i.accumulateTwoPhaseDispatches(r),r}}var o=e(16),i=e(21),a=e(69),s=e(105),u=e(133),l=e(150),c=e(154),p=e(161),d=o.topLevelTypes,f={select:{phasedRegistrationNames:{bubbled:c({onSelect:null}),captured:c({onSelectCapture:null})},dependencies:[d.topBlur,d.topContextMenu,d.topFocus,d.topKeyDown,d.topMouseDown,d.topMouseUp,d.topSelectionChange]}},h=null,m=null,v=null,g=!1,y={eventTypes:f,extractEvents:function(e,t,n,o){switch(e){case d.topFocus:(l(t)||"true"===t.contentEditable)&&(h=t,m=n,v=null);break;case d.topBlur:h=null,m=null,v=null;break;case d.topMouseDown:g=!0;break;case d.topContextMenu:case d.topMouseUp:return g=!1,r(o);case d.topSelectionChange:case d.topKeyDown:case d.topKeyUp:return r(o)}}};t.exports=y},{105:105,133:133,150:150,154:154,16:16,161:161,21:21,69:69}],100:[function(e,t){"use strict";var n=Math.pow(2,53),r={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};t.exports=r},{}],101:[function(e,t){"use strict";var n=e(16),r=e(20),o=e(21),i=e(102),a=e(105),s=e(106),u=e(108),l=e(109),c=e(104),p=e(110),d=e(111),f=e(112),h=e(134),m=e(147),v=e(154),g=(e(166),n.topLevelTypes),y={blur:{phasedRegistrationNames:{bubbled:v({onBlur:!0}),captured:v({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:v({onClick:!0}),captured:v({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:v({onContextMenu:!0}),captured:v({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:v({onCopy:!0}),captured:v({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:v({onCut:!0}),captured:v({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:v({onDoubleClick:!0}),captured:v({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:v({onDrag:!0}),captured:v({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:v({onDragEnd:!0}),captured:v({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:v({onDragEnter:!0}),captured:v({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:v({onDragExit:!0}),captured:v({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:v({onDragLeave:!0}),captured:v({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:v({onDragOver:!0}),captured:v({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:v({onDragStart:!0}),captured:v({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:v({onDrop:!0}),captured:v({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:v({onFocus:!0}),captured:v({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:v({onInput:!0}),captured:v({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:v({onKeyDown:!0}),captured:v({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:v({onKeyPress:!0}),captured:v({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:v({onKeyUp:!0}),captured:v({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:v({onLoad:!0}),captured:v({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:v({onError:!0}),captured:v({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:v({onMouseDown:!0}),captured:v({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:v({onMouseMove:!0}),captured:v({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:v({onMouseOut:!0}),captured:v({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:v({onMouseOver:!0}),captured:v({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:v({onMouseUp:!0}),captured:v({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:v({onPaste:!0}),captured:v({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:v({onReset:!0}),captured:v({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:v({onScroll:!0}),captured:v({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:v({onSubmit:!0}),captured:v({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:v({onTouchCancel:!0}),captured:v({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:v({onTouchEnd:!0}),captured:v({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:v({onTouchMove:!0}),captured:v({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:v({onTouchStart:!0}),captured:v({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:v({onWheel:!0}),captured:v({onWheelCapture:!0})}}},C={topBlur:y.blur,topClick:y.click,topContextMenu:y.contextMenu,topCopy:y.copy,topCut:y.cut,topDoubleClick:y.doubleClick,topDrag:y.drag,topDragEnd:y.dragEnd,topDragEnter:y.dragEnter,topDragExit:y.dragExit,topDragLeave:y.dragLeave,topDragOver:y.dragOver,topDragStart:y.dragStart,topDrop:y.drop,topError:y.error,topFocus:y.focus,topInput:y.input,topKeyDown:y.keyDown,topKeyPress:y.keyPress,topKeyUp:y.keyUp,topLoad:y.load,topMouseDown:y.mouseDown,topMouseMove:y.mouseMove,topMouseOut:y.mouseOut,topMouseOver:y.mouseOver,topMouseUp:y.mouseUp,topPaste:y.paste,topReset:y.reset,topScroll:y.scroll,topSubmit:y.submit,topTouchCancel:y.touchCancel,topTouchEnd:y.touchEnd,topTouchMove:y.touchMove,topTouchStart:y.touchStart,topWheel:y.wheel};for(var E in C)C[E].dependencies=[E];var b={eventTypes:y,executeDispatch:function(e,t,n){var o=r.executeDispatch(e,t,n);o===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,t,n,r){var v=C[e];if(!v)return null;var y;switch(e){case g.topInput:case g.topLoad:case g.topError:case g.topReset:case g.topSubmit:y=a;break;case g.topKeyPress:if(0===h(r))return null;case g.topKeyDown:case g.topKeyUp:y=u;break;case g.topBlur:case g.topFocus:y=s;break;case g.topClick:if(2===r.button)return null;case g.topContextMenu:case g.topDoubleClick:case g.topMouseDown:case g.topMouseMove:case g.topMouseOut:case g.topMouseOver:case g.topMouseUp:y=l;break;case g.topDrag:case g.topDragEnd:case g.topDragEnter:case g.topDragExit:case g.topDragLeave:case g.topDragOver:case g.topDragStart:case g.topDrop:y=c;break;case g.topTouchCancel:case g.topTouchEnd:case g.topTouchMove:case g.topTouchStart:y=p;break;case g.topScroll:y=d;break;case g.topWheel:y=f;break;case g.topCopy:case g.topCut:case g.topPaste:y=i}m(y);var E=y.getPooled(v,n,r);return o.accumulateTwoPhaseDispatches(E),E}};t.exports=b},{102:102,104:104,105:105,106:106,108:108,109:109,110:110,111:111,112:112,134:134,147:147,154:154,16:16,166:166,20:20,21:21}],102:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e(105),o={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};r.augmentClass(n,o),t.exports=n},{105:105}],103:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e(105),o={data:null};r.augmentClass(n,o),t.exports=n},{105:105}],104:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e(109),o={dataTransfer:null};r.augmentClass(n,o),t.exports=n},{109:109}],105:[function(e,t){"use strict";function n(e,t,n){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var r=this.constructor.Interface;for(var o in r)if(r.hasOwnProperty(o)){var a=r[o];this[o]=a?a(n):n[o]}var s=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;this.isDefaultPrevented=s?i.thatReturnsTrue:i.thatReturnsFalse,this.isPropagationStopped=i.thatReturnsFalse}var r=e(30),o=e(29),i=e(126),a=e(137),s={type:null,target:a,currentTarget:i.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};o(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=i.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=i.thatReturnsTrue},persist:function(){this.isPersistent=i.thatReturnsTrue},isPersistent:i.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),n.Interface=s,n.augmentClass=function(e,t){var n=this,i=Object.create(n.prototype);o(i,e.prototype),e.prototype=i,e.prototype.constructor=e,e.Interface=o({},n.Interface,t),e.augmentClass=n.augmentClass,r.addPoolingTo(e,r.threeArgumentPooler)},r.addPoolingTo(n,r.threeArgumentPooler),t.exports=n},{126:126,137:137,29:29,30:30}],106:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e(111),o={relatedTarget:null};r.augmentClass(n,o),t.exports=n},{111:111}],107:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e(105),o={data:null};r.augmentClass(n,o),t.exports=n},{105:105}],108:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e(111),o=e(134),i=e(135),a=e(136),s={key:i,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:a,charCode:function(e){return"keypress"===e.type?o(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?o(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};r.augmentClass(n,s),t.exports=n},{111:111,134:134,135:135,136:136}],109:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e(111),o=e(114),i=e(136),a={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:i,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+o.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+o.currentScrollTop}};r.augmentClass(n,a),t.exports=n},{111:111,114:114,136:136}],110:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e(111),o=e(136),i={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:o};r.augmentClass(n,i),t.exports=n},{111:111,136:136}],111:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e(105),o=e(137),i={view:function(e){if(e.view)return e.view;var t=o(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};r.augmentClass(n,i),t.exports=n},{105:105,137:137}],112:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e(109),o={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};r.augmentClass(n,o),t.exports=n},{109:109}],113:[function(e,t){"use strict";var n=e(147),r={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,r,o,i,a,s,u){n(!this.isInTransaction());var l,c;try{this._isInTransaction=!0,l=!0,this.initializeAll(0),c=e.call(t,r,o,i,a,s,u),l=!1}finally{try{if(l)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return c},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=o.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===o.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(i){}}}},closeAll:function(e){n(this.isInTransaction());for(var t=this.transactionWrappers,r=e;r<t.length;r++){var i,a=t[r],s=this.wrapperInitData[r];try{i=!0,s!==o.OBSERVED_ERROR&&a.close&&a.close.call(this,s),i=!1}finally{if(i)try{this.closeAll(r+1)}catch(u){}}}this.wrapperInitData.length=0}},o={Mixin:r,OBSERVED_ERROR:{}};t.exports=o},{147:147}],114:[function(e,t){"use strict";var n={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){n.currentScrollLeft=e.x,n.currentScrollTop=e.y}};t.exports=n},{}],115:[function(e,t){"use strict";function n(e,t){if(r(null!=t),null==e)return t;var n=Array.isArray(e),o=Array.isArray(t);return n&&o?(e.push.apply(e,t),e):n?(e.push(t),e):o?[e].concat(t):[e,t]}var r=e(147);t.exports=n},{147:147}],116:[function(e,t){"use strict";function n(e){for(var t=1,n=0,o=0;o<e.length;o++)t=(t+e.charCodeAt(o))%r,n=(n+t)%r;return t|n<<16}var r=65521;t.exports=n},{}],117:[function(e,t){function n(e){return e.replace(r,function(e,t){return t.toUpperCase()})}var r=/-(.)/g;t.exports=n},{}],118:[function(e,t){"use strict";function n(e){return r(e.replace(o,"ms-"))}var r=e(117),o=/^-ms-/;t.exports=n},{117:117}],119:[function(e,t){"use strict";function n(e,t){var n=o.mergeProps(t,e.props);return!n.hasOwnProperty(a)&&e.props.hasOwnProperty(a)&&(n.children=e.props.children),r.createElement(e.type,n)}var r=e(61),o=e(81),i=e(154),a=(e(166),i({children:null}));t.exports=n},{154:154,166:166,61:61,81:81}],120:[function(e,t){function n(e,t){return e&&t?e===t?!0:r(e)?!1:r(t)?n(e,t.parentNode):e.contains?e.contains(t):e.compareDocumentPosition?!!(16&e.compareDocumentPosition(t)):!1:!1}var r=e(151);t.exports=n},{151:151}],121:[function(e,t){function n(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function r(e){return n(e)?Array.isArray(e)?e.slice():o(e):[e]}var o=e(163);t.exports=r},{163:163}],122:[function(e,t){"use strict";function n(e){var t=o.createFactory(e),n=r.createClass({displayName:"ReactFullPageComponent"+e,componentWillUnmount:function(){i(!1)},render:function(){return t(this.props)}});return n}var r=e(38),o=e(61),i=e(147);t.exports=n},{147:147,38:38,61:61}],123:[function(e,t){function n(e){var t=e.match(l);return t&&t[1].toLowerCase()}function r(e,t){var r=u;s(!!u);var o=n(e),l=o&&a(o);if(l){r.innerHTML=l[1]+e+l[2];for(var c=l[0];c--;)r=r.lastChild}else r.innerHTML=e;var p=r.getElementsByTagName("script");p.length&&(s(t),i(p).forEach(t));for(var d=i(r.childNodes);r.lastChild;)r.removeChild(r.lastChild);return d}var o=e(22),i=e(121),a=e(139),s=e(147),u=o.canUseDOM?document.createElement("div"):null,l=/^\s*<(\w+)/;t.exports=r},{121:121,139:139,147:147,22:22}],124:[function(e,t){"use strict";function n(e){return"object"==typeof e?Object.keys(e).filter(function(t){return e[t]}).join(" "):Array.prototype.join.call(arguments," ")}e(166);t.exports=n},{166:166}],125:[function(e,t){"use strict";function n(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||o.hasOwnProperty(e)&&o[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var r=e(5),o=r.isUnitlessNumber;t.exports=n},{5:5}],126:[function(e,t){function n(e){return function(){return e}}function r(){}r.thatReturns=n,r.thatReturnsFalse=n(!1),r.thatReturnsTrue=n(!0),r.thatReturnsNull=n(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},t.exports=r},{}],127:[function(e,t){"use strict";var n={};t.exports=n},{}],128:[function(e,t){"use strict";function n(e){return o[e]}function r(e){return(""+e).replace(i,n)}var o={"&":"&",">":">","<":"<",'"':""","'":"'"},i=/[&><"']/g;t.exports=r},{}],129:[function(e,t){"use strict";function n(e){return null==e?null:a(e)?e:r.has(e)?o.getNodeFromInstance(e):(i(null==e.render||"function"!=typeof e.render),void i(!1))}{var r=(e(45),e(71)),o=e(75),i=e(147),a=e(149);e(166)}t.exports=n},{147:147,149:149,166:166,45:45,71:71,75:75}],130:[function(e,t){"use strict";function n(e,t,n){var r=e,o=!r.hasOwnProperty(n);o&&null!=t&&(r[n]=t)}function r(e){if(null==e)return e;var t={};return o(e,n,t),t}{var o=e(164);e(166)}t.exports=r},{164:164,166:166}],131:[function(e,t){"use strict";function n(e){try{e.focus()}catch(t){}}t.exports=n},{}],132:[function(e,t){"use strict";var n=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};t.exports=n},{}],133:[function(e,t){function n(){try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=n},{}],134:[function(e,t){"use strict";function n(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}t.exports=n},{}],135:[function(e,t){"use strict";function n(e){if(e.key){var t=o[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=r(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?i[e.keyCode]||"Unidentified":""}var r=e(134),o={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},i={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};t.exports=n},{134:134}],136:[function(e,t){"use strict";function n(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=o[e];return r?!!n[r]:!1}function r(){return n}var o={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};t.exports=r},{}],137:[function(e,t){"use strict";function n(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}t.exports=n},{}],138:[function(e,t){"use strict";function n(e){var t=e&&(r&&e[r]||e[o]);return"function"==typeof t?t:void 0}var r="function"==typeof Symbol&&Symbol.iterator,o="@@iterator";t.exports=n},{}],139:[function(e,t){function n(e){return o(!!i),p.hasOwnProperty(e)||(e="*"),a.hasOwnProperty(e)||(i.innerHTML="*"===e?"<link />":"<"+e+"></"+e+">",a[e]=!i.firstChild),a[e]?p[e]:null}var r=e(22),o=e(147),i=r.canUseDOM?document.createElement("div"):null,a={circle:!0,defs:!0,ellipse:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},s=[1,'<select multiple="true">',"</select>"],u=[1,"<table>","</table>"],l=[3,"<table><tbody><tr>","</tr></tbody></table>"],c=[1,"<svg>","</svg>"],p={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:s,option:s,caption:u,colgroup:u,tbody:u,tfoot:u,thead:u,td:l,th:l,circle:c,defs:c,ellipse:c,g:c,line:c,linearGradient:c,path:c,polygon:c,polyline:c,radialGradient:c,rect:c,stop:c,text:c};t.exports=n},{147:147,22:22}],140:[function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function r(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function o(e,t){for(var o=n(e),i=0,a=0;o;){if(3===o.nodeType){if(a=i+o.textContent.length,t>=i&&a>=t)return{node:o,offset:t-i};i=a}o=n(r(o))}}t.exports=o},{}],141:[function(e,t){"use strict";function n(e){return e?e.nodeType===r?e.documentElement:e.firstChild:null}var r=9;t.exports=n},{}],142:[function(e,t){"use strict";function n(){return!o&&r.canUseDOM&&(o="textContent"in document.documentElement?"textContent":"innerText"),o}var r=e(22),o=null;t.exports=n},{22:22}],143:[function(e,t){"use strict";function n(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=n},{}],144:[function(e,t){function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;t.exports=n},{}],145:[function(e,t){"use strict";function n(e){return r(e).replace(o,"-ms-")}var r=e(144),o=/^ms-/;t.exports=n},{144:144}],146:[function(e,t){"use strict";function n(e){return"function"==typeof e&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function r(e,t){var r;if((null===e||e===!1)&&(e=i.emptyElement),"object"==typeof e){var o=e;r=t===o.type&&"string"==typeof o.type?a.createInternalComponent(o):n(o.type)?new o.type(o):new l}else"string"==typeof e||"number"==typeof e?r=a.createInstanceForText(e):u(!1);return r.construct(e),r._mountIndex=0,r._mountImage=null,r}var o=e(43),i=e(63),a=e(78),s=e(29),u=e(147),l=(e(166),function(){});s(l.prototype,o.Mixin,{_instantiateReactComponent:r}),t.exports=r},{147:147,166:166,29:29,43:43,63:63,78:78}],147:[function(e,t){"use strict";var n=function(e,t,n,r,o,i,a,s){if(!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,o,i,a,s],c=0;u=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return l[c++]}))}throw u.framesToPop=1,u}};t.exports=n},{}],148:[function(e,t){"use strict";function n(e,t){if(!o.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,i=n in document;if(!i){var a=document.createElement("div");a.setAttribute(n,"return;"),i="function"==typeof a[n]}return!i&&r&&"wheel"===e&&(i=document.implementation.hasFeature("Events.wheel","3.0")),i}var r,o=e(22);o.canUseDOM&&(r=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=n},{22:22}],149:[function(e,t){function n(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=n},{}],150:[function(e,t){"use strict";function n(e){return e&&("INPUT"===e.nodeName&&r[e.type]||"TEXTAREA"===e.nodeName)}var r={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};t.exports=n},{}],151:[function(e,t){function n(e){return r(e)&&3==e.nodeType}var r=e(149);t.exports=n},{149:149}],152:[function(e,t){"use strict";function n(e){e||(e="");var t,n=arguments.length;if(n>1)for(var r=1;n>r;r++)t=arguments[r],t&&(e=(e?e+" ":"")+t);return e}t.exports=n},{}],153:[function(e,t){"use strict";var n=e(147),r=function(e){var t,r={};n(e instanceof Object&&!Array.isArray(e));for(t in e)e.hasOwnProperty(t)&&(r[t]=t);return r};t.exports=r},{147:147}],154:[function(e,t){var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=n},{}],155:[function(e,t){"use strict";function n(e,t,n){if(!e)return null;var o={};for(var i in e)r.call(e,i)&&(o[i]=t.call(n,e[i],i,e));return o}var r=Object.prototype.hasOwnProperty;t.exports=n},{}],156:[function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}t.exports=n},{}],157:[function(e,t){"use strict";function n(e){return o(r.isValidElement(e)),e}var r=e(61),o=e(147);t.exports=n},{147:147,61:61}],158:[function(e,t){"use strict";function n(e){return'"'+r(e)+'"'}var r=e(128);t.exports=n},{128:128}],159:[function(e,t){"use strict";var n=e(22),r=/^[ \r\n\t\f]/,o=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,i=function(e,t){e.innerHTML=t};if("undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(i=function(e,t){MSApp.execUnsafeLocalFunction(function(){e.innerHTML=t})}),n.canUseDOM){var a=document.createElement("div");a.innerHTML=" ",""===a.innerHTML&&(i=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),r.test(t)||"<"===t[0]&&o.test(t)){e.innerHTML=""+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}t.exports=i},{22:22}],160:[function(e,t){"use strict";var n=e(22),r=e(128),o=e(159),i=function(e,t){e.textContent=t};n.canUseDOM&&("textContent"in document.documentElement||(i=function(e,t){o(e,r(t))})),t.exports=i},{128:128,159:159,22:22}],161:[function(e,t){"use strict";function n(e,t){if(e===t)return!0;var n;for(n in e)if(e.hasOwnProperty(n)&&(!t.hasOwnProperty(n)||e[n]!==t[n]))return!1;for(n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}t.exports=n},{}],162:[function(e,t){"use strict";function n(e,t){if(null!=e&&null!=t){var n=typeof e,r=typeof t;if("string"===n||"number"===n)return"string"===r||"number"===r;if("object"===r&&e.type===t.type&&e.key===t.key){var o=e._owner===t._owner;
return o}}return!1}e(166);t.exports=n},{166:166}],163:[function(e,t){function n(e){var t=e.length;if(r(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e)),r("number"==typeof t),r(0===t||t-1 in e),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var o=Array(t),i=0;t>i;i++)o[i]=e[i];return o}var r=e(147);t.exports=n},{147:147}],164:[function(e,t){"use strict";function n(e){return m[e]}function r(e,t){return e&&null!=e.key?i(e.key):t.toString(36)}function o(e){return(""+e).replace(v,n)}function i(e){return"$"+o(e)}function a(e,t,n,o,s){var c=typeof e;if(("undefined"===c||"boolean"===c)&&(e=null),null===e||"string"===c||"number"===c||u.isValidElement(e))return o(s,e,""===t?f+r(e,0):t,n),1;var m,v,g,y=0;if(Array.isArray(e))for(var C=0;C<e.length;C++)m=e[C],v=(""!==t?t+h:f)+r(m,C),g=n+y,y+=a(m,v,g,o,s);else{var E=p(e);if(E){var b,_=E.call(e);if(E!==e.entries)for(var x=0;!(b=_.next()).done;)m=b.value,v=(""!==t?t+h:f)+r(m,x++),g=n+y,y+=a(m,v,g,o,s);else for(;!(b=_.next()).done;){var D=b.value;D&&(m=D[1],v=(""!==t?t+h:f)+i(D[0])+h+r(m,0),g=n+y,y+=a(m,v,g,o,s))}}else if("object"===c){d(1!==e.nodeType);var M=l.extract(e);for(var T in M)M.hasOwnProperty(T)&&(m=M[T],v=(""!==t?t+h:f)+i(T)+h+r(m,0),g=n+y,y+=a(m,v,g,o,s))}}return y}function s(e,t,n){return null==e?0:a(e,"",0,t,n)}var u=e(61),l=e(67),c=e(70),p=e(138),d=e(147),f=(e(166),c.SEPARATOR),h=":",m={"=":"=0",".":"=1",":":"=2"},v=/[=.:]/g;t.exports=s},{138:138,147:147,166:166,61:61,67:67,70:70}],165:[function(e,t){"use strict";function n(e){return Array.isArray(e)?e.concat():e&&"object"==typeof e?i(new e.constructor,e):e}function r(e,t,n){s(Array.isArray(e));var r=t[n];s(Array.isArray(r))}function o(e,t){if(s("object"==typeof t),t.hasOwnProperty(p))return s(1===Object.keys(t).length),t[p];var a=n(e);if(t.hasOwnProperty(d)){var h=t[d];s(h&&"object"==typeof h),s(a&&"object"==typeof a),i(a,t[d])}t.hasOwnProperty(u)&&(r(e,t,u),t[u].forEach(function(e){a.push(e)})),t.hasOwnProperty(l)&&(r(e,t,l),t[l].forEach(function(e){a.unshift(e)})),t.hasOwnProperty(c)&&(s(Array.isArray(e)),s(Array.isArray(t[c])),t[c].forEach(function(e){s(Array.isArray(e)),a.splice.apply(a,e)})),t.hasOwnProperty(f)&&(s("function"==typeof t[f]),a=t[f](a));for(var v in t)m.hasOwnProperty(v)&&m[v]||(a[v]=o(e[v],t[v]));return a}var i=e(29),a=e(154),s=e(147),u=a({$push:null}),l=a({$unshift:null}),c=a({$splice:null}),p=a({$set:null}),d=a({$merge:null}),f=a({$apply:null}),h=[u,l,c,p,d,f],m={};h.forEach(function(e){m[e]=!0}),t.exports=o},{147:147,154:154,29:29}],166:[function(e,t){"use strict";var n=e(126),r=n;t.exports=r},{126:126}]},{},[1])(1)}); |
src/components/PrimaryButton/PrimaryButton.js | carbon-design-system/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import Button from '../Button';
const PrimaryButton = props => <Button kind="primary" {...props} />;
export default PrimaryButton;
|
mypiano/node_modules/@angular/cli/node_modules/zone.js/dist/zone.js | ezequielfreire007/proyectoIonic | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
typeof define === 'function' && define.amd ? define(factory) :
(factory());
}(this, (function () { 'use strict';
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var Zone$1 = (function (global) {
var FUNCTION = 'function';
var performance = global['performance'];
function mark(name) {
performance && performance['mark'] && performance['mark'](name);
}
function performanceMeasure(name, label) {
performance && performance['measure'] && performance['measure'](name, label);
}
mark('Zone');
if (global['Zone']) {
throw new Error('Zone already loaded.');
}
var Zone = (function () {
function Zone(parent, zoneSpec) {
this._properties = null;
this._parent = parent;
this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
this._properties = zoneSpec && zoneSpec.properties || {};
this._zoneDelegate =
new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
}
Zone.assertZonePatched = function () {
if (global['Promise'] !== patches['ZoneAwarePromise']) {
throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
'has been overwritten.\n' +
'Most likely cause is that a Promise polyfill has been loaded ' +
'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
'If you must load one, do so before loading zone.js.)');
}
};
Object.defineProperty(Zone, "root", {
get: function () {
var zone = Zone.current;
while (zone.parent) {
zone = zone.parent;
}
return zone;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Zone, "current", {
get: function () {
return _currentZoneFrame.zone;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Zone, "currentTask", {
get: function () {
return _currentTask;
},
enumerable: true,
configurable: true
});
Zone.__load_patch = function (name, fn) {
if (patches.hasOwnProperty(name)) {
throw Error('Already loaded patch: ' + name);
}
else if (!global['__Zone_disable_' + name]) {
var perfName = 'Zone:' + name;
mark(perfName);
patches[name] = fn(global, Zone, _api);
performanceMeasure(perfName, perfName);
}
};
Object.defineProperty(Zone.prototype, "parent", {
get: function () {
return this._parent;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Zone.prototype, "name", {
get: function () {
return this._name;
},
enumerable: true,
configurable: true
});
Zone.prototype.get = function (key) {
var zone = this.getZoneWith(key);
if (zone)
return zone._properties[key];
};
Zone.prototype.getZoneWith = function (key) {
var current = this;
while (current) {
if (current._properties.hasOwnProperty(key)) {
return current;
}
current = current._parent;
}
return null;
};
Zone.prototype.fork = function (zoneSpec) {
if (!zoneSpec)
throw new Error('ZoneSpec required!');
return this._zoneDelegate.fork(this, zoneSpec);
};
Zone.prototype.wrap = function (callback, source) {
if (typeof callback !== FUNCTION) {
throw new Error('Expecting function got: ' + callback);
}
var _callback = this._zoneDelegate.intercept(this, callback, source);
var zone = this;
return function () {
return zone.runGuarded(_callback, this, arguments, source);
};
};
Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
if (applyThis === void 0) { applyThis = undefined; }
if (applyArgs === void 0) { applyArgs = null; }
if (source === void 0) { source = null; }
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
}
finally {
_currentZoneFrame = _currentZoneFrame.parent;
}
};
Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
if (applyThis === void 0) { applyThis = null; }
if (applyArgs === void 0) { applyArgs = null; }
if (source === void 0) { source = null; }
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
}
catch (error) {
if (this._zoneDelegate.handleError(this, error)) {
throw error;
}
}
}
finally {
_currentZoneFrame = _currentZoneFrame.parent;
}
};
Zone.prototype.runTask = function (task, applyThis, applyArgs) {
if (task.zone != this) {
throw new Error('A task can only be run in the zone of creation! (Creation: ' +
(task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
}
// https://github.com/angular/zone.js/issues/778, sometimes eventTask
// will run in notScheduled(canceled) state, we should not try to
// run such kind of task but just return
// we have to define an variable here, if not
// typescript compiler will complain below
var isNotScheduled = task.state === notScheduled;
if (isNotScheduled && task.type === eventTask) {
return;
}
var reEntryGuard = task.state != running;
reEntryGuard && task._transitionTo(running, scheduled);
task.runCount++;
var previousTask = _currentTask;
_currentTask = task;
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
if (task.type == macroTask && task.data && !task.data.isPeriodic) {
task.cancelFn = null;
}
try {
return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
}
catch (error) {
if (this._zoneDelegate.handleError(this, error)) {
throw error;
}
}
}
finally {
// if the task's state is notScheduled or unknown, then it has already been cancelled
// we should not reset the state to scheduled
if (task.state !== notScheduled && task.state !== unknown) {
if (task.type == eventTask || (task.data && task.data.isPeriodic)) {
reEntryGuard && task._transitionTo(scheduled, running);
}
else {
task.runCount = 0;
this._updateTaskCount(task, -1);
reEntryGuard &&
task._transitionTo(notScheduled, running, notScheduled);
}
}
_currentZoneFrame = _currentZoneFrame.parent;
_currentTask = previousTask;
}
};
Zone.prototype.scheduleTask = function (task) {
if (task.zone && task.zone !== this) {
// check if the task was rescheduled, the newZone
// should not be the children of the original zone
var newZone = this;
while (newZone) {
if (newZone === task.zone) {
throw Error("can not reschedule task to " + this
.name + " which is descendants of the original zone " + task.zone.name);
}
newZone = newZone.parent;
}
}
task._transitionTo(scheduling, notScheduled);
var zoneDelegates = [];
task._zoneDelegates = zoneDelegates;
task._zone = this;
try {
task = this._zoneDelegate.scheduleTask(this, task);
}
catch (err) {
// should set task's state to unknown when scheduleTask throw error
// because the err may from reschedule, so the fromState maybe notScheduled
task._transitionTo(unknown, scheduling, notScheduled);
// TODO: @JiaLiPassion, should we check the result from handleError?
this._zoneDelegate.handleError(this, err);
throw err;
}
if (task._zoneDelegates === zoneDelegates) {
// we have to check because internally the delegate can reschedule the task.
this._updateTaskCount(task, 1);
}
if (task.state == scheduling) {
task._transitionTo(scheduled, scheduling);
}
return task;
};
Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, null));
};
Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
};
Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) {
return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
};
Zone.prototype.cancelTask = function (task) {
if (task.zone != this)
throw new Error('A task can only be cancelled in the zone of creation! (Creation: ' +
(task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
task._transitionTo(canceling, scheduled, running);
try {
this._zoneDelegate.cancelTask(this, task);
}
catch (err) {
// if error occurs when cancelTask, transit the state to unknown
task._transitionTo(unknown, canceling);
this._zoneDelegate.handleError(this, err);
throw err;
}
this._updateTaskCount(task, -1);
task._transitionTo(notScheduled, canceling);
task.runCount = 0;
return task;
};
Zone.prototype._updateTaskCount = function (task, count) {
var zoneDelegates = task._zoneDelegates;
if (count == -1) {
task._zoneDelegates = null;
}
for (var i = 0; i < zoneDelegates.length; i++) {
zoneDelegates[i]._updateTaskCount(task.type, count);
}
};
return Zone;
}());
Zone.__symbol__ = __symbol__;
var DELEGATE_ZS = {
name: '',
onHasTask: function (delegate, _, target, hasTaskState) {
return delegate.hasTask(target, hasTaskState);
},
onScheduleTask: function (delegate, _, target, task) {
return delegate.scheduleTask(target, task);
},
onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) { return delegate.invokeTask(target, task, applyThis, applyArgs); },
onCancelTask: function (delegate, _, target, task) {
return delegate.cancelTask(target, task);
}
};
var ZoneDelegate = (function () {
function ZoneDelegate(zone, parentDelegate, zoneSpec) {
this._taskCounts = { 'microTask': 0, 'macroTask': 0, 'eventTask': 0 };
this.zone = zone;
this._parentDelegate = parentDelegate;
this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
this._forkCurrZone = zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate.zone);
this._interceptZS =
zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
this._interceptDlgt =
zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
this._interceptCurrZone =
zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate.zone);
this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
this._invokeDlgt =
zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
this._invokeCurrZone = zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate.zone);
this._handleErrorZS =
zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
this._handleErrorDlgt =
zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
this._handleErrorCurrZone =
zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone);
this._scheduleTaskZS =
zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
this._scheduleTaskDlgt =
zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
this._scheduleTaskCurrZone =
zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone);
this._invokeTaskZS =
zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
this._invokeTaskDlgt =
zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
this._invokeTaskCurrZone =
zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate.zone);
this._cancelTaskZS =
zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
this._cancelTaskDlgt =
zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
this._cancelTaskCurrZone =
zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate.zone);
this._hasTaskZS = null;
this._hasTaskDlgt = null;
this._hasTaskDlgtOwner = null;
this._hasTaskCurrZone = null;
var zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
var parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
if (zoneSpecHasTask || parentHasTask) {
// If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
// a case all task related interceptors must go through this ZD. We can't short circuit it.
this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
this._hasTaskDlgt = parentDelegate;
this._hasTaskDlgtOwner = this;
this._hasTaskCurrZone = zone;
if (!zoneSpec.onScheduleTask) {
this._scheduleTaskZS = DELEGATE_ZS;
this._scheduleTaskDlgt = parentDelegate;
this._scheduleTaskCurrZone = this.zone;
}
if (!zoneSpec.onInvokeTask) {
this._invokeTaskZS = DELEGATE_ZS;
this._invokeTaskDlgt = parentDelegate;
this._invokeTaskCurrZone = this.zone;
}
if (!zoneSpec.onCancelTask) {
this._cancelTaskZS = DELEGATE_ZS;
this._cancelTaskDlgt = parentDelegate;
this._cancelTaskCurrZone = this.zone;
}
}
}
ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) {
return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) :
new Zone(targetZone, zoneSpec);
};
ZoneDelegate.prototype.intercept = function (targetZone, callback, source) {
return this._interceptZS ?
this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) :
callback;
};
ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
return this._invokeZS ?
this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.handleError = function (targetZone, error) {
return this._handleErrorZS ?
this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) :
true;
};
ZoneDelegate.prototype.scheduleTask = function (targetZone, task) {
var returnTask = task;
if (this._scheduleTaskZS) {
if (this._hasTaskZS) {
returnTask._zoneDelegates.push(this._hasTaskDlgtOwner);
}
returnTask = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);
if (!returnTask)
returnTask = task;
}
else {
if (task.scheduleFn) {
task.scheduleFn(task);
}
else if (task.type == microTask) {
scheduleMicroTask(task);
}
else {
throw new Error('Task is missing scheduleFn.');
}
}
return returnTask;
};
ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
return this._invokeTaskZS ?
this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
task.callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
var value;
if (this._cancelTaskZS) {
value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);
}
else {
if (!task.cancelFn) {
throw Error('Task is not cancelable');
}
value = task.cancelFn(task);
}
return value;
};
ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) {
// hasTask should not throw error so other ZoneDelegate
// can still trigger hasTask callback
try {
return this._hasTaskZS &&
this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
}
catch (err) {
this.handleError(targetZone, err);
}
};
ZoneDelegate.prototype._updateTaskCount = function (type, count) {
var counts = this._taskCounts;
var prev = counts[type];
var next = counts[type] = prev + count;
if (next < 0) {
throw new Error('More tasks executed then were scheduled.');
}
if (prev == 0 || next == 0) {
var isEmpty = {
microTask: counts['microTask'] > 0,
macroTask: counts['macroTask'] > 0,
eventTask: counts['eventTask'] > 0,
change: type
};
this.hasTask(this.zone, isEmpty);
}
};
return ZoneDelegate;
}());
var ZoneTask = (function () {
function ZoneTask(type, source, callback, options, scheduleFn, cancelFn) {
this._zone = null;
this.runCount = 0;
this._zoneDelegates = null;
this._state = 'notScheduled';
this.type = type;
this.source = source;
this.data = options;
this.scheduleFn = scheduleFn;
this.cancelFn = cancelFn;
this.callback = callback;
var self = this;
if (type === eventTask && options && options.isUsingGlobalCallback) {
this.invoke = ZoneTask.invokeTask;
}
else {
this.invoke = function () {
return ZoneTask.invokeTask.apply(global, [self, this, arguments]);
};
}
}
ZoneTask.invokeTask = function (task, target, args) {
if (!task) {
task = this;
}
_numberOfNestedTaskFrames++;
try {
task.runCount++;
return task.zone.runTask(task, target, args);
}
finally {
if (_numberOfNestedTaskFrames == 1) {
drainMicroTaskQueue();
}
_numberOfNestedTaskFrames--;
}
};
Object.defineProperty(ZoneTask.prototype, "zone", {
get: function () {
return this._zone;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ZoneTask.prototype, "state", {
get: function () {
return this._state;
},
enumerable: true,
configurable: true
});
ZoneTask.prototype.cancelScheduleRequest = function () {
this._transitionTo(notScheduled, scheduling);
};
ZoneTask.prototype._transitionTo = function (toState, fromState1, fromState2) {
if (this._state === fromState1 || this._state === fromState2) {
this._state = toState;
if (toState == notScheduled) {
this._zoneDelegates = null;
}
}
else {
throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ?
' or \'' + fromState2 + '\'' :
'') + ", was '" + this._state + "'.");
}
};
ZoneTask.prototype.toString = function () {
if (this.data && typeof this.data.handleId !== 'undefined') {
return this.data.handleId;
}
else {
return Object.prototype.toString.call(this);
}
};
// add toJSON method to prevent cyclic error when
// call JSON.stringify(zoneTask)
ZoneTask.prototype.toJSON = function () {
return {
type: this.type,
state: this.state,
source: this.source,
zone: this.zone.name,
invoke: this.invoke,
scheduleFn: this.scheduleFn,
cancelFn: this.cancelFn,
runCount: this.runCount,
callback: this.callback
};
};
return ZoneTask;
}());
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/// MICROTASK QUEUE
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
var symbolSetTimeout = __symbol__('setTimeout');
var symbolPromise = __symbol__('Promise');
var symbolThen = __symbol__('then');
var _microTaskQueue = [];
var _isDrainingMicrotaskQueue = false;
var nativeMicroTaskQueuePromise;
function scheduleMicroTask(task) {
// if we are not running in any task, and there has not been anything scheduled
// we must bootstrap the initial task creation by manually scheduling the drain
if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
// We are not running in Task, so we need to kickstart the microtask queue.
if (!nativeMicroTaskQueuePromise) {
if (global[symbolPromise]) {
nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
}
}
if (nativeMicroTaskQueuePromise) {
nativeMicroTaskQueuePromise[symbolThen](drainMicroTaskQueue);
}
else {
global[symbolSetTimeout](drainMicroTaskQueue, 0);
}
}
task && _microTaskQueue.push(task);
}
function drainMicroTaskQueue() {
if (!_isDrainingMicrotaskQueue) {
_isDrainingMicrotaskQueue = true;
while (_microTaskQueue.length) {
var queue = _microTaskQueue;
_microTaskQueue = [];
for (var i = 0; i < queue.length; i++) {
var task = queue[i];
try {
task.zone.runTask(task, null, null);
}
catch (error) {
_api.onUnhandledError(error);
}
}
}
var showError = !Zone[__symbol__('ignoreConsoleErrorUncaughtError')];
_api.microtaskDrainDone();
_isDrainingMicrotaskQueue = false;
}
}
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/// BOOTSTRAP
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
var NO_ZONE = { name: 'NO ZONE' };
var notScheduled = 'notScheduled', scheduling = 'scheduling', scheduled = 'scheduled', running = 'running', canceling = 'canceling', unknown = 'unknown';
var microTask = 'microTask', macroTask = 'macroTask', eventTask = 'eventTask';
var patches = {};
var _api = {
symbol: __symbol__,
currentZoneFrame: function () { return _currentZoneFrame; },
onUnhandledError: noop,
microtaskDrainDone: noop,
scheduleMicroTask: scheduleMicroTask,
showUncaughtError: function () { return !Zone[__symbol__('ignoreConsoleErrorUncaughtError')]; },
patchEventTarget: function () { return []; },
patchOnProperties: noop,
patchMethod: function () { return noop; },
setNativePromise: function (NativePromise) {
nativeMicroTaskQueuePromise = NativePromise.resolve(0);
},
};
var _currentZoneFrame = { parent: null, zone: new Zone(null, null) };
var _currentTask = null;
var _numberOfNestedTaskFrames = 0;
function noop() { }
function __symbol__(name) {
return '__zone_symbol__' + name;
}
performanceMeasure('Zone', 'Zone');
return global['Zone'] = Zone;
})(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
var __read = (undefined && undefined.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __values = (undefined && undefined.__values) || function (o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
};
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
var __symbol__ = api.symbol;
var _uncaughtPromiseErrors = [];
var symbolPromise = __symbol__('Promise');
var symbolThen = __symbol__('then');
api.onUnhandledError = function (e) {
if (api.showUncaughtError()) {
var rejection = e && e.rejection;
if (rejection) {
console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);
}
else {
console.error(e);
}
}
};
api.microtaskDrainDone = function () {
while (_uncaughtPromiseErrors.length) {
var _loop_1 = function () {
var uncaughtPromiseError = _uncaughtPromiseErrors.shift();
try {
uncaughtPromiseError.zone.runGuarded(function () {
throw uncaughtPromiseError;
});
}
catch (error) {
handleUnhandledRejection(error);
}
};
while (_uncaughtPromiseErrors.length) {
_loop_1();
}
}
};
var UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
function handleUnhandledRejection(e) {
api.onUnhandledError(e);
try {
var handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
if (handler && typeof handler === 'function') {
handler.apply(this, [e]);
}
}
catch (err) {
}
}
function isThenable(value) {
return value && value.then;
}
function forwardResolution(value) {
return value;
}
function forwardRejection(rejection) {
return ZoneAwarePromise.reject(rejection);
}
var symbolState = __symbol__('state');
var symbolValue = __symbol__('value');
var source = 'Promise.then';
var UNRESOLVED = null;
var RESOLVED = true;
var REJECTED = false;
var REJECTED_NO_CATCH = 0;
function makeResolver(promise, state) {
return function (v) {
try {
resolvePromise(promise, state, v);
}
catch (err) {
resolvePromise(promise, false, err);
}
// Do not return value or you will break the Promise spec.
};
}
var once = function () {
var wasCalled = false;
return function wrapper(wrappedFunction) {
return function () {
if (wasCalled) {
return;
}
wasCalled = true;
wrappedFunction.apply(null, arguments);
};
};
};
var TYPE_ERROR = 'Promise resolved with itself';
var OBJECT = 'object';
var FUNCTION = 'function';
var CURRENT_TASK_SYMBOL = __symbol__('currentTask');
// Promise Resolution
function resolvePromise(promise, state, value) {
var onceWrapper = once();
if (promise === value) {
throw new TypeError(TYPE_ERROR);
}
if (promise[symbolState] === UNRESOLVED) {
// should only get value.then once based on promise spec.
var then = null;
try {
if (typeof value === OBJECT || typeof value === FUNCTION) {
then = value && value.then;
}
}
catch (err) {
onceWrapper(function () {
resolvePromise(promise, false, err);
})();
return promise;
}
// if (value instanceof ZoneAwarePromise) {
if (state !== REJECTED && value instanceof ZoneAwarePromise &&
value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
value[symbolState] !== UNRESOLVED) {
clearRejectedNoCatch(value);
resolvePromise(promise, value[symbolState], value[symbolValue]);
}
else if (state !== REJECTED && typeof then === FUNCTION) {
try {
then.apply(value, [
onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false))
]);
}
catch (err) {
onceWrapper(function () {
resolvePromise(promise, false, err);
})();
}
}
else {
promise[symbolState] = state;
var queue = promise[symbolValue];
promise[symbolValue] = value;
// record task information in value when error occurs, so we can
// do some additional work such as render longStackTrace
if (state === REJECTED && value instanceof Error) {
value[CURRENT_TASK_SYMBOL] = Zone.currentTask;
}
for (var i = 0; i < queue.length;) {
scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
}
if (queue.length == 0 && state == REJECTED) {
promise[symbolState] = REJECTED_NO_CATCH;
try {
throw new Error('Uncaught (in promise): ' + value +
(value && value.stack ? '\n' + value.stack : ''));
}
catch (err) {
var error_1 = err;
error_1.rejection = value;
error_1.promise = promise;
error_1.zone = Zone.current;
error_1.task = Zone.currentTask;
_uncaughtPromiseErrors.push(error_1);
api.scheduleMicroTask(); // to make sure that it is running
}
}
}
}
// Resolving an already resolved promise is a noop.
return promise;
}
var REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
function clearRejectedNoCatch(promise) {
if (promise[symbolState] === REJECTED_NO_CATCH) {
// if the promise is rejected no catch status
// and queue.length > 0, means there is a error handler
// here to handle the rejected promise, we should trigger
// windows.rejectionhandled eventHandler or nodejs rejectionHandled
// eventHandler
try {
var handler = Zone[REJECTION_HANDLED_HANDLER];
if (handler && typeof handler === FUNCTION) {
handler.apply(this, [{ rejection: promise[symbolValue], promise: promise }]);
}
}
catch (err) {
}
promise[symbolState] = REJECTED;
for (var i = 0; i < _uncaughtPromiseErrors.length; i++) {
if (promise === _uncaughtPromiseErrors[i].promise) {
_uncaughtPromiseErrors.splice(i, 1);
}
}
}
}
function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
clearRejectedNoCatch(promise);
var delegate = promise[symbolState] ?
(typeof onFulfilled === FUNCTION) ? onFulfilled : forwardResolution :
(typeof onRejected === FUNCTION) ? onRejected : forwardRejection;
zone.scheduleMicroTask(source, function () {
try {
resolvePromise(chainPromise, true, zone.run(delegate, undefined, [promise[symbolValue]]));
}
catch (error) {
resolvePromise(chainPromise, false, error);
}
});
}
var ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
var ZoneAwarePromise = (function () {
function ZoneAwarePromise(executor) {
var promise = this;
if (!(promise instanceof ZoneAwarePromise)) {
throw new Error('Must be an instanceof Promise.');
}
promise[symbolState] = UNRESOLVED;
promise[symbolValue] = []; // queue;
try {
executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));
}
catch (error) {
resolvePromise(promise, false, error);
}
}
ZoneAwarePromise.toString = function () {
return ZONE_AWARE_PROMISE_TO_STRING;
};
ZoneAwarePromise.resolve = function (value) {
return resolvePromise(new this(null), RESOLVED, value);
};
ZoneAwarePromise.reject = function (error) {
return resolvePromise(new this(null), REJECTED, error);
};
ZoneAwarePromise.race = function (values) {
var resolve;
var reject;
var promise = new this(function (res, rej) {
_a = __read([res, rej], 2), resolve = _a[0], reject = _a[1];
var _a;
});
function onResolve(value) {
promise && (promise = null || resolve(value));
}
function onReject(error) {
promise && (promise = null || reject(error));
}
try {
for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
var value = values_1_1.value;
if (!isThenable(value)) {
value = this.resolve(value);
}
value.then(onResolve, onReject);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
}
finally { if (e_1) throw e_1.error; }
}
return promise;
var e_1, _a;
};
ZoneAwarePromise.all = function (values) {
var resolve;
var reject;
var promise = new this(function (res, rej) {
resolve = res;
reject = rej;
});
var count = 0;
var resolvedValues = [];
try {
for (var values_2 = __values(values), values_2_1 = values_2.next(); !values_2_1.done; values_2_1 = values_2.next()) {
var value = values_2_1.value;
if (!isThenable(value)) {
value = this.resolve(value);
}
value.then((function (index) { return function (value) {
resolvedValues[index] = value;
count--;
if (!count) {
resolve(resolvedValues);
}
}; })(count), reject);
count++;
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (values_2_1 && !values_2_1.done && (_a = values_2.return)) _a.call(values_2);
}
finally { if (e_2) throw e_2.error; }
}
if (!count)
resolve(resolvedValues);
return promise;
var e_2, _a;
};
ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
var chainPromise = new this.constructor(null);
var zone = Zone.current;
if (this[symbolState] == UNRESOLVED) {
this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
}
else {
scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
}
return chainPromise;
};
ZoneAwarePromise.prototype.catch = function (onRejected) {
return this.then(null, onRejected);
};
return ZoneAwarePromise;
}());
// Protect against aggressive optimizers dropping seemingly unused properties.
// E.g. Closure Compiler in advanced mode.
ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
ZoneAwarePromise['race'] = ZoneAwarePromise.race;
ZoneAwarePromise['all'] = ZoneAwarePromise.all;
var NativePromise = global[symbolPromise] = global['Promise'];
var ZONE_AWARE_PROMISE = Zone.__symbol__('ZoneAwarePromise');
var desc = Object.getOwnPropertyDescriptor(global, 'Promise');
if (!desc || desc.configurable) {
desc && delete desc.writable;
desc && delete desc.value;
if (!desc) {
desc = { configurable: true, enumerable: true };
}
desc.get = function () {
// if we already set ZoneAwarePromise, use patched one
// otherwise return native one.
return global[ZONE_AWARE_PROMISE] ? global[ZONE_AWARE_PROMISE] : global[symbolPromise];
};
desc.set = function (NewNativePromise) {
if (NewNativePromise === ZoneAwarePromise) {
// if the NewNativePromise is ZoneAwarePromise
// save to global
global[ZONE_AWARE_PROMISE] = NewNativePromise;
}
else {
// if the NewNativePromise is not ZoneAwarePromise
// for example: after load zone.js, some library just
// set es6-promise to global, if we set it to global
// directly, assertZonePatched will fail and angular
// will not loaded, so we just set the NewNativePromise
// to global[symbolPromise], so the result is just like
// we load ES6 Promise before zone.js
global[symbolPromise] = NewNativePromise;
if (!NewNativePromise.prototype[symbolThen]) {
patchThen(NewNativePromise);
}
api.setNativePromise(NewNativePromise);
}
};
Object.defineProperty(global, 'Promise', desc);
}
global['Promise'] = ZoneAwarePromise;
var symbolThenPatched = __symbol__('thenPatched');
function patchThen(Ctor) {
var proto = Ctor.prototype;
var originalThen = proto.then;
// Keep a reference to the original method.
proto[symbolThen] = originalThen;
// check Ctor.prototype.then propertyDescritor is writable or not
// in meteor env, writable is false, we have to make it to be true.
var prop = Object.getOwnPropertyDescriptor(Ctor.prototype, 'then');
if (prop && prop.writable === false && prop.configurable) {
Object.defineProperty(Ctor.prototype, 'then', { writable: true });
}
Ctor.prototype.then = function (onResolve, onReject) {
var _this = this;
var wrapped = new ZoneAwarePromise(function (resolve, reject) {
originalThen.call(_this, resolve, reject);
});
return wrapped.then(onResolve, onReject);
};
Ctor[symbolThenPatched] = true;
}
function zoneify(fn) {
return function () {
var resultPromise = fn.apply(this, arguments);
if (resultPromise instanceof ZoneAwarePromise) {
return resultPromise;
}
var ctor = resultPromise.constructor;
if (!ctor[symbolThenPatched]) {
patchThen(ctor);
}
return resultPromise;
};
}
if (NativePromise) {
patchThen(NativePromise);
var fetch_1 = global['fetch'];
if (typeof fetch_1 == FUNCTION) {
global['fetch'] = zoneify(fetch_1);
}
}
// This is not part of public API, but it is useful for tests, so we expose it.
Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
return ZoneAwarePromise;
});
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Suppress closure compiler errors about unknown 'Zone' variable
* @fileoverview
* @suppress {undefinedVars,globalThis,missingRequire}
*/
var zoneSymbol = Zone.__symbol__;
var _global = typeof window === 'object' && window || typeof self === 'object' && self || global;
var FUNCTION = 'function';
var UNDEFINED = 'undefined';
var REMOVE_ATTRIBUTE = 'removeAttribute';
function bindArguments(args, source) {
for (var i = args.length - 1; i >= 0; i--) {
if (typeof args[i] === FUNCTION) {
args[i] = Zone.current.wrap(args[i], source + '_' + i);
}
}
return args;
}
function patchPrototype(prototype, fnNames) {
var source = prototype.constructor['name'];
var _loop_1 = function (i) {
var name_1 = fnNames[i];
var delegate = prototype[name_1];
if (delegate) {
var prototypeDesc = Object.getOwnPropertyDescriptor(prototype, name_1);
if (!isPropertyWritable(prototypeDesc)) {
return "continue";
}
prototype[name_1] = (function (delegate) {
var patched = function () {
return delegate.apply(this, bindArguments(arguments, source + '.' + name_1));
};
attachOriginToPatched(patched, delegate);
return patched;
})(delegate);
}
};
for (var i = 0; i < fnNames.length; i++) {
_loop_1(i);
}
}
function isPropertyWritable(propertyDesc) {
if (!propertyDesc) {
return true;
}
if (propertyDesc.writable === false) {
return false;
}
if (typeof propertyDesc.get === FUNCTION && typeof propertyDesc.set === UNDEFINED) {
return false;
}
return true;
}
var isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
// Make sure to access `process` through `_global` so that WebPack does not accidently browserify
// this code.
var isNode = (!('nw' in _global) && typeof _global.process !== 'undefined' &&
{}.toString.call(_global.process) === '[object process]');
var isBrowser = !isNode && !isWebWorker && !!(typeof window !== 'undefined' && window['HTMLElement']);
// we are in electron of nw, so we are both browser and nodejs
// Make sure to access `process` through `_global` so that WebPack does not accidently browserify
// this code.
var isMix = typeof _global.process !== 'undefined' &&
{}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
!!(typeof window !== 'undefined' && window['HTMLElement']);
var zoneSymbolEventNames = {};
var wrapFn = function (event) {
// https://github.com/angular/zone.js/issues/911, in IE, sometimes
// event will be undefined, so we need to use window.event
event = event || _global.event;
if (!event) {
return;
}
var eventNameSymbol = zoneSymbolEventNames[event.type];
if (!eventNameSymbol) {
eventNameSymbol = zoneSymbolEventNames[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
}
var target = this || event.target || _global;
var listener = target[eventNameSymbol];
var result = listener && listener.apply(this, arguments);
if (result != undefined && !result) {
event.preventDefault();
}
return result;
};
function patchProperty(obj, prop, prototype) {
var desc = Object.getOwnPropertyDescriptor(obj, prop);
if (!desc && prototype) {
// when patch window object, use prototype to check prop exist or not
var prototypeDesc = Object.getOwnPropertyDescriptor(prototype, prop);
if (prototypeDesc) {
desc = { enumerable: true, configurable: true };
}
}
// if the descriptor not exists or is not configurable
// just return
if (!desc || !desc.configurable) {
return;
}
// A property descriptor cannot have getter/setter and be writable
// deleting the writable and value properties avoids this error:
//
// TypeError: property descriptors must not specify a value or be writable when a
// getter or setter has been specified
delete desc.writable;
delete desc.value;
var originalDescGet = desc.get;
// substr(2) cuz 'onclick' -> 'click', etc
var eventName = prop.substr(2);
var eventNameSymbol = zoneSymbolEventNames[eventName];
if (!eventNameSymbol) {
eventNameSymbol = zoneSymbolEventNames[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
}
desc.set = function (newValue) {
// in some of windows's onproperty callback, this is undefined
// so we need to check it
var target = this;
if (!target && obj === _global) {
target = _global;
}
if (!target) {
return;
}
var previousValue = target[eventNameSymbol];
if (previousValue) {
target.removeEventListener(eventName, wrapFn);
}
if (typeof newValue === 'function') {
target[eventNameSymbol] = newValue;
target.addEventListener(eventName, wrapFn, false);
}
else {
target[eventNameSymbol] = null;
}
};
// The getter would return undefined for unassigned properties but the default value of an
// unassigned property is null
desc.get = function () {
// in some of windows's onproperty callback, this is undefined
// so we need to check it
var target = this;
if (!target && obj === _global) {
target = _global;
}
if (!target) {
return null;
}
var listener = target[eventNameSymbol];
if (listener) {
return listener;
}
else if (originalDescGet) {
// result will be null when use inline event attribute,
// such as <button onclick="func();">OK</button>
// because the onclick function is internal raw uncompiled handler
// the onclick will be evaluated when first time event was triggered or
// the property is accessed, https://github.com/angular/zone.js/issues/525
// so we should use original native get to retrieve the handler
var value = originalDescGet && originalDescGet.apply(this);
if (value) {
desc.set.apply(this, [value]);
if (typeof target[REMOVE_ATTRIBUTE] === FUNCTION) {
target.removeAttribute(prop);
}
return value;
}
}
return null;
};
Object.defineProperty(obj, prop, desc);
}
function patchOnProperties(obj, properties, prototype) {
if (properties) {
for (var i = 0; i < properties.length; i++) {
patchProperty(obj, 'on' + properties[i], prototype);
}
}
else {
var onProperties = [];
for (var prop in obj) {
if (prop.substr(0, 2) == 'on') {
onProperties.push(prop);
}
}
for (var j = 0; j < onProperties.length; j++) {
patchProperty(obj, onProperties[j], prototype);
}
}
}
var originalInstanceKey = zoneSymbol('originalInstance');
// wrap some native API on `window`
function patchClass(className) {
var OriginalClass = _global[className];
if (!OriginalClass)
return;
// keep original class in global
_global[zoneSymbol(className)] = OriginalClass;
_global[className] = function () {
var a = bindArguments(arguments, className);
switch (a.length) {
case 0:
this[originalInstanceKey] = new OriginalClass();
break;
case 1:
this[originalInstanceKey] = new OriginalClass(a[0]);
break;
case 2:
this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
break;
case 3:
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
break;
case 4:
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
break;
default:
throw new Error('Arg list too long.');
}
};
// attach original delegate to patched function
attachOriginToPatched(_global[className], OriginalClass);
var instance = new OriginalClass(function () { });
var prop;
for (prop in instance) {
// https://bugs.webkit.org/show_bug.cgi?id=44721
if (className === 'XMLHttpRequest' && prop === 'responseBlob')
continue;
(function (prop) {
if (typeof instance[prop] === 'function') {
_global[className].prototype[prop] = function () {
return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
};
}
else {
Object.defineProperty(_global[className].prototype, prop, {
set: function (fn) {
if (typeof fn === 'function') {
this[originalInstanceKey][prop] = Zone.current.wrap(fn, className + '.' + prop);
// keep callback in wrapped function so we can
// use it in Function.prototype.toString to return
// the native one.
attachOriginToPatched(this[originalInstanceKey][prop], fn);
}
else {
this[originalInstanceKey][prop] = fn;
}
},
get: function () {
return this[originalInstanceKey][prop];
}
});
}
}(prop));
}
for (prop in OriginalClass) {
if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
_global[className][prop] = OriginalClass[prop];
}
}
}
function patchMethod(target, name, patchFn) {
var proto = target;
while (proto && !proto.hasOwnProperty(name)) {
proto = Object.getPrototypeOf(proto);
}
if (!proto && target[name]) {
// somehow we did not find it, but we can see it. This happens on IE for Window properties.
proto = target;
}
var delegateName = zoneSymbol(name);
var delegate;
if (proto && !(delegate = proto[delegateName])) {
delegate = proto[delegateName] = proto[name];
// check whether proto[name] is writable
// some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
var desc = proto && Object.getOwnPropertyDescriptor(proto, name);
if (isPropertyWritable(desc)) {
var patchDelegate_1 = patchFn(delegate, delegateName, name);
proto[name] = function () {
return patchDelegate_1(this, arguments);
};
attachOriginToPatched(proto[name], delegate);
}
}
return delegate;
}
// TODO: @JiaLiPassion, support cancel task later if necessary
function patchMacroTask(obj, funcName, metaCreator) {
var setNative = null;
function scheduleTask(task) {
var data = task.data;
data.args[data.callbackIndex] = function () {
task.invoke.apply(this, arguments);
};
setNative.apply(data.target, data.args);
return task;
}
setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
var meta = metaCreator(self, args);
if (meta.callbackIndex >= 0 && typeof args[meta.callbackIndex] === 'function') {
var task = Zone.current.scheduleMacroTask(meta.name, args[meta.callbackIndex], meta, scheduleTask, null);
return task;
}
else {
// cause an error by calling it directly.
return delegate.apply(self, args);
}
}; });
}
function attachOriginToPatched(patched, original) {
patched[zoneSymbol('OriginalDelegate')] = original;
}
var isDetectedIEOrEdge = false;
var ieOrEdge = false;
function isIEOrEdge() {
if (isDetectedIEOrEdge) {
return ieOrEdge;
}
isDetectedIEOrEdge = true;
try {
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
ieOrEdge = true;
}
return ieOrEdge;
}
catch (error) {
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// override Function.prototype.toString to make zone.js patched function
// look like native function
Zone.__load_patch('toString', function (global, Zone, api) {
// patch Func.prototype.toString to let them look like native
var originalFunctionToString = Zone['__zone_symbol__originalToString'] =
Function.prototype.toString;
var FUNCTION = 'function';
var ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
var PROMISE_SYMBOL = zoneSymbol('Promise');
var ERROR_SYMBOL = zoneSymbol('Error');
Function.prototype.toString = function () {
if (typeof this === FUNCTION) {
var originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
if (originalDelegate) {
if (typeof originalDelegate === FUNCTION) {
return originalFunctionToString.apply(this[ORIGINAL_DELEGATE_SYMBOL], arguments);
}
else {
return Object.prototype.toString.call(originalDelegate);
}
}
if (this === Promise) {
var nativePromise = global[PROMISE_SYMBOL];
if (nativePromise) {
return originalFunctionToString.apply(nativePromise, arguments);
}
}
if (this === Error) {
var nativeError = global[ERROR_SYMBOL];
if (nativeError) {
return originalFunctionToString.apply(nativeError, arguments);
}
}
}
return originalFunctionToString.apply(this, arguments);
};
// patch Object.prototype.toString to let them look like native
var originalObjectToString = Object.prototype.toString;
var PROMISE_OBJECT_TO_STRING = '[object Promise]';
Object.prototype.toString = function () {
if (this instanceof Promise) {
return PROMISE_OBJECT_TO_STRING;
}
return originalObjectToString.apply(this, arguments);
};
});
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @fileoverview
* @suppress {missingRequire}
*/
var __read$1 = (undefined && undefined.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (undefined && undefined.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read$1(arguments[i]));
return ar;
};
var TRUE_STR = 'true';
var FALSE_STR = 'false';
// an identifier to tell ZoneTask do not create a new invoke closure
var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
isUsingGlobalCallback: true
};
var zoneSymbolEventNames$1 = {};
var globalSources = {};
var CONSTRUCTOR_NAME = 'name';
var FUNCTION_TYPE = 'function';
var OBJECT_TYPE = 'object';
var ZONE_SYMBOL_PREFIX = '__zone_symbol__';
var EVENT_NAME_SYMBOL_REGX = /^__zone_symbol__(\w+)(true|false)$/;
var IMMEDIATE_PROPAGATION_SYMBOL = ('__zone_symbol__propagationStopped');
function patchEventTarget(_global, apis, patchOptions) {
var ADD_EVENT_LISTENER = (patchOptions && patchOptions.addEventListenerFnName) || 'addEventListener';
var REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.removeEventListenerFnName) || 'removeEventListener';
var LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listenersFnName) || 'eventListeners';
var REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.removeAllFnName) || 'removeAllListeners';
var zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
var ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
var PREPEND_EVENT_LISTENER = 'prependListener';
var PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
var invokeTask = function (task, target, event) {
// for better performance, check isRemoved which is set
// by removeEventListener
if (task.isRemoved) {
return;
}
var delegate = task.callback;
if (typeof delegate === OBJECT_TYPE && delegate.handleEvent) {
// create the bind version of handleEvent when invoke
task.callback = function (event) { return delegate.handleEvent(event); };
task.originalDelegate = delegate;
}
// invoke static task.invoke
task.invoke(task, target, [event]);
var options = task.options;
if (options && typeof options === 'object' && options.once) {
// if options.once is true, after invoke once remove listener here
// only browser need to do this, nodejs eventEmitter will cal removeListener
// inside EventEmitter.once
var delegate_1 = task.originalDelegate ? task.originalDelegate : task.callback;
target[REMOVE_EVENT_LISTENER].apply(target, [event.type, delegate_1, options]);
}
};
// global shared zoneAwareCallback to handle all event callback with capture = false
var globalZoneAwareCallback = function (event) {
// https://github.com/angular/zone.js/issues/911, in IE, sometimes
// event will be undefined, so we need to use window.event
event = event || _global.event;
if (!event) {
return;
}
// event.target is needed for Samusung TV and SourceBuffer
// || global is needed https://github.com/angular/zone.js/issues/190
var target = this || event.target || _global;
var tasks = target[zoneSymbolEventNames$1[event.type][FALSE_STR]];
if (tasks) {
// invoke all tasks which attached to current target with given event.type and capture = false
// for performance concern, if task.length === 1, just invoke
if (tasks.length === 1) {
invokeTask(tasks[0], target, event);
}
else {
// https://github.com/angular/zone.js/issues/836
// copy the tasks array before invoke, to avoid
// the callback will remove itself or other listener
var copyTasks = tasks.slice();
for (var i = 0; i < copyTasks.length; i++) {
if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
break;
}
invokeTask(copyTasks[i], target, event);
}
}
}
};
// global shared zoneAwareCallback to handle all event callback with capture = true
var globalZoneAwareCaptureCallback = function (event) {
// https://github.com/angular/zone.js/issues/911, in IE, sometimes
// event will be undefined, so we need to use window.event
event = event || _global.event;
if (!event) {
return;
}
// event.target is needed for Samusung TV and SourceBuffer
// || global is needed https://github.com/angular/zone.js/issues/190
var target = this || event.target || _global;
var tasks = target[zoneSymbolEventNames$1[event.type][TRUE_STR]];
if (tasks) {
// invoke all tasks which attached to current target with given event.type and capture = false
// for performance concern, if task.length === 1, just invoke
if (tasks.length === 1) {
invokeTask(tasks[0], target, event);
}
else {
// https://github.com/angular/zone.js/issues/836
// copy the tasks array before invoke, to avoid
// the callback will remove itself or other listener
var copyTasks = tasks.slice();
for (var i = 0; i < copyTasks.length; i++) {
if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
break;
}
invokeTask(copyTasks[i], target, event);
}
}
}
};
function patchEventTargetMethods(obj, patchOptions) {
if (!obj) {
return false;
}
var useGlobalCallback = true;
if (patchOptions && patchOptions.useGlobalCallback !== undefined) {
useGlobalCallback = patchOptions.useGlobalCallback;
}
var validateHandler = patchOptions && patchOptions.validateHandler;
var checkDuplicate = true;
if (patchOptions && patchOptions.checkDuplicate !== undefined) {
checkDuplicate = patchOptions.checkDuplicate;
}
var returnTarget = false;
if (patchOptions && patchOptions.returnTarget !== undefined) {
returnTarget = patchOptions.returnTarget;
}
var proto = obj;
while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
proto = Object.getPrototypeOf(proto);
}
if (!proto && obj[ADD_EVENT_LISTENER]) {
// somehow we did not find it, but we can see it. This happens on IE for Window properties.
proto = obj;
}
if (!proto) {
return false;
}
if (proto[zoneSymbolAddEventListener]) {
return false;
}
// a shared global taskData to pass data for scheduleEventTask
// so we do not need to create a new object just for pass some data
var taskData = {};
var nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
var nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
proto[REMOVE_EVENT_LISTENER];
var nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
proto[LISTENERS_EVENT_LISTENER];
var nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
var nativePrependEventListener;
if (patchOptions && patchOptions.prependEventListenerFnName) {
nativePrependEventListener = proto[zoneSymbol(patchOptions.prependEventListenerFnName)] =
proto[patchOptions.prependEventListenerFnName];
}
var customScheduleGlobal = function (task) {
// if there is already a task for the eventName + capture,
// just return, because we use the shared globalZoneAwareCallback here.
if (taskData.isExisting) {
return;
}
return nativeAddEventListener.apply(taskData.target, [
taskData.eventName,
taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback,
taskData.options
]);
};
var customCancelGlobal = function (task) {
// if task is not marked as isRemoved, this call is directly
// from Zone.prototype.cancelTask, we should remove the task
// from tasksList of target first
if (!task.isRemoved) {
var symbolEventNames = zoneSymbolEventNames$1[task.eventName];
var symbolEventName = void 0;
if (symbolEventNames) {
symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
}
var existingTasks = symbolEventName && task.target[symbolEventName];
if (existingTasks) {
for (var i = 0; i < existingTasks.length; i++) {
var existingTask = existingTasks[i];
if (existingTask === task) {
existingTasks.splice(i, 1);
// set isRemoved to data for faster invokeTask check
task.isRemoved = true;
if (existingTasks.length === 0) {
// all tasks for the eventName + capture have gone,
// remove globalZoneAwareCallback and remove the task cache from target
task.allRemoved = true;
task.target[symbolEventName] = null;
}
break;
}
}
}
}
// if all tasks for the eventName + capture have gone,
// we will really remove the global event callback,
// if not, return
if (!task.allRemoved) {
return;
}
return nativeRemoveEventListener.apply(task.target, [
task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback,
task.options
]);
};
var customScheduleNonGlobal = function (task) {
return nativeAddEventListener.apply(taskData.target, [taskData.eventName, task.invoke, taskData.options]);
};
var customSchedulePrepend = function (task) {
return nativePrependEventListener.apply(taskData.target, [taskData.eventName, task.invoke, taskData.options]);
};
var customCancelNonGlobal = function (task) {
return nativeRemoveEventListener.apply(task.target, [task.eventName, task.invoke, task.options]);
};
var customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
var customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
var compareTaskCallbackVsDelegate = function (task, delegate) {
var typeOfDelegate = typeof delegate;
if ((typeOfDelegate === FUNCTION_TYPE && task.callback === delegate) ||
(typeOfDelegate === OBJECT_TYPE && task.originalDelegate === delegate)) {
// same callback, same capture, same event name, just return
return true;
}
return false;
};
var compare = (patchOptions && patchOptions.compareTaskCallbackVsDelegate) ?
patchOptions.compareTaskCallbackVsDelegate :
compareTaskCallbackVsDelegate;
var makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget, prepend) {
if (returnTarget === void 0) { returnTarget = false; }
if (prepend === void 0) { prepend = false; }
return function () {
var target = this || _global;
var targetZone = Zone.current;
var delegate = arguments[1];
if (!delegate) {
return nativeListener.apply(this, arguments);
}
// don't create the bind delegate function for handleEvent
// case here to improve addEventListener performance
// we will create the bind delegate when invoke
var isHandleEvent = false;
if (typeof delegate !== FUNCTION_TYPE) {
if (!delegate.handleEvent) {
return nativeListener.apply(this, arguments);
}
isHandleEvent = true;
}
if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
return;
}
var eventName = arguments[0];
var options = arguments[2];
var capture;
var once = false;
if (options === undefined) {
capture = false;
}
else if (options === true) {
capture = true;
}
else if (options === false) {
capture = false;
}
else {
capture = options ? !!options.capture : false;
once = options ? !!options.once : false;
}
var zone = Zone.current;
var symbolEventNames = zoneSymbolEventNames$1[eventName];
var symbolEventName;
if (!symbolEventNames) {
// the code is duplicate, but I just want to get some better performance
var falseEventName = eventName + FALSE_STR;
var trueEventName = eventName + TRUE_STR;
var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
zoneSymbolEventNames$1[eventName] = {};
zoneSymbolEventNames$1[eventName][FALSE_STR] = symbol;
zoneSymbolEventNames$1[eventName][TRUE_STR] = symbolCapture;
symbolEventName = capture ? symbolCapture : symbol;
}
else {
symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
}
var existingTasks = target[symbolEventName];
var isExisting = false;
if (existingTasks) {
// already have task registered
isExisting = true;
if (checkDuplicate) {
for (var i = 0; i < existingTasks.length; i++) {
if (compare(existingTasks[i], delegate)) {
// same callback, same capture, same event name, just return
return;
}
}
}
}
else {
existingTasks = target[symbolEventName] = [];
}
var source;
var constructorName = target.constructor[CONSTRUCTOR_NAME];
var targetSource = globalSources[constructorName];
if (targetSource) {
source = targetSource[eventName];
}
if (!source) {
source = constructorName + addSource + eventName;
}
// do not create a new object as task.data to pass those things
// just use the global shared one
taskData.options = options;
if (once) {
// if addEventListener with once options, we don't pass it to
// native addEventListener, instead we keep the once setting
// and handle ourselves.
taskData.options.once = false;
}
taskData.target = target;
taskData.capture = capture;
taskData.eventName = eventName;
taskData.isExisting = isExisting;
var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : null;
var task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
// have to save those information to task in case
// application may call task.zone.cancelTask() directly
if (once) {
options.once = true;
}
task.options = options;
task.target = target;
task.capture = capture;
task.eventName = eventName;
if (isHandleEvent) {
// save original delegate for compare to check duplicate
task.originalDelegate = delegate;
}
if (!prepend) {
existingTasks.push(task);
}
else {
existingTasks.unshift(task);
}
if (returnTarget) {
return target;
}
};
};
proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
if (nativePrependEventListener) {
proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
}
proto[REMOVE_EVENT_LISTENER] = function () {
var target = this || _global;
var eventName = arguments[0];
var options = arguments[2];
var capture;
if (options === undefined) {
capture = false;
}
else if (options === true) {
capture = true;
}
else if (options === false) {
capture = false;
}
else {
capture = options ? !!options.capture : false;
}
var delegate = arguments[1];
if (!delegate) {
return nativeRemoveEventListener.apply(this, arguments);
}
if (validateHandler &&
!validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
return;
}
var symbolEventNames = zoneSymbolEventNames$1[eventName];
var symbolEventName;
if (symbolEventNames) {
symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
}
var existingTasks = symbolEventName && target[symbolEventName];
if (existingTasks) {
for (var i = 0; i < existingTasks.length; i++) {
var existingTask = existingTasks[i];
var typeOfDelegate = typeof delegate;
if (compare(existingTask, delegate)) {
existingTasks.splice(i, 1);
// set isRemoved to data for faster invokeTask check
existingTask.isRemoved = true;
if (existingTasks.length === 0) {
// all tasks for the eventName + capture have gone,
// remove globalZoneAwareCallback and remove the task cache from target
existingTask.allRemoved = true;
target[symbolEventName] = null;
}
existingTask.zone.cancelTask(existingTask);
return;
}
}
}
};
proto[LISTENERS_EVENT_LISTENER] = function () {
var target = this || _global;
var eventName = arguments[0];
var listeners = [];
var tasks = findEventTasks(target, eventName);
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
listeners.push(delegate);
}
return listeners;
};
proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
var target = this || _global;
var eventName = arguments[0];
if (!eventName) {
var keys = Object.keys(target);
for (var i = 0; i < keys.length; i++) {
var prop = keys[i];
var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
var evtName = match && match[1];
// in nodejs EventEmitter, removeListener event is
// used for monitoring the removeListener call,
// so just keep removeListener eventListener until
// all other eventListeners are removed
if (evtName && evtName !== 'removeListener') {
this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].apply(this, [evtName]);
}
}
// remove removeListener listener finally
this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].apply(this, ['removeListener']);
}
else {
var symbolEventNames = zoneSymbolEventNames$1[eventName];
if (symbolEventNames) {
var symbolEventName = symbolEventNames[FALSE_STR];
var symbolCaptureEventName = symbolEventNames[TRUE_STR];
var tasks = target[symbolEventName];
var captureTasks = target[symbolCaptureEventName];
if (tasks) {
var removeTasks = __spread(tasks);
for (var i = 0; i < removeTasks.length; i++) {
var task = removeTasks[i];
var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
this[REMOVE_EVENT_LISTENER].apply(this, [eventName, delegate, task.options]);
}
}
if (captureTasks) {
var removeTasks = __spread(captureTasks);
for (var i = 0; i < removeTasks.length; i++) {
var task = removeTasks[i];
var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
this[REMOVE_EVENT_LISTENER].apply(this, [eventName, delegate, task.options]);
}
}
}
}
};
// for native toString patch
attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
if (nativeRemoveAllListeners) {
attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
}
if (nativeListeners) {
attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
}
return true;
}
var results = [];
for (var i = 0; i < apis.length; i++) {
results[i] = patchEventTargetMethods(apis[i], patchOptions);
}
return results;
}
function findEventTasks(target, eventName) {
var foundTasks = [];
for (var prop in target) {
var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
var evtName = match && match[1];
if (evtName && (!eventName || evtName === eventName)) {
var tasks = target[prop];
if (tasks) {
for (var i = 0; i < tasks.length; i++) {
foundTasks.push(tasks[i]);
}
}
}
}
return foundTasks;
}
function patchEventPrototype(global, api) {
var Event = global['Event'];
if (Event && Event.prototype) {
api.patchMethod(Event.prototype, 'stopImmediatePropagation', function (delegate) { return function (self, args) {
self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
}; });
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @fileoverview
* @suppress {missingRequire}
*/
var taskSymbol = zoneSymbol('zoneTask');
function patchTimer(window, setName, cancelName, nameSuffix) {
var setNative = null;
var clearNative = null;
setName += nameSuffix;
cancelName += nameSuffix;
var tasksByHandleId = {};
var NUMBER = 'number';
var STRING = 'string';
var FUNCTION = 'function';
var INTERVAL = 'Interval';
var TIMEOUT = 'Timeout';
var NOT_SCHEDULED = 'notScheduled';
function scheduleTask(task) {
var data = task.data;
function timer() {
try {
task.invoke.apply(this, arguments);
}
finally {
if (typeof data.handleId === NUMBER) {
// in non-nodejs env, we remove timerId
// from local cache
delete tasksByHandleId[data.handleId];
}
else if (data.handleId) {
// Node returns complex objects as handleIds
// we remove task reference from timer object
data.handleId[taskSymbol] = null;
}
}
}
data.args[0] = timer;
data.handleId = setNative.apply(window, data.args);
return task;
}
function clearTask(task) {
return clearNative(task.data.handleId);
}
setNative =
patchMethod(window, setName, function (delegate) { return function (self, args) {
if (typeof args[0] === FUNCTION) {
var zone = Zone.current;
var options = {
handleId: null,
isPeriodic: nameSuffix === INTERVAL,
delay: (nameSuffix === TIMEOUT || nameSuffix === INTERVAL) ? args[1] || 0 : null,
args: args
};
var task = zone.scheduleMacroTask(setName, args[0], options, scheduleTask, clearTask);
if (!task) {
return task;
}
// Node.js must additionally support the ref and unref functions.
var handle = task.data.handleId;
if (typeof handle === NUMBER) {
// for non nodejs env, we save handleId: task
// mapping in local cache for clearTimeout
tasksByHandleId[handle] = task;
}
else if (handle) {
// for nodejs env, we save task
// reference in timerId Object for clearTimeout
handle[taskSymbol] = task;
}
// check whether handle is null, because some polyfill or browser
// may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
if (handle && handle.ref && handle.unref && typeof handle.ref === FUNCTION &&
typeof handle.unref === FUNCTION) {
task.ref = handle.ref.bind(handle);
task.unref = handle.unref.bind(handle);
}
if (typeof handle === NUMBER || handle) {
return handle;
}
return task;
}
else {
// cause an error by calling it directly.
return delegate.apply(window, args);
}
}; });
clearNative =
patchMethod(window, cancelName, function (delegate) { return function (self, args) {
var id = args[0];
var task;
if (typeof id === NUMBER) {
// non nodejs env.
task = tasksByHandleId[id];
}
else {
// nodejs env.
task = id && id[taskSymbol];
// other environments.
if (!task) {
task = id;
}
}
if (task && typeof task.type === STRING) {
if (task.state !== NOT_SCHEDULED &&
(task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
if (typeof id === NUMBER) {
delete tasksByHandleId[id];
}
else if (id) {
id[taskSymbol] = null;
}
// Do not cancel already canceled functions
task.zone.cancelTask(task);
}
}
else {
// cause an error by calling it directly.
delegate.apply(window, args);
}
}; });
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/*
* This is necessary for Chrome and Chrome mobile, to enable
* things like redefining `createdCallback` on an element.
*/
var _defineProperty = Object[zoneSymbol('defineProperty')] = Object.defineProperty;
var _getOwnPropertyDescriptor = Object[zoneSymbol('getOwnPropertyDescriptor')] =
Object.getOwnPropertyDescriptor;
var _create = Object.create;
var unconfigurablesKey = zoneSymbol('unconfigurables');
var PROTOTYPE = 'prototype';
var OBJECT = 'object';
var UNDEFINED$1 = 'undefined';
function propertyPatch() {
Object.defineProperty = function (obj, prop, desc) {
if (isUnconfigurable(obj, prop)) {
throw new TypeError('Cannot assign to read only property \'' + prop + '\' of ' + obj);
}
var originalConfigurableFlag = desc.configurable;
if (prop !== PROTOTYPE) {
desc = rewriteDescriptor(obj, prop, desc);
}
return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);
};
Object.defineProperties = function (obj, props) {
Object.keys(props).forEach(function (prop) {
Object.defineProperty(obj, prop, props[prop]);
});
return obj;
};
Object.create = function (obj, proto) {
if (typeof proto === OBJECT && !Object.isFrozen(proto)) {
Object.keys(proto).forEach(function (prop) {
proto[prop] = rewriteDescriptor(obj, prop, proto[prop]);
});
}
return _create(obj, proto);
};
Object.getOwnPropertyDescriptor = function (obj, prop) {
var desc = _getOwnPropertyDescriptor(obj, prop);
if (isUnconfigurable(obj, prop)) {
desc.configurable = false;
}
return desc;
};
}
function _redefineProperty(obj, prop, desc) {
var originalConfigurableFlag = desc.configurable;
desc = rewriteDescriptor(obj, prop, desc);
return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);
}
function isUnconfigurable(obj, prop) {
return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop];
}
function rewriteDescriptor(obj, prop, desc) {
desc.configurable = true;
if (!desc.configurable) {
if (!obj[unconfigurablesKey]) {
_defineProperty(obj, unconfigurablesKey, { writable: true, value: {} });
}
obj[unconfigurablesKey][prop] = true;
}
return desc;
}
function _tryDefineProperty(obj, prop, desc, originalConfigurableFlag) {
try {
return _defineProperty(obj, prop, desc);
}
catch (error) {
if (desc.configurable) {
// In case of errors, when the configurable flag was likely set by rewriteDescriptor(), let's
// retry with the original flag value
if (typeof originalConfigurableFlag == UNDEFINED$1) {
delete desc.configurable;
}
else {
desc.configurable = originalConfigurableFlag;
}
try {
return _defineProperty(obj, prop, desc);
}
catch (error) {
var descJson = null;
try {
descJson = JSON.stringify(desc);
}
catch (error) {
descJson = descJson.toString();
}
console.log("Attempting to configure '" + prop + "' with descriptor '" + descJson + "' on object '" + obj + "' and got error, giving up: " + error);
}
}
else {
throw error;
}
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// we have to patch the instance since the proto is non-configurable
function apply(api, _global) {
var WS = _global.WebSocket;
// On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener
// On older Chrome, no need since EventTarget was already patched
if (!_global.EventTarget) {
patchEventTarget(_global, [WS.prototype]);
}
_global.WebSocket = function (a, b) {
var socket = arguments.length > 1 ? new WS(a, b) : new WS(a);
var proxySocket;
var proxySocketProto;
// Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance
var onmessageDesc = Object.getOwnPropertyDescriptor(socket, 'onmessage');
if (onmessageDesc && onmessageDesc.configurable === false) {
proxySocket = Object.create(socket);
// socket have own property descriptor 'onopen', 'onmessage', 'onclose', 'onerror'
// but proxySocket not, so we will keep socket as prototype and pass it to
// patchOnProperties method
proxySocketProto = socket;
['addEventListener', 'removeEventListener', 'send', 'close'].forEach(function (propName) {
proxySocket[propName] = function () {
var args = Array.prototype.slice.call(arguments);
if (propName === 'addEventListener' || propName === 'removeEventListener') {
var eventName = args.length > 0 ? args[0] : undefined;
if (eventName) {
var propertySymbol = Zone.__symbol__('ON_PROPERTY' + eventName);
socket[propertySymbol] = proxySocket[propertySymbol];
}
}
return socket[propName].apply(socket, args);
};
});
}
else {
// we can patch the real socket
proxySocket = socket;
}
patchOnProperties(proxySocket, ['close', 'error', 'message', 'open'], proxySocketProto);
return proxySocket;
};
var globalWebSocket = _global['WebSocket'];
for (var prop in WS) {
globalWebSocket[prop] = WS[prop];
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @fileoverview
* @suppress {globalThis}
*/
var globalEventHandlersEventNames = [
'abort',
'animationcancel',
'animationend',
'animationiteration',
'auxclick',
'beforeinput',
'blur',
'cancel',
'canplay',
'canplaythrough',
'change',
'compositionstart',
'compositionupdate',
'compositionend',
'cuechange',
'click',
'close',
'contextmenu',
'curechange',
'dblclick',
'drag',
'dragend',
'dragenter',
'dragexit',
'dragleave',
'dragover',
'drop',
'durationchange',
'emptied',
'ended',
'error',
'focus',
'focusin',
'focusout',
'gotpointercapture',
'input',
'invalid',
'keydown',
'keypress',
'keyup',
'load',
'loadstart',
'loadeddata',
'loadedmetadata',
'lostpointercapture',
'mousedown',
'mouseenter',
'mouseleave',
'mousemove',
'mouseout',
'mouseover',
'mouseup',
'mousewheel',
'orientationchange',
'pause',
'play',
'playing',
'pointercancel',
'pointerdown',
'pointerenter',
'pointerleave',
'pointerlockchange',
'mozpointerlockchange',
'webkitpointerlockerchange',
'pointerlockerror',
'mozpointerlockerror',
'webkitpointerlockerror',
'pointermove',
'pointout',
'pointerover',
'pointerup',
'progress',
'ratechange',
'reset',
'resize',
'scroll',
'seeked',
'seeking',
'select',
'selectionchange',
'selectstart',
'show',
'sort',
'stalled',
'submit',
'suspend',
'timeupdate',
'volumechange',
'touchcancel',
'touchmove',
'touchstart',
'touchend',
'transitioncancel',
'transitionend',
'waiting',
'wheel'
];
var documentEventNames = [
'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'fullscreenchange',
'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange', 'fullscreenerror',
'mozfullscreenerror', 'webkitfullscreenerror', 'msfullscreenerror', 'readystatechange',
'visibilitychange'
];
var windowEventNames = [
'absolutedeviceorientation',
'afterinput',
'afterprint',
'appinstalled',
'beforeinstallprompt',
'beforeprint',
'beforeunload',
'devicelight',
'devicemotion',
'deviceorientation',
'deviceorientationabsolute',
'deviceproximity',
'hashchange',
'languagechange',
'message',
'mozbeforepaint',
'offline',
'online',
'paint',
'pageshow',
'pagehide',
'popstate',
'rejectionhandled',
'storage',
'unhandledrejection',
'unload',
'userproximity',
'vrdisplyconnected',
'vrdisplaydisconnected',
'vrdisplaypresentchange'
];
var htmlElementEventNames = [
'beforecopy', 'beforecut', 'beforepaste', 'copy', 'cut', 'paste', 'dragstart', 'loadend',
'animationstart', 'search', 'transitionrun', 'transitionstart', 'webkitanimationend',
'webkitanimationiteration', 'webkitanimationstart', 'webkittransitionend'
];
var mediaElementEventNames = ['encrypted', 'waitingforkey', 'msneedkey', 'mozinterruptbegin', 'mozinterruptend'];
var ieElementEventNames = [
'activate',
'afterupdate',
'ariarequest',
'beforeactivate',
'beforedeactivate',
'beforeeditfocus',
'beforeupdate',
'cellchange',
'controlselect',
'dataavailable',
'datasetchanged',
'datasetcomplete',
'errorupdate',
'filterchange',
'layoutcomplete',
'losecapture',
'move',
'moveend',
'movestart',
'propertychange',
'resizeend',
'resizestart',
'rowenter',
'rowexit',
'rowsdelete',
'rowsinserted',
'command',
'compassneedscalibration',
'deactivate',
'help',
'mscontentzoom',
'msmanipulationstatechanged',
'msgesturechange',
'msgesturedoubletap',
'msgestureend',
'msgesturehold',
'msgesturestart',
'msgesturetap',
'msgotpointercapture',
'msinertiastart',
'mslostpointercapture',
'mspointercancel',
'mspointerdown',
'mspointerenter',
'mspointerhover',
'mspointerleave',
'mspointermove',
'mspointerout',
'mspointerover',
'mspointerup',
'pointerout',
'mssitemodejumplistitemremoved',
'msthumbnailclick',
'stop',
'storagecommit'
];
var webglEventNames = ['webglcontextrestored', 'webglcontextlost', 'webglcontextcreationerror'];
var formEventNames = ['autocomplete', 'autocompleteerror'];
var detailEventNames = ['toggle'];
var frameEventNames = ['load'];
var frameSetEventNames = ['blur', 'error', 'focus', 'load', 'resize', 'scroll', 'messageerror'];
var marqueeEventNames = ['bounce', 'finish', 'start'];
var XMLHttpRequestEventNames = [
'loadstart', 'progress', 'abort', 'error', 'load', 'progress', 'timeout', 'loadend',
'readystatechange'
];
var IDBIndexEventNames = ['upgradeneeded', 'complete', 'abort', 'success', 'error', 'blocked', 'versionchange', 'close'];
var websocketEventNames = ['close', 'error', 'open', 'message'];
var workerEventNames = ['error', 'message'];
var eventNames = globalEventHandlersEventNames.concat(webglEventNames, formEventNames, detailEventNames, documentEventNames, windowEventNames, htmlElementEventNames, ieElementEventNames);
function filterProperties(target, onProperties, ignoreProperties) {
if (!ignoreProperties) {
return onProperties;
}
var tip = ignoreProperties.filter(function (ip) { return ip.target === target; });
if (!tip || tip.length === 0) {
return onProperties;
}
var targetIgnoreProperties = tip[0].ignoreProperties;
return onProperties.filter(function (op) { return targetIgnoreProperties.indexOf(op) === -1; });
}
function patchFilteredProperties(target, onProperties, ignoreProperties, prototype) {
var filteredProperties = filterProperties(target, onProperties, ignoreProperties);
patchOnProperties(target, filteredProperties, prototype);
}
function propertyDescriptorPatch(api, _global) {
if (isNode && !isMix) {
return;
}
var supportsWebSocket = typeof WebSocket !== 'undefined';
if (canPatchViaPropertyDescriptor()) {
var ignoreProperties = _global.__Zone_ignore_on_properties;
// for browsers that we can patch the descriptor: Chrome & Firefox
if (isBrowser) {
// in IE/Edge, onProp not exist in window object, but in WindowPrototype
// so we need to pass WindowPrototype to check onProp exist or not
patchFilteredProperties(window, eventNames.concat(['messageerror']), ignoreProperties, Object.getPrototypeOf(window));
patchFilteredProperties(Document.prototype, eventNames, ignoreProperties);
if (typeof window['SVGElement'] !== 'undefined') {
patchFilteredProperties(window['SVGElement'].prototype, eventNames, ignoreProperties);
}
patchFilteredProperties(Element.prototype, eventNames, ignoreProperties);
patchFilteredProperties(HTMLElement.prototype, eventNames, ignoreProperties);
patchFilteredProperties(HTMLMediaElement.prototype, mediaElementEventNames, ignoreProperties);
patchFilteredProperties(HTMLFrameSetElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties);
patchFilteredProperties(HTMLBodyElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties);
patchFilteredProperties(HTMLFrameElement.prototype, frameEventNames, ignoreProperties);
patchFilteredProperties(HTMLIFrameElement.prototype, frameEventNames, ignoreProperties);
var HTMLMarqueeElement_1 = window['HTMLMarqueeElement'];
if (HTMLMarqueeElement_1) {
patchFilteredProperties(HTMLMarqueeElement_1.prototype, marqueeEventNames, ignoreProperties);
}
var Worker_1 = window['Worker'];
if (Worker_1) {
patchFilteredProperties(Worker_1.prototype, workerEventNames, ignoreProperties);
}
}
patchFilteredProperties(XMLHttpRequest.prototype, XMLHttpRequestEventNames, ignoreProperties);
var XMLHttpRequestEventTarget = _global['XMLHttpRequestEventTarget'];
if (XMLHttpRequestEventTarget) {
patchFilteredProperties(XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype, XMLHttpRequestEventNames, ignoreProperties);
}
if (typeof IDBIndex !== 'undefined') {
patchFilteredProperties(IDBIndex.prototype, IDBIndexEventNames, ignoreProperties);
patchFilteredProperties(IDBRequest.prototype, IDBIndexEventNames, ignoreProperties);
patchFilteredProperties(IDBOpenDBRequest.prototype, IDBIndexEventNames, ignoreProperties);
patchFilteredProperties(IDBDatabase.prototype, IDBIndexEventNames, ignoreProperties);
patchFilteredProperties(IDBTransaction.prototype, IDBIndexEventNames, ignoreProperties);
patchFilteredProperties(IDBCursor.prototype, IDBIndexEventNames, ignoreProperties);
}
if (supportsWebSocket) {
patchFilteredProperties(WebSocket.prototype, websocketEventNames, ignoreProperties);
}
}
else {
// Safari, Android browsers (Jelly Bean)
patchViaCapturingAllTheEvents();
patchClass('XMLHttpRequest');
if (supportsWebSocket) {
apply(api, _global);
}
}
}
function canPatchViaPropertyDescriptor() {
if ((isBrowser || isMix) && !Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') &&
typeof Element !== 'undefined') {
// WebKit https://bugs.webkit.org/show_bug.cgi?id=134364
// IDL interface attributes are not configurable
var desc = Object.getOwnPropertyDescriptor(Element.prototype, 'onclick');
if (desc && !desc.configurable)
return false;
}
var xhrDesc = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'onreadystatechange');
// add enumerable and configurable here because in opera
// by default XMLHttpRequest.prototype.onreadystatechange is undefined
// without adding enumerable and configurable will cause onreadystatechange
// non-configurable
// and if XMLHttpRequest.prototype.onreadystatechange is undefined,
// we should set a real desc instead a fake one
if (xhrDesc) {
Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {
enumerable: true,
configurable: true,
get: function () {
return true;
}
});
var req = new XMLHttpRequest();
var result = !!req.onreadystatechange;
// restore original desc
Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', xhrDesc || {});
return result;
}
else {
var SYMBOL_FAKE_ONREADYSTATECHANGE_1 = zoneSymbol('fakeonreadystatechange');
Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {
enumerable: true,
configurable: true,
get: function () {
return this[SYMBOL_FAKE_ONREADYSTATECHANGE_1];
},
set: function (value) {
this[SYMBOL_FAKE_ONREADYSTATECHANGE_1] = value;
}
});
var req = new XMLHttpRequest();
var detectFunc = function () { };
req.onreadystatechange = detectFunc;
var result = req[SYMBOL_FAKE_ONREADYSTATECHANGE_1] === detectFunc;
req.onreadystatechange = null;
return result;
}
}
var unboundKey = zoneSymbol('unbound');
// Whenever any eventListener fires, we check the eventListener target and all parents
// for `onwhatever` properties and replace them with zone-bound functions
// - Chrome (for now)
function patchViaCapturingAllTheEvents() {
var _loop_1 = function (i) {
var property = eventNames[i];
var onproperty = 'on' + property;
self.addEventListener(property, function (event) {
var elt = event.target, bound, source;
if (elt) {
source = elt.constructor['name'] + '.' + onproperty;
}
else {
source = 'unknown.' + onproperty;
}
while (elt) {
if (elt[onproperty] && !elt[onproperty][unboundKey]) {
bound = Zone.current.wrap(elt[onproperty], source);
bound[unboundKey] = elt[onproperty];
elt[onproperty] = bound;
}
elt = elt.parentElement;
}
}, true);
};
for (var i = 0; i < eventNames.length; i++) {
_loop_1(i);
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function eventTargetPatch(_global, api) {
var WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';
var NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex,WebSocket'
.split(',');
var EVENT_TARGET = 'EventTarget';
var apis = [];
var isWtf = _global['wtf'];
var WTF_ISSUE_555_ARRAY = WTF_ISSUE_555.split(',');
if (isWtf) {
// Workaround for: https://github.com/google/tracing-framework/issues/555
apis = WTF_ISSUE_555_ARRAY.map(function (v) { return 'HTML' + v + 'Element'; }).concat(NO_EVENT_TARGET);
}
else if (_global[EVENT_TARGET]) {
apis.push(EVENT_TARGET);
}
else {
// Note: EventTarget is not available in all browsers,
// if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget
apis = NO_EVENT_TARGET;
}
var isDisableIECheck = _global['__Zone_disable_IE_check'] || false;
var isEnableCrossContextCheck = _global['__Zone_enable_cross_context_check'] || false;
var ieOrEdge = isIEOrEdge();
var ADD_EVENT_LISTENER_SOURCE = '.addEventListener:';
var FUNCTION_WRAPPER = '[object FunctionWrapper]';
var BROWSER_TOOLS = 'function __BROWSERTOOLS_CONSOLE_SAFEFUNC() { [native code] }';
// predefine all __zone_symbol__ + eventName + true/false string
for (var i = 0; i < eventNames.length; i++) {
var eventName = eventNames[i];
var falseEventName = eventName + FALSE_STR;
var trueEventName = eventName + TRUE_STR;
var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
zoneSymbolEventNames$1[eventName] = {};
zoneSymbolEventNames$1[eventName][FALSE_STR] = symbol;
zoneSymbolEventNames$1[eventName][TRUE_STR] = symbolCapture;
}
// predefine all task.source string
for (var i = 0; i < WTF_ISSUE_555.length; i++) {
var target = WTF_ISSUE_555_ARRAY[i];
var targets = globalSources[target] = {};
for (var j = 0; j < eventNames.length; j++) {
var eventName = eventNames[j];
targets[eventName] = target + ADD_EVENT_LISTENER_SOURCE + eventName;
}
}
var checkIEAndCrossContext = function (nativeDelegate, delegate, target, args) {
if (!isDisableIECheck && ieOrEdge) {
if (isEnableCrossContextCheck) {
try {
var testString = delegate.toString();
if ((testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS)) {
nativeDelegate.apply(target, args);
return false;
}
}
catch (error) {
nativeDelegate.apply(target, args);
return false;
}
}
else {
var testString = delegate.toString();
if ((testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS)) {
nativeDelegate.apply(target, args);
return false;
}
}
}
else if (isEnableCrossContextCheck) {
try {
delegate.toString();
}
catch (error) {
nativeDelegate.apply(target, args);
return false;
}
}
return true;
};
var apiTypes = [];
for (var i = 0; i < apis.length; i++) {
var type = _global[apis[i]];
apiTypes.push(type && type.prototype);
}
patchEventTarget(_global, apiTypes, { validateHandler: checkIEAndCrossContext });
api.patchEventTarget = patchEventTarget;
return true;
}
function patchEvent(global, api) {
patchEventPrototype(global, api);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function registerElementPatch(_global) {
if ((!isBrowser && !isMix) || !('registerElement' in _global.document)) {
return;
}
var _registerElement = document.registerElement;
var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
document.registerElement = function (name, opts) {
if (opts && opts.prototype) {
callbacks.forEach(function (callback) {
var source = 'Document.registerElement::' + callback;
if (opts.prototype.hasOwnProperty(callback)) {
var descriptor = Object.getOwnPropertyDescriptor(opts.prototype, callback);
if (descriptor && descriptor.value) {
descriptor.value = Zone.current.wrap(descriptor.value, source);
_redefineProperty(opts.prototype, callback, descriptor);
}
else {
opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source);
}
}
else if (opts.prototype[callback]) {
opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source);
}
});
}
return _registerElement.apply(document, [name, opts]);
};
attachOriginToPatched(document.registerElement, _registerElement);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @fileoverview
* @suppress {missingRequire}
*/
Zone.__load_patch('util', function (global, Zone, api) {
api.patchOnProperties = patchOnProperties;
api.patchMethod = patchMethod;
});
Zone.__load_patch('timers', function (global, Zone, api) {
var set = 'set';
var clear = 'clear';
patchTimer(global, set, clear, 'Timeout');
patchTimer(global, set, clear, 'Interval');
patchTimer(global, set, clear, 'Immediate');
});
Zone.__load_patch('requestAnimationFrame', function (global, Zone, api) {
patchTimer(global, 'request', 'cancel', 'AnimationFrame');
patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
});
Zone.__load_patch('blocking', function (global, Zone, api) {
var blockingMethods = ['alert', 'prompt', 'confirm'];
for (var i = 0; i < blockingMethods.length; i++) {
var name_1 = blockingMethods[i];
patchMethod(global, name_1, function (delegate, symbol, name) {
return function (s, args) {
return Zone.current.run(delegate, global, args, name);
};
});
}
});
Zone.__load_patch('EventTarget', function (global, Zone, api) {
patchEvent(global, api);
eventTargetPatch(global, api);
// patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
var XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
api.patchEventTarget(global, [XMLHttpRequestEventTarget.prototype]);
}
patchClass('MutationObserver');
patchClass('WebKitMutationObserver');
patchClass('IntersectionObserver');
patchClass('FileReader');
});
Zone.__load_patch('on_property', function (global, Zone, api) {
propertyDescriptorPatch(api, global);
propertyPatch();
registerElementPatch(global);
});
Zone.__load_patch('canvas', function (global, Zone, api) {
var HTMLCanvasElement = global['HTMLCanvasElement'];
if (typeof HTMLCanvasElement !== 'undefined' && HTMLCanvasElement.prototype &&
HTMLCanvasElement.prototype.toBlob) {
patchMacroTask(HTMLCanvasElement.prototype, 'toBlob', function (self, args) {
return { name: 'HTMLCanvasElement.toBlob', target: self, callbackIndex: 0, args: args };
});
}
});
Zone.__load_patch('XHR', function (global, Zone, api) {
// Treat XMLHTTPRequest as a macrotask.
patchXHR(global);
var XHR_TASK = zoneSymbol('xhrTask');
var XHR_SYNC = zoneSymbol('xhrSync');
var XHR_LISTENER = zoneSymbol('xhrListener');
var XHR_SCHEDULED = zoneSymbol('xhrScheduled');
var XHR_URL = zoneSymbol('xhrURL');
function patchXHR(window) {
function findPendingTask(target) {
var pendingTask = target[XHR_TASK];
return pendingTask;
}
var SYMBOL_ADDEVENTLISTENER = zoneSymbol('addEventListener');
var SYMBOL_REMOVEEVENTLISTENER = zoneSymbol('removeEventListener');
var oriAddListener = XMLHttpRequest.prototype[SYMBOL_ADDEVENTLISTENER];
var oriRemoveListener = XMLHttpRequest.prototype[SYMBOL_REMOVEEVENTLISTENER];
if (!oriAddListener) {
var XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget'];
if (XMLHttpRequestEventTarget) {
oriAddListener = XMLHttpRequestEventTarget.prototype[SYMBOL_ADDEVENTLISTENER];
oriRemoveListener = XMLHttpRequestEventTarget.prototype[SYMBOL_REMOVEEVENTLISTENER];
}
}
var READY_STATE_CHANGE = 'readystatechange';
var SCHEDULED = 'scheduled';
function scheduleTask(task) {
XMLHttpRequest[XHR_SCHEDULED] = false;
var data = task.data;
var target = data.target;
// remove existing event listener
var listener = target[XHR_LISTENER];
if (!oriAddListener) {
oriAddListener = target[SYMBOL_ADDEVENTLISTENER];
oriRemoveListener = target[SYMBOL_REMOVEEVENTLISTENER];
}
if (listener) {
oriRemoveListener.apply(target, [READY_STATE_CHANGE, listener]);
}
var newListener = target[XHR_LISTENER] = function () {
if (target.readyState === target.DONE) {
// sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
// readyState=4 multiple times, so we need to check task state here
if (!data.aborted && XMLHttpRequest[XHR_SCHEDULED] && task.state === SCHEDULED) {
task.invoke();
}
}
};
oriAddListener.apply(target, [READY_STATE_CHANGE, newListener]);
var storedTask = target[XHR_TASK];
if (!storedTask) {
target[XHR_TASK] = task;
}
sendNative.apply(target, data.args);
XMLHttpRequest[XHR_SCHEDULED] = true;
return task;
}
function placeholderCallback() { }
function clearTask(task) {
var data = task.data;
// Note - ideally, we would call data.target.removeEventListener here, but it's too late
// to prevent it from firing. So instead, we store info for the event listener.
data.aborted = true;
return abortNative.apply(data.target, data.args);
}
var openNative = patchMethod(window.XMLHttpRequest.prototype, 'open', function () { return function (self, args) {
self[XHR_SYNC] = args[2] == false;
self[XHR_URL] = args[1];
return openNative.apply(self, args);
}; });
var XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
var sendNative = patchMethod(window.XMLHttpRequest.prototype, 'send', function () { return function (self, args) {
var zone = Zone.current;
if (self[XHR_SYNC]) {
// if the XHR is sync there is no task to schedule, just execute the code.
return sendNative.apply(self, args);
}
else {
var options = {
target: self,
url: self[XHR_URL],
isPeriodic: false,
delay: null,
args: args,
aborted: false
};
return zone.scheduleMacroTask(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
}
}; });
var STRING_TYPE = 'string';
var abortNative = patchMethod(window.XMLHttpRequest.prototype, 'abort', function (delegate) { return function (self, args) {
var task = findPendingTask(self);
if (task && typeof task.type == STRING_TYPE) {
// If the XHR has already completed, do nothing.
// If the XHR has already been aborted, do nothing.
// Fix #569, call abort multiple times before done will cause
// macroTask task count be negative number
if (task.cancelFn == null || (task.data && task.data.aborted)) {
return;
}
task.zone.cancelTask(task);
}
// Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
// task
// to cancel. Do nothing.
}; });
}
});
Zone.__load_patch('geolocation', function (global, Zone, api) {
/// GEO_LOCATION
if (global['navigator'] && global['navigator'].geolocation) {
patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
}
});
Zone.__load_patch('PromiseRejectionEvent', function (global, Zone, api) {
// handle unhandled promise rejection
function findPromiseRejectionHandler(evtName) {
return function (e) {
var eventTasks = findEventTasks(global, evtName);
eventTasks.forEach(function (eventTask) {
// windows has added unhandledrejection event listener
// trigger the event listener
var PromiseRejectionEvent = global['PromiseRejectionEvent'];
if (PromiseRejectionEvent) {
var evt = new PromiseRejectionEvent(evtName, { promise: e.promise, reason: e.rejection });
eventTask.invoke(evt);
}
});
};
}
if (global['PromiseRejectionEvent']) {
Zone[zoneSymbol('unhandledPromiseRejectionHandler')] =
findPromiseRejectionHandler('unhandledrejection');
Zone[zoneSymbol('rejectionHandledHandler')] =
findPromiseRejectionHandler('rejectionhandled');
}
});
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
})));
|
src/components/compact/CompactColor.js | casesandberg/react-color | import React from 'react'
import reactCSS from 'reactcss'
import * as colorUtils from '../../helpers/color'
import { Swatch } from '../common'
export const CompactColor = ({ color, onClick = () => {}, onSwatchHover, active }) => {
const styles = reactCSS({
'default': {
color: {
background: color,
width: '15px',
height: '15px',
float: 'left',
marginRight: '5px',
marginBottom: '5px',
position: 'relative',
cursor: 'pointer',
},
dot: {
absolute: '5px 5px 5px 5px',
background: colorUtils.getContrastingColor(color),
borderRadius: '50%',
opacity: '0',
},
},
'active': {
dot: {
opacity: '1',
},
},
'color-#FFFFFF': {
color: {
boxShadow: 'inset 0 0 0 1px #ddd',
},
dot: {
background: '#000',
},
},
'transparent': {
dot: {
background: '#000',
},
},
}, { active, 'color-#FFFFFF': color === '#FFFFFF', 'transparent': color === 'transparent' })
return (
<Swatch
style={ styles.color }
color={ color }
onClick={ onClick }
onHover={ onSwatchHover }
focusStyle={{ boxShadow: `0 0 4px ${ color }` }}
>
<div style={ styles.dot } />
</Swatch>
)
}
export default CompactColor
|
src/packages/@ncigdc/modern_components/CaseSymbol/CaseSymbol.relay.js | NCI-GDC/portal-ui | // @flow
import React from 'react';
import { graphql } from 'react-relay';
import { makeFilter } from '@ncigdc/utils/filters';
import { compose, withPropsOnChange, branch, renderComponent } from 'recompose';
import { BaseQuery } from '@ncigdc/modern_components/Query';
export default (Component: ReactClass<*>) =>
compose(
branch(
({ caseId }) => !caseId,
renderComponent(() => (
<div>
<pre>caseId</pre> must be provided
</div>
)),
),
withPropsOnChange(['caseId'], ({ caseId }) => {
return {
variables: {
filters: makeFilter([
{
field: 'cases.case_id',
value: [caseId],
},
]),
},
};
}),
)((props: Object) => {
return (
<BaseQuery
parentProps={props}
name="CaseSymbol"
variables={props.variables}
Component={Component}
query={graphql`
query CaseSymbol_relayQuery($filters: FiltersArgument) {
viewer {
repository {
cases {
hits(filters: $filters, first: 1) {
edges {
node {
submitter_id
project {
project_id
}
}
}
}
}
}
}
}
`}
/>
);
});
|
src/components/chrome/original-wordmark/ChromeOriginalWordmark.js | fpoumian/react-devicon | import React from 'react'
import PropTypes from 'prop-types'
import SVGDeviconInline from '../../_base/SVGDeviconInline'
import iconSVG from './ChromeOriginalWordmark.svg'
/** ChromeOriginalWordmark */
function ChromeOriginalWordmark({ width, height, className }) {
return (
<SVGDeviconInline
className={'ChromeOriginalWordmark' + ' ' + className}
iconSVG={iconSVG}
width={width}
height={height}
/>
)
}
ChromeOriginalWordmark.propTypes = {
className: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}
export default ChromeOriginalWordmark
|
ajax/libs/handsontable/0.11.0-beta1/jquery.handsontable.full.js | aashish24/cdnjs | /**
* Handsontable 0.11.0-beta1
* Handsontable is a simple jQuery plugin for editable tables with basic copy-paste compatibility with Excel and Google Docs
*
* Copyright 2012-2014 Marcin Warpechowski
* Licensed under the MIT license.
* http://handsontable.com/
*
* Date: Thu Jul 10 2014 13:20:50 GMT+0200 (CEST)
*/
/*jslint white: true, browser: true, plusplus: true, indent: 4, maxerr: 50 */
var Handsontable = { //class namespace
plugins: {}, //plugin namespace
helper: {} //helper namespace
};
(function ($, window, Handsontable) {
"use strict";
//http://stackoverflow.com/questions/3629183/why-doesnt-indexof-work-on-an-array-ie8
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
/**
* Array.filter() shim by Trevor Menagh (https://github.com/trevmex) with some modifications
*/
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun, thisp) {
"use strict";
if (typeof this === "undefined" || this === null) {
throw new TypeError();
}
if (typeof fun !== "function") {
throw new TypeError();
}
thisp = thisp || this;
if (isNodeList(thisp)) {
thisp = convertNodeListToArray(thisp);
}
var len = thisp.length,
res = [],
i,
val;
for (i = 0; i < len; i += 1) {
if (thisp.hasOwnProperty(i)) {
val = thisp[i]; // in case fun mutates this
if (fun.call(thisp, val, i, thisp)) {
res.push(val);
}
}
}
return res;
function isNodeList(object) {
return /NodeList/i.test(object.item);
}
function convertNodeListToArray(nodeList) {
var array = [];
for (var i = 0, len = nodeList.length; i < len; i++){
array[i] = nodeList[i]
}
return array;
}
};
}
/*
* Copyright 2012 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
if (typeof WeakMap === 'undefined') {
(function() {
var defineProperty = Object.defineProperty;
try {
var properDefineProperty = true;
defineProperty(function(){}, 'foo', {});
} catch (e) {
properDefineProperty = false;
}
/*
IE8 does not support Date.now() but IE8 compatibility mode in IE9 and IE10 does.
M$ deserves a high five for this one :)
*/
var counter = +(new Date) % 1e9;
var WeakMap = function() {
this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__');
if(!properDefineProperty){
this._wmCache = [];
}
};
if(properDefineProperty){
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});
},
get: function(key) {
var entry;
return (entry = key[this.name]) && entry[0] === key ?
entry[1] : undefined;
},
'delete': function(key) {
this.set(key, undefined);
}
};
} else {
WeakMap.prototype = {
set: function(key, value) {
if(typeof key == 'undefined' || typeof value == 'undefined') return;
for(var i = 0, len = this._wmCache.length; i < len; i++){
if(this._wmCache[i].key == key){
this._wmCache[i].value = value;
return;
}
}
this._wmCache.push({key: key, value: value});
},
get: function(key) {
if(typeof key == 'undefined') return;
for(var i = 0, len = this._wmCache.length; i < len; i++){
if(this._wmCache[i].key == key){
return this._wmCache[i].value;
}
}
return;
},
'delete': function(key) {
if(typeof key == 'undefined') return;
for(var i = 0, len = this._wmCache.length; i < len; i++){
if(this._wmCache[i].key == key){
Array.prototype.slice.call(this._wmCache, i, 1);
}
}
}
};
}
window.WeakMap = WeakMap;
})();
}
Handsontable.activeGuid = null;
/**
* Handsontable constructor
* @param rootElement The jQuery element in which Handsontable DOM will be inserted
* @param userSettings
* @constructor
*/
Handsontable.Core = function (rootElement, userSettings) {
var priv
, datamap
, grid
, selection
, editorManager
, autofill
, instance = this
, GridSettings = function () {};
Handsontable.helper.extend(GridSettings.prototype, DefaultSettings.prototype); //create grid settings as a copy of default settings
Handsontable.helper.extend(GridSettings.prototype, userSettings); //overwrite defaults with user settings
Handsontable.helper.extend(GridSettings.prototype, expandType(userSettings));
this.rootElement = rootElement;
this.container = document.createElement('DIV');
this.container.className = 'htContainer';
rootElement.prepend(this.container);
this.container = $(this.container);
var $document = $(document.documentElement);
var $body = $(document.body);
this.guid = 'ht_' + Handsontable.helper.randomString(); //this is the namespace for global events
if (!this.rootElement[0].id) {
this.rootElement[0].id = this.guid; //if root element does not have an id, assign a random id
}
priv = {
cellSettings: [],
columnSettings: [],
columnsSettingConflicts: ['data', 'width'],
settings: new GridSettings(), // current settings instance
selRange: null, //exposed by public method `getSelectedRange`
isPopulated: null,
scrollable: null,
firstRun: true
};
grid = {
/**
* Inserts or removes rows and columns
* @param {String} action Possible values: "insert_row", "insert_col", "remove_row", "remove_col"
* @param {Number} index
* @param {Number} amount
* @param {String} [source] Optional. Source of hook runner.
* @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
*/
alter: function (action, index, amount, source, keepEmptyRows) {
var delta;
amount = amount || 1;
switch (action) {
case "insert_row":
delta = datamap.createRow(index, amount);
if (delta) {
if (selection.isSelected() && priv.selRange.from.row >= index) {
priv.selRange.from.row = priv.selRange.from.row + delta;
selection.transformEnd(delta, 0); //will call render() internally
}
else {
selection.refreshBorders(); //it will call render and prepare methods
}
}
break;
case "insert_col":
delta = datamap.createCol(index, amount);
if (delta) {
if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){
var spliceArray = [index, 0];
spliceArray.length += delta; //inserts empty (undefined) elements at the end of an array
Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArray); //inserts empty (undefined) elements into the colHeader array
}
if (selection.isSelected() && priv.selRange.from.col >= index) {
priv.selRange.from.col = priv.selRange.from.col + delta;
selection.transformEnd(0, delta); //will call render() internally
}
else {
selection.refreshBorders(); //it will call render and prepare methods
}
}
break;
case "remove_row":
datamap.removeRow(index, amount);
priv.cellSettings.splice(index, amount);
grid.adjustRowsAndCols();
selection.refreshBorders(); //it will call render and prepare methods
break;
case "remove_col":
datamap.removeCol(index, amount);
for(var row = 0, len = datamap.getAll().length; row < len; row++){
if(row in priv.cellSettings){ //if row hasn't been rendered it wouldn't have cellSettings
priv.cellSettings[row].splice(index, amount);
}
}
if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){
if(typeof index == 'undefined'){
index = -1;
}
instance.getSettings().colHeaders.splice(index, amount);
}
priv.columnSettings.splice(index, amount);
grid.adjustRowsAndCols();
selection.refreshBorders(); //it will call render and prepare methods
break;
default:
throw new Error('There is no such action "' + action + '"');
break;
}
if (!keepEmptyRows) {
grid.adjustRowsAndCols(); //makes sure that we did not add rows that will be removed in next refresh
}
},
/**
* Makes sure there are empty rows at the bottom of the table
*/
adjustRowsAndCols: function () {
var r, rlen, emptyRows, emptyCols;
//should I add empty rows to data source to meet minRows?
rlen = instance.countRows();
if (rlen < priv.settings.minRows) {
for (r = 0; r < priv.settings.minRows - rlen; r++) {
datamap.createRow(instance.countRows(), 1, true);
}
}
emptyRows = instance.countEmptyRows(true);
//should I add empty rows to meet minSpareRows?
if (emptyRows < priv.settings.minSpareRows) {
for (; emptyRows < priv.settings.minSpareRows && instance.countRows() < priv.settings.maxRows; emptyRows++) {
datamap.createRow(instance.countRows(), 1, true);
}
}
//count currently empty cols
emptyCols = instance.countEmptyCols(true);
//should I add empty cols to meet minCols?
if (!priv.settings.columns && instance.countCols() < priv.settings.minCols) {
for (; instance.countCols() < priv.settings.minCols; emptyCols++) {
datamap.createCol(instance.countCols(), 1, true);
}
}
//should I add empty cols to meet minSpareCols?
if (!priv.settings.columns && instance.dataType === 'array' && emptyCols < priv.settings.minSpareCols) {
for (; emptyCols < priv.settings.minSpareCols && instance.countCols() < priv.settings.maxCols; emptyCols++) {
datamap.createCol(instance.countCols(), 1, true);
}
}
// if (priv.settings.enterBeginsEditing) {
// for (; (((priv.settings.minRows || priv.settings.minSpareRows) && instance.countRows() > priv.settings.minRows) && (priv.settings.minSpareRows && emptyRows > priv.settings.minSpareRows)); emptyRows--) {
// datamap.removeRow();
// }
// }
// if (priv.settings.enterBeginsEditing && !priv.settings.columns) {
// for (; (((priv.settings.minCols || priv.settings.minSpareCols) && instance.countCols() > priv.settings.minCols) && (priv.settings.minSpareCols && emptyCols > priv.settings.minSpareCols)); emptyCols--) {
// datamap.removeCol();
// }
// }
var rowCount = instance.countRows();
var colCount = instance.countCols();
if (rowCount === 0 || colCount === 0) {
selection.deselect();
}
if (selection.isSelected()) {
var selectionChanged;
var fromRow = priv.selRange.from.row;
var fromCol = priv.selRange.from.col;
var toRow = priv.selRange.to.row;
var toCol = priv.selRange.to.col;
//if selection is outside, move selection to last row
if (fromRow > rowCount - 1) {
fromRow = rowCount - 1;
selectionChanged = true;
if (toRow > fromRow) {
toRow = fromRow;
}
} else if (toRow > rowCount - 1) {
toRow = rowCount - 1;
selectionChanged = true;
if (fromRow > toRow) {
fromRow = toRow;
}
}
//if selection is outside, move selection to last row
if (fromCol > colCount - 1) {
fromCol = colCount - 1;
selectionChanged = true;
if (toCol > fromCol) {
toCol = fromCol;
}
} else if (toCol > colCount - 1) {
toCol = colCount - 1;
selectionChanged = true;
if (fromCol > toCol) {
fromCol = toCol;
}
}
if (selectionChanged) {
instance.selectCell(fromRow, fromCol, toRow, toCol);
}
}
},
/**
* Populate cells at position with 2d array
* @param {Object} start Start selection position
* @param {Array} input 2d array
* @param {Object} [end] End selection position (only for drag-down mode)
* @param {String} [source="populateFromArray"]
* @param {String} [method="overwrite"]
* @return {Object|undefined} ending td in pasted area (only if any cell was changed)
*/
populateFromArray: function (start, input, end, source, method) {
var r, rlen, c, clen, setData = [], current = {};
rlen = input.length;
if (rlen === 0) {
return false;
}
var repeatCol
, repeatRow
, cmax
, rmax;
// insert data with specified pasteMode method
switch (method) {
case 'shift_down' :
repeatCol = end ? end.col - start.col + 1 : 0;
repeatRow = end ? end.row - start.row + 1 : 0;
input = Handsontable.helper.translateRowsToColumns(input);
for (c = 0, clen = input.length, cmax = Math.max(clen, repeatCol); c < cmax; c++) {
if (c < clen) {
for (r = 0, rlen = input[c].length; r < repeatRow - rlen; r++) {
input[c].push(input[c][r % rlen]);
}
input[c].unshift(start.col + c, start.row, 0);
instance.spliceCol.apply(instance, input[c]);
}
else {
input[c % clen][0] = start.col + c;
instance.spliceCol.apply(instance, input[c % clen]);
}
}
break;
case 'shift_right' :
repeatCol = end ? end.col - start.col + 1 : 0;
repeatRow = end ? end.row - start.row + 1 : 0;
for (r = 0, rlen = input.length, rmax = Math.max(rlen, repeatRow); r < rmax; r++) {
if (r < rlen) {
for (c = 0, clen = input[r].length; c < repeatCol - clen; c++) {
input[r].push(input[r][c % clen]);
}
input[r].unshift(start.row + r, start.col, 0);
instance.spliceRow.apply(instance, input[r]);
}
else {
input[r % rlen][0] = start.row + r;
instance.spliceRow.apply(instance, input[r % rlen]);
}
}
break;
case 'overwrite' :
default:
// overwrite and other not specified options
current.row = start.row;
current.col = start.col;
for (r = 0; r < rlen; r++) {
if ((end && current.row > end.row) || (!priv.settings.minSpareRows && current.row > instance.countRows() - 1) || (current.row >= priv.settings.maxRows)) {
break;
}
current.col = start.col;
clen = input[r] ? input[r].length : 0;
for (c = 0; c < clen; c++) {
if ((end && current.col > end.col) || (!priv.settings.minSpareCols && current.col > instance.countCols() - 1) || (current.col >= priv.settings.maxCols)) {
break;
}
if (!instance.getCellMeta(current.row, current.col).readOnly) {
setData.push([current.row, current.col, input[r][c]]);
}
current.col++;
if (end && c === clen - 1) {
c = -1;
}
}
current.row++;
if (end && r === rlen - 1) {
r = -1;
}
}
instance.setDataAtCell(setData, null, null, source || 'populateFromArray');
break;
}
}
};
this.selection = selection = { //this public assignment is only temporary
inProgress: false,
/**
* Sets inProgress to true. This enables onSelectionEnd and onSelectionEndByProp to function as desired
*/
begin: function () {
instance.selection.inProgress = true;
},
/**
* Sets inProgress to false. Triggers onSelectionEnd and onSelectionEndByProp
*/
finish: function () {
var sel = instance.getSelected();
Handsontable.hooks.run(instance, "afterSelectionEnd", sel[0], sel[1], sel[2], sel[3]);
Handsontable.hooks.run(instance, "afterSelectionEndByProp", sel[0], instance.colToProp(sel[1]), sel[2], instance.colToProp(sel[3]));
instance.selection.inProgress = false;
},
isInProgress: function () {
return instance.selection.inProgress;
},
/**
* Starts selection range on given td object
* @param {WalkontableCellCoords} coords
*/
setRangeStart: function (coords) {
Handsontable.hooks.run(instance, "beforeSetRangeStart", coords);
priv.selRange = new WalkontableCellRange(coords, coords, coords);
selection.setRangeEnd(coords);
},
/**
* Ends selection range on given td object
* @param {WalkontableCellCoords} coords
* @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to range end
*/
setRangeEnd: function (coords, scrollToCell) {
//trigger handlers
Handsontable.hooks.run(instance, "beforeSetRangeEnd", coords);
instance.selection.begin();
priv.selRange.to = coords;
if (!priv.settings.multiSelect) {
priv.selRange.from = coords;
}
//set up current selection
instance.view.wt.selections.current.clear();
instance.view.wt.selections.current.add(priv.selRange.highlight);
//set up area selection
instance.view.wt.selections.area.clear();
if (selection.isMultiple()) {
instance.view.wt.selections.area.add(priv.selRange.from);
instance.view.wt.selections.area.add(priv.selRange.to);
}
//set up highlight
if (priv.settings.currentRowClassName || priv.settings.currentColClassName) {
instance.view.wt.selections.highlight.clear();
instance.view.wt.selections.highlight.add(priv.selRange.from);
instance.view.wt.selections.highlight.add(priv.selRange.to);
}
//trigger handlers
Handsontable.hooks.run(instance, "afterSelection", priv.selRange.from.row, priv.selRange.from.col, priv.selRange.to.row, priv.selRange.to.col);
Handsontable.hooks.run(instance, "afterSelectionByProp", priv.selRange.from.row, datamap.colToProp(priv.selRange.from.col), priv.selRange.to.row, datamap.colToProp(priv.selRange.to.col));
if (scrollToCell !== false && instance.view.mainViewIsActive()) {
instance.view.scrollViewport(coords);
}
selection.refreshBorders();
},
/**
* Destroys editor, redraws borders around cells, prepares editor
* @param {Boolean} revertOriginal
* @param {Boolean} keepEditor
*/
refreshBorders: function (revertOriginal, keepEditor) {
if (!keepEditor) {
editorManager.destroyEditor(revertOriginal);
}
instance.view.render();
if (selection.isSelected() && !keepEditor) {
editorManager.prepareEditor();
}
},
/**
* Returns information if we have a multiselection
* @return {Boolean}
*/
isMultiple: function () {
return !(priv.selRange.to.col === priv.selRange.from.col && priv.selRange.to.row === priv.selRange.from.row);
},
/**
* Selects cell relative to current cell (if possible)
*/
transformStart: function (rowDelta, colDelta, force) {
var delta = new WalkontableCellCoords(rowDelta, colDelta);
instance.runHooks('modifyTransformStart', delta);
if (priv.selRange.highlight.row + rowDelta > instance.countRows() - 1) {
if (force && priv.settings.minSpareRows > 0) {
instance.alter("insert_row", instance.countRows());
}
else if (priv.settings.autoWrapCol) {
delta.row = 1 - instance.countRows();
delta.col = priv.selRange.highlight.col + delta.col == instance.countCols() - 1 ? 1 - instance.countCols() : 1;
}
}
else if (priv.settings.autoWrapCol && priv.selRange.highlight.row + delta.row < 0 && priv.selRange.highlight.col + delta.col >= 0) {
delta.row = instance.countRows() - 1;
delta.col = priv.selRange.highlight.col + delta.col == 0 ? instance.countCols() - 1 : -1;
}
if (priv.selRange.highlight.col + delta.col > instance.countCols() - 1) {
if (force && priv.settings.minSpareCols > 0) {
instance.alter("insert_col", instance.countCols());
}
else if (priv.settings.autoWrapRow) {
delta.row = priv.selRange.highlight.row + delta.row == instance.countRows() - 1 ? 1 - instance.countRows() : 1;
delta.col = 1 - instance.countCols();
}
}
else if (priv.settings.autoWrapRow && priv.selRange.highlight.col + delta.col < 0 && priv.selRange.highlight.row + delta.row >= 0) {
delta.row = priv.selRange.highlight.row + delta.row == 0 ? instance.countRows() - 1 : -1;
delta.col = instance.countCols() - 1;
}
var totalRows = instance.countRows();
var totalCols = instance.countCols();
var coords = new WalkontableCellCoords(priv.selRange.highlight.row + delta.row, priv.selRange.highlight.col + delta.col);
if (coords.row < 0) {
coords.row = 0;
}
else if (coords.row > 0 && coords.row >= totalRows) {
coords.row = totalRows - 1;
}
if (coords.col < 0) {
coords.col = 0;
}
else if (coords.col > 0 && coords.col >= totalCols) {
coords.col = totalCols - 1;
}
selection.setRangeStart(coords);
},
/**
* Sets selection end cell relative to current selection end cell (if possible)
*/
transformEnd: function (rowDelta, colDelta) {
var delta = new WalkontableCellCoords(rowDelta, colDelta);
instance.runHooks('modifyTransformEnd', delta);
var totalRows = instance.countRows();
var totalCols = instance.countCols();
var coords = new WalkontableCellCoords(priv.selRange.to.row + delta.row, priv.selRange.to.col + delta.col);
if (coords.row < 0) {
coords.row = 0;
}
else if (coords.row > 0 && coords.row >= totalRows) {
coords.row = totalRows - 1;
}
if (coords.col < 0) {
coords.col = 0;
}
else if (coords.col > 0 && coords.col >= totalCols) {
coords.col = totalCols - 1;
}
selection.setRangeEnd(coords);
},
/**
* Returns true if currently there is a selection on screen, false otherwise
* @return {Boolean}
*/
isSelected: function () {
return (priv.selRange !== null);
},
/**
* Returns true if coords is within current selection coords
* @param {WalkontableCellCoords} coords
* @return {Boolean}
*/
inInSelection: function (coords) {
if (!selection.isSelected()) {
return false;
}
return priv.selRange.includes(coords);
},
/**
* Deselects all selected cells
*/
deselect: function () {
if (!selection.isSelected()) {
return;
}
instance.selection.inProgress = false; //needed by HT inception
priv.selRange = null;
instance.view.wt.selections.current.clear();
instance.view.wt.selections.area.clear();
editorManager.destroyEditor();
selection.refreshBorders();
Handsontable.hooks.run(instance, 'afterDeselect');
},
/**
* Select all cells
*/
selectAll: function () {
if (!priv.settings.multiSelect) {
return;
}
selection.setRangeStart(new WalkontableCellCoords(0, 0));
selection.setRangeEnd(new WalkontableCellCoords(instance.countRows() - 1, instance.countCols() - 1), false);
},
/**
* Deletes data from selected cells
*/
empty: function () {
if (!selection.isSelected()) {
return;
}
var topLeft = priv.selRange.getTopLeftCorner();
var bottomRight = priv.selRange.getBottomRightCorner();
var r, c, changes = [];
for (r = topLeft.row; r <= bottomRight.row; r++) {
for (c = topLeft.col; c <= bottomRight.col; c++) {
if (!instance.getCellMeta(r, c).readOnly) {
changes.push([r, c, '']);
}
}
}
instance.setDataAtCell(changes);
}
};
this.autofill = autofill = { //this public assignment is only temporary
handle: null,
/**
* Create fill handle and fill border objects
*/
init: function () {
if (!autofill.handle) {
autofill.handle = {};
}
else {
autofill.handle.disabled = false;
}
},
/**
* Hide fill handle and fill border permanently
*/
disable: function () {
autofill.handle.disabled = true;
},
/**
* Selects cells down to the last row in the left column, then fills down to that cell
*/
selectAdjacent: function () {
var select, data, r, maxR, c;
if (selection.isMultiple()) {
select = instance.view.wt.selections.area.getCorners();
}
else {
select = instance.view.wt.selections.current.getCorners();
}
data = datamap.getAll();
rows : for (r = select[2] + 1; r < instance.countRows(); r++) {
for (c = select[1]; c <= select[3]; c++) {
if (data[r][c]) {
break rows;
}
}
if (!!data[r][select[1] - 1] || !!data[r][select[3] + 1]) {
maxR = r;
}
}
if (maxR) {
instance.view.wt.selections.fill.clear();
instance.view.wt.selections.fill.add([select[0], select[1]]);
instance.view.wt.selections.fill.add([maxR, select[3]]);
autofill.apply();
}
},
/**
* Apply fill values to the area in fill border, omitting the selection border
*/
apply: function () {
var drag, select, start, end, _data;
autofill.handle.isDragged = 0;
drag = instance.view.wt.selections.fill.getCorners();
if (!drag) {
return;
}
instance.view.wt.selections.fill.clear();
if (selection.isMultiple()) {
select = instance.view.wt.selections.area.getCorners();
}
else {
select = instance.view.wt.selections.current.getCorners();
}
if (drag[0] === select[0] && drag[1] < select[1]) {
start = new WalkontableCellCoords(
drag[0],
drag[1]
);
end = new WalkontableCellCoords(
drag[2],
select[1] - 1
);
}
else if (drag[0] === select[0] && drag[3] > select[3]) {
start = new WalkontableCellCoords(
drag[0],
select[3] + 1
);
end = new WalkontableCellCoords(
drag[2],
drag[3]
);
}
else if (drag[0] < select[0] && drag[1] === select[1]) {
start = new WalkontableCellCoords(
drag[0],
drag[1]
);
end = new WalkontableCellCoords(
select[0] - 1,
drag[3]
);
}
else if (drag[2] > select[2] && drag[1] === select[1]) {
start = new WalkontableCellCoords(
select[2] + 1,
drag[1]
);
end = new WalkontableCellCoords(
drag[2],
drag[3]
);
}
if (start) {
_data = SheetClip.parse(datamap.getText(priv.selRange.from, priv.selRange.to));
Handsontable.hooks.run(instance, 'beforeAutofill', start, end, _data);
grid.populateFromArray(start, _data, end, 'autofill');
selection.setRangeStart(new WalkontableCellCoords(drag[0], drag[1]));
selection.setRangeEnd(new WalkontableCellCoords(drag[2], drag[3]));
}
/*else {
//reset to avoid some range bug
selection.refreshBorders();
}*/
},
/**
* Show fill border
* @param {WalkontableCellCoords} coords
*/
showBorder: function (coords) {
var topLeft = priv.selRange.getTopLeftCorner();
var bottomRight = priv.selRange.getBottomRightCorner();
if (priv.settings.fillHandle !== 'horizontal' && (bottomRight.row < coords.row || topLeft.row > coords.row)) {
coords = new WalkontableCellCoords(coords.row, bottomRight.col);
}
else if (priv.settings.fillHandle !== 'vertical') {
coords = new WalkontableCellCoords(bottomRight.row, coords.col);
}
else {
return; //wrong direction
}
instance.view.wt.selections.fill.clear();
instance.view.wt.selections.fill.add(priv.selRange.from);
instance.view.wt.selections.fill.add(priv.selRange.to);
instance.view.wt.selections.fill.add(coords);
instance.view.render();
}
};
this.init = function () {
Handsontable.hooks.run(instance, 'beforeInit');
this.updateSettings(priv.settings, true);
this.view = new Handsontable.TableView(this);
editorManager = new Handsontable.EditorManager(instance, priv, selection, datamap);
this.forceFullRender = true; //used when data was changed
this.view.render();
if (typeof priv.firstRun === 'object') {
Handsontable.hooks.run(instance, 'afterChange', priv.firstRun[0], priv.firstRun[1]);
priv.firstRun = false;
}
Handsontable.hooks.run(instance, 'afterInit');
};
function ValidatorsQueue() { //moved this one level up so it can be used in any function here. Probably this should be moved to a separate file
var resolved = false;
return {
validatorsInQueue: 0,
addValidatorToQueue: function () {
this.validatorsInQueue++;
resolved = false;
},
removeValidatorFormQueue: function () {
this.validatorsInQueue = this.validatorsInQueue - 1 < 0 ? 0 : this.validatorsInQueue - 1;
this.checkIfQueueIsEmpty();
},
onQueueEmpty: function () {
},
checkIfQueueIsEmpty: function () {
if (this.validatorsInQueue == 0 && resolved == false) {
resolved = true;
this.onQueueEmpty();
}
}
};
}
function validateChanges(changes, source, callback) {
var waitingForValidator = new ValidatorsQueue();
waitingForValidator.onQueueEmpty = resolve;
for (var i = changes.length - 1; i >= 0; i--) {
if (changes[i] === null) {
changes.splice(i, 1);
}
else {
var row = changes[i][0];
var col = datamap.propToCol(changes[i][1]);
var logicalCol = instance.runHooksAndReturn('modifyCol', col); //column order may have changes, so we need to translate physical col index (stored in datasource) to logical (displayed to user)
var cellProperties = instance.getCellMeta(row, logicalCol);
if (cellProperties.type === 'numeric' && typeof changes[i][3] === 'string') {
if (changes[i][3].length > 0 && /^-?[\d\s]*(\.|\,)?\d*$/.test(changes[i][3])) {
if(typeof cellProperties.language == 'undefined') {
numeral.language('en');
} else {
numeral.language(cellProperties.language);
}
changes[i][3] = parseFloat(changes[i][3].replace(',','.'));
}
}
if (instance.getCellValidator(cellProperties)) {
waitingForValidator.addValidatorToQueue();
instance.validateCell(changes[i][3], cellProperties, (function (i, cellProperties) {
return function (result) {
if (typeof result !== 'boolean') {
throw new Error("Validation error: result is not boolean");
}
if (result === false && cellProperties.allowInvalid === false) {
changes.splice(i, 1); // cancel the change
cellProperties.valid = true; // we cancelled the change, so cell value is still valid
--i;
}
waitingForValidator.removeValidatorFormQueue();
}
})(i, cellProperties)
, source);
}
}
}
waitingForValidator.checkIfQueueIsEmpty();
function resolve() {
var beforeChangeResult;
if (changes.length) {
beforeChangeResult = Handsontable.hooks.execute(instance, "beforeChange", changes, source);
if (typeof beforeChangeResult === 'function') {
$.when(result).then(function () {
callback(); //called when async validators and async beforeChange are resolved
});
}
else if (beforeChangeResult === false) {
changes.splice(0, changes.length); //invalidate all changes (remove everything from array)
}
}
if (typeof beforeChangeResult !== 'function') {
callback(); //called when async validators are resolved and beforeChange was not async
}
}
}
/**
* Internal function to apply changes. Called after validateChanges
* @param {Array} changes Array in form of [row, prop, oldValue, newValue]
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
*/
function applyChanges(changes, source) {
var i = changes.length - 1;
if (i < 0) {
return;
}
for (; 0 <= i; i--) {
if (changes[i] === null) {
changes.splice(i, 1);
continue;
}
if(changes[i][2] == null && changes[i][3] == null) {
continue;
}
if (priv.settings.minSpareRows) {
while (changes[i][0] > instance.countRows() - 1) {
datamap.createRow();
}
}
if (instance.dataType === 'array' && priv.settings.minSpareCols) {
while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) {
datamap.createCol();
}
}
datamap.set(changes[i][0], changes[i][1], changes[i][3]);
}
instance.forceFullRender = true; //used when data was changed
grid.adjustRowsAndCols();
Handsontable.hooks.run(instance, 'beforeChangeRender', changes, source);
selection.refreshBorders(null, true);
Handsontable.hooks.run(instance, 'afterChange', changes, source || 'edit');
}
this.validateCell = function (value, cellProperties, callback, source) {
var validator = instance.getCellValidator(cellProperties);
if (Object.prototype.toString.call(validator) === '[object RegExp]') {
validator = (function (validator) {
return function (value, callback) {
callback(validator.test(value));
}
})(validator);
}
if (typeof validator == 'function') {
value = Handsontable.hooks.execute(instance, "beforeValidate", value, cellProperties.row, cellProperties.prop, source);
// To provide consistent behaviour, validation should be always asynchronous
setTimeout(function () {
validator.call(cellProperties, value, function (valid) {
cellProperties.valid = valid;
valid = Handsontable.hooks.execute(instance, "afterValidate", valid, value, cellProperties.row, cellProperties.prop, source);
callback(valid);
});
});
} else { //resolve callback even if validator function was not found
cellProperties.valid = true;
callback(true);
}
};
function setDataInputToArray(row, prop_or_col, value) {
if (typeof row === "object") { //is it an array of changes
return row;
}
else if ($.isPlainObject(value)) { //backwards compatibility
return value;
}
else {
return [
[row, prop_or_col, value]
];
}
}
/**
* Set data at given cell
* @public
* @param {Number|Array} row or array of changes in format [[row, col, value], ...]
* @param {Number|String} col or source String
* @param {String} value
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
*/
this.setDataAtCell = function (row, col, value, source) {
var input = setDataInputToArray(row, col, value)
, i
, ilen
, changes = []
, prop;
for (i = 0, ilen = input.length; i < ilen; i++) {
if (typeof input[i] !== 'object') {
throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter');
}
if (typeof input[i][1] !== 'number') {
throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`');
}
prop = datamap.colToProp(input[i][1]);
changes.push([
input[i][0],
prop,
datamap.get(input[i][0], prop),
input[i][2]
]);
}
if (!source && typeof row === "object") {
source = col;
}
validateChanges(changes, source, function () {
applyChanges(changes, source);
});
};
/**
* Set data at given row property
* @public
* @param {Number|Array} row or array of changes in format [[row, prop, value], ...]
* @param {String} prop or source String
* @param {String} value
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
*/
this.setDataAtRowProp = function (row, prop, value, source) {
var input = setDataInputToArray(row, prop, value)
, i
, ilen
, changes = [];
for (i = 0, ilen = input.length; i < ilen; i++) {
changes.push([
input[i][0],
input[i][1],
datamap.get(input[i][0], input[i][1]),
input[i][2]
]);
}
if (!source && typeof row === "object") {
source = prop;
}
validateChanges(changes, source, function () {
applyChanges(changes, source);
});
};
/**
* Listen to document body keyboard input
*/
this.listen = function () {
Handsontable.activeGuid = instance.guid;
if (document.activeElement && document.activeElement !== document.body) {
document.activeElement.blur();
}
else if (!document.activeElement) { //IE
document.body.focus();
}
};
/**
* Stop listening to document body keyboard input
*/
this.unlisten = function () {
Handsontable.activeGuid = null;
};
/**
* Returns true if current Handsontable instance is listening on document body keyboard input
*/
this.isListening = function () {
return Handsontable.activeGuid === instance.guid;
};
/**
* Destroys current editor, renders and selects current cell. If revertOriginal != true, edited data is saved
* @param {Boolean} revertOriginal
*/
this.destroyEditor = function (revertOriginal) {
selection.refreshBorders(revertOriginal);
};
/**
* Populate cells at position with 2d array
* @param {Number} row Start row
* @param {Number} col Start column
* @param {Array} input 2d array
* @param {Number=} endRow End row (use when you want to cut input when certain row is reached)
* @param {Number=} endCol End column (use when you want to cut input when certain column is reached)
* @param {String=} [source="populateFromArray"]
* @param {String=} [method="overwrite"]
* @return {Object|undefined} ending td in pasted area (only if any cell was changed)
*/
this.populateFromArray = function (row, col, input, endRow, endCol, source, method) {
if (!(typeof input === 'object' && typeof input[0] === 'object')) {
throw new Error("populateFromArray parameter `input` must be an array of arrays"); //API changed in 0.9-beta2, let's check if you use it correctly
}
return grid.populateFromArray(new WalkontableCellCoords(row, col), input, typeof endRow === 'number' ? new WalkontableCellCoords(endRow, endCol) : null, source, method);
};
/**
* Adds/removes data from the column
* @param {Number} col Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
this.spliceCol = function (col, index, amount/*, elements... */) {
return datamap.spliceCol.apply(datamap, arguments);
};
/**
* Adds/removes data from the row
* @param {Number} row Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
this.spliceRow = function (row, index, amount/*, elements... */) {
return datamap.spliceRow.apply(datamap, arguments);
};
/**
* Returns current selection. Returns undefined if there is no selection.
* @public
* @return {Array} [`startRow`, `startCol`, `endRow`, `endCol`]
*/
this.getSelected = function () { //https://github.com/handsontable/jquery-handsontable/issues/44 //cjl
if (selection.isSelected()) {
return [priv.selRange.from.row, priv.selRange.from.col, priv.selRange.to.row, priv.selRange.to.col];
}
};
/**
* Returns current selection as a WalkontableCellRange object. Returns undefined if there is no selection.
* @public
* @return {WalkontableCellRange}
*/
this.getSelectedRange = function () { //https://github.com/handsontable/jquery-handsontable/issues/44 //cjl
if (selection.isSelected()) {
return priv.selRange;
}
};
/**
* Render visible data
* @public
*/
this.render = function () {
if (instance.view) {
instance.forceFullRender = true; //used when data was changed
selection.refreshBorders(null, true);
}
};
/**
* Load data from array
* @public
* @param {Array} data
*/
this.loadData = function (data) {
if (typeof data === 'object' && data !== null) {
if (!(data.push && data.splice)) { //check if data is array. Must use duck-type check so Backbone Collections also pass it
//when data is not an array, attempt to make a single-row array of it
data = [data];
}
}
else if(data === null) {
data = [];
var row;
for (var r = 0, rlen = priv.settings.startRows; r < rlen; r++) {
row = [];
for (var c = 0, clen = priv.settings.startCols; c < clen; c++) {
row.push(null);
}
data.push(row);
}
}
else {
throw new Error("loadData only accepts array of objects or array of arrays (" + typeof data + " given)");
}
priv.isPopulated = false;
GridSettings.prototype.data = data;
if (priv.settings.dataSchema instanceof Array || data[0] instanceof Array) {
instance.dataType = 'array';
}
else if (typeof priv.settings.dataSchema === 'function') {
instance.dataType = 'function';
}
else {
instance.dataType = 'object';
}
datamap = new Handsontable.DataMap(instance, priv, GridSettings);
clearCellSettingCache();
grid.adjustRowsAndCols();
Handsontable.hooks.run(instance, 'afterLoadData');
if (priv.firstRun) {
priv.firstRun = [null, 'loadData'];
}
else {
Handsontable.hooks.run(instance, 'afterChange', null, 'loadData');
instance.render();
}
priv.isPopulated = true;
function clearCellSettingCache() {
priv.cellSettings.length = 0;
}
};
/**
* Return the current data object (the same that was passed by `data` configuration option or `loadData` method). Optionally you can provide cell range `r`, `c`, `r2`, `c2` to get only a fragment of grid data
* @public
* @param {Number} r (Optional) From row
* @param {Number} c (Optional) From col
* @param {Number} r2 (Optional) To row
* @param {Number} c2 (Optional) To col
* @return {Array|Object}
*/
this.getData = function (r, c, r2, c2) {
if (typeof r === 'undefined') {
return datamap.getAll();
}
else {
return datamap.getRange(new WalkontableCellCoords(r, c), new WalkontableCellCoords(r2, c2), datamap.DESTINATION_RENDERER);
}
};
this.getCopyableData = function (startRow, startCol, endRow, endCol) {
return datamap.getCopyableText(new WalkontableCellCoords(startRow, startCol), new WalkontableCellCoords(endRow, endCol));
};
/**
* Update settings
* @public
*/
this.updateSettings = function (settings, init) {
var i, clen;
if (typeof settings.rows !== "undefined") {
throw new Error("'rows' setting is no longer supported. do you mean startRows, minRows or maxRows?");
}
if (typeof settings.cols !== "undefined") {
throw new Error("'cols' setting is no longer supported. do you mean startCols, minCols or maxCols?");
}
for (i in settings) {
if (i === 'data') {
continue; //loadData will be triggered later
}
else {
if (Handsontable.hooks.hooks[i] !== void 0 || Handsontable.hooks.legacy[i] !== void 0) {
if (typeof settings[i] === 'function' || Handsontable.helper.isArray(settings[i])) {
instance.addHook(i, settings[i]);
}
}
else {
// Update settings
if (!init && settings.hasOwnProperty(i)) {
GridSettings.prototype[i] = settings[i];
}
}
}
}
// Load data or create data map
if (settings.data === void 0 && priv.settings.data === void 0) {
instance.loadData(null); //data source created just now
}
else if (settings.data !== void 0) {
instance.loadData(settings.data); //data source given as option
}
else if (settings.columns !== void 0) {
datamap.createMap();
}
// Init columns constructors configuration
clen = instance.countCols();
//Clear cellSettings cache
priv.cellSettings.length = 0;
if (clen > 0) {
var proto, column;
for (i = 0; i < clen; i++) {
priv.columnSettings[i] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts);
// shortcut for prototype
proto = priv.columnSettings[i].prototype;
// Use settings provided by user
if (GridSettings.prototype.columns) {
column = GridSettings.prototype.columns[i];
Handsontable.helper.extend(proto, column);
Handsontable.helper.extend(proto, expandType(column));
}
}
}
Handsontable.hooks.run(instance, 'afterCellMetaReset');
if (typeof settings.fillHandle !== "undefined") {
if (autofill.handle && settings.fillHandle === false) {
autofill.disable();
}
else if (!autofill.handle && settings.fillHandle !== false) {
autofill.init();
}
}
if (typeof settings.className !== "undefined") {
if (GridSettings.prototype.className) {
instance.rootElement.removeClass(GridSettings.prototype.className);
}
if (settings.className) {
instance.rootElement.addClass(settings.className);
}
}
if (typeof settings.height != 'undefined'){
var height = settings.height;
if (typeof height == 'function'){
height = height();
}
instance.rootElement[0].style.height = height + 'px';
}
if (typeof settings.width != 'undefined'){
var width = settings.width;
if (typeof width == 'function'){
width = width();
}
instance.rootElement[0].style.width = width + 'px';
}
if (height){
instance.rootElement[0].style.overflow = 'auto';
} else {
instance.rootElement[0].style.overflow = 'none';
}
if (!init) {
Handsontable.hooks.run(instance, 'afterUpdateSettings');
}
grid.adjustRowsAndCols();
if (instance.view && !priv.firstRun) {
instance.forceFullRender = true; //used when data was changed
selection.refreshBorders(null, true);
}
};
this.getValue = function () {
var sel = instance.getSelected();
if (GridSettings.prototype.getValue) {
if (typeof GridSettings.prototype.getValue === 'function') {
return GridSettings.prototype.getValue.call(instance);
}
else if (sel) {
return instance.getData()[sel[0]][GridSettings.prototype.getValue];
}
}
else if (sel) {
return instance.getDataAtCell(sel[0], sel[1]);
}
};
function expandType(obj) {
if (!obj.hasOwnProperty('type')) return; //ignore obj.prototype.type
var type, expandedType = {};
if (typeof obj.type === 'object') {
type = obj.type;
}
else if (typeof obj.type === 'string') {
type = Handsontable.cellTypes[obj.type];
if (type === void 0) {
throw new Error('You declared cell type "' + obj.type + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes');
}
}
for (var i in type) {
if (type.hasOwnProperty(i) && !obj.hasOwnProperty(i)) {
expandedType[i] = type[i];
}
}
return expandedType;
};
/**
* Returns current settings object
* @return {Object}
*/
this.getSettings = function () {
return priv.settings;
};
/**
* Clears grid
* @public
*/
this.clear = function () {
selection.selectAll();
selection.empty();
};
/**
* Inserts or removes rows and columns
* @param {String} action See grid.alter for possible values
* @param {Number} index
* @param {Number} amount
* @param {String} [source] Optional. Source of hook runner.
* @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
* @public
*/
this.alter = function (action, index, amount, source, keepEmptyRows) {
grid.alter(action, index, amount, source, keepEmptyRows);
};
/**
* Returns <td> element corresponding to params row, col
* @param {Number} row
* @param {Number} col
* @public
* @return {Element}
*/
this.getCell = function (row, col) {
return instance.view.getCellAtCoords(new WalkontableCellCoords(row, col));
};
/**
* Returns property name associated with column number
* @param {Number} col
* @public
* @return {String}
*/
this.colToProp = function (col) {
return datamap.colToProp(col);
};
/**
* Returns column number associated with property name
* @param {String} prop
* @public
* @return {Number}
*/
this.propToCol = function (prop) {
return datamap.propToCol(prop);
};
/**
* Return value at `row`, `col`
* @param {Number} row
* @param {Number} col
* @public
* @return value (mixed data type)
*/
this.getDataAtCell = function (row, col) {
return datamap.get(row, datamap.colToProp(col));
};
/**
* Return value at `row`, `prop`
* @param {Number} row
* @param {String} prop
* @public
* @return value (mixed data type)
*/
this.getDataAtRowProp = function (row, prop) {
return datamap.get(row, prop);
};
/**
* Return value at `col`
* @param {Number} col
* @public
* @return value (mixed data type)
*/
this.getDataAtCol = function (col) {
return [].concat.apply([], datamap.getRange(new WalkontableCellCoords(0, col), new WalkontableCellCoords(priv.settings.data.length - 1, col), datamap.DESTINATION_RENDERER));
};
/**
* Return value at `prop`
* @param {String} prop
* @public
* @return value (mixed data type)
*/
this.getDataAtProp = function (prop) {
return [].concat.apply([], datamap.getRange(new WalkontableCellCoords(0, datamap.propToCol(prop)), new WalkontableCellCoords(priv.settings.data.length - 1, datamap.propToCol(prop)), datamap.DESTINATION_RENDERER));
};
/**
* Return value at `row`
* @param {Number} row
* @public
* @return value (mixed data type)
*/
this.getDataAtRow = function (row) {
return priv.settings.data[row];
};
/**
* Sets cell meta data object "key" corresponding to params row, col
* @param {Number} row
* @param {Number} col
* @param {String} key
* @param {String} val
*
*/
this.setCellMeta = function (row, col, key, val) {
if (!priv.cellSettings[row]) {
priv.cellSettings[row] = [];
}
if (!priv.cellSettings[row][col]) {
priv.cellSettings[row][col] = new priv.columnSettings[col]();
}
priv.cellSettings[row][col][key] = val;
Handsontable.hooks.run(instance, 'afterSetCellMeta', row, col, key, val);
};
/**
* Returns cell meta data object corresponding to params row, col
* @param {Number} row
* @param {Number} col
* @public
* @return {Object}
*/
this.getCellMeta = function (row, col) {
var prop = datamap.colToProp(col)
, cellProperties;
row = translateRowIndex(row);
col = translateColIndex(col);
if (!priv.columnSettings[col]) {
priv.columnSettings[col] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts);
}
if (!priv.cellSettings[row]) {
priv.cellSettings[row] = [];
}
if (!priv.cellSettings[row][col]) {
priv.cellSettings[row][col] = new priv.columnSettings[col]();
}
cellProperties = priv.cellSettings[row][col]; //retrieve cellProperties from cache
cellProperties.row = row;
cellProperties.col = col;
cellProperties.prop = prop;
cellProperties.instance = instance;
Handsontable.hooks.run(instance, 'beforeGetCellMeta', row, col, cellProperties);
Handsontable.helper.extend(cellProperties, expandType(cellProperties)); //for `type` added in beforeGetCellMeta
if (cellProperties.cells) {
var settings = cellProperties.cells.call(cellProperties, row, col, prop);
if (settings) {
Handsontable.helper.extend(cellProperties, settings);
Handsontable.helper.extend(cellProperties, expandType(settings)); //for `type` added in cells
}
}
Handsontable.hooks.run(instance, 'afterGetCellMeta', row, col, cellProperties);
return cellProperties;
};
/**
* If displayed rows order is different than the order of rows stored in memory (i.e. sorting is applied)
* we need to translate logical (stored) row index to physical (displayed) index.
* @param row - original row index
* @returns {int} translated row index
*/
function translateRowIndex(row){
return Handsontable.hooks.execute(instance, 'modifyRow', row);
}
/**
* If displayed columns order is different than the order of columns stored in memory (i.e. column were moved using manualColumnMove plugin)
* we need to translate logical (stored) column index to physical (displayed) index.
* @param col - original column index
* @returns {int} - translated column index
*/
function translateColIndex(col){
return Handsontable.hooks.execute(instance, 'modifyCol', col); // warning: this must be done after datamap.colToProp
}
var rendererLookup = Handsontable.helper.cellMethodLookupFactory('renderer');
this.getCellRenderer = function (row, col) {
var renderer = rendererLookup.call(this, row, col);
return Handsontable.renderers.getRenderer(renderer);
};
this.getCellEditor = Handsontable.helper.cellMethodLookupFactory('editor');
this.getCellValidator = Handsontable.helper.cellMethodLookupFactory('validator');
/**
* Validates all cells using their validator functions and calls callback when finished. Does not render the view
* @param callback
*/
this.validateCells = function (callback) {
var waitingForValidator = new ValidatorsQueue();
waitingForValidator.onQueueEmpty = callback;
var i = instance.countRows() - 1;
while (i >= 0) {
var j = instance.countCols() - 1;
while (j >= 0) {
waitingForValidator.addValidatorToQueue();
instance.validateCell(instance.getDataAtCell(i, j), instance.getCellMeta(i, j), function () {
waitingForValidator.removeValidatorFormQueue();
}, 'validateCells');
j--;
}
i--;
}
waitingForValidator.checkIfQueueIsEmpty();
};
/**
* Return array of row headers (if they are enabled). If param `row` given, return header at given row as string
* @param {Number} row (Optional)
* @return {Array|String}
*/
this.getRowHeader = function (row) {
if (row === void 0) {
var out = [];
for (var i = 0, ilen = instance.countRows(); i < ilen; i++) {
out.push(instance.getRowHeader(i));
}
return out;
}
else if (Object.prototype.toString.call(priv.settings.rowHeaders) === '[object Array]' && priv.settings.rowHeaders[row] !== void 0) {
return priv.settings.rowHeaders[row];
}
else if (typeof priv.settings.rowHeaders === 'function') {
return priv.settings.rowHeaders(row);
}
else if (priv.settings.rowHeaders && typeof priv.settings.rowHeaders !== 'string' && typeof priv.settings.rowHeaders !== 'number') {
return row + 1;
}
else {
return priv.settings.rowHeaders;
}
};
/**
* Returns information of this table is configured to display row headers
* @returns {boolean}
*/
this.hasRowHeaders = function () {
return !!priv.settings.rowHeaders;
};
/**
* Returns information of this table is configured to display column headers
* @returns {boolean}
*/
this.hasColHeaders = function () {
if (priv.settings.colHeaders !== void 0 && priv.settings.colHeaders !== null) { //Polymer has empty value = null
return !!priv.settings.colHeaders;
}
for (var i = 0, ilen = instance.countCols(); i < ilen; i++) {
if (instance.getColHeader(i)) {
return true;
}
}
return false;
};
/**
* Return array of column headers (if they are enabled). If param `col` given, return header at given column as string
* @param {Number} col (Optional)
* @return {Array|String}
*/
this.getColHeader = function (col) {
if (col === void 0) {
var out = [];
for (var i = 0, ilen = instance.countCols(); i < ilen; i++) {
out.push(instance.getColHeader(i));
}
return out;
}
else {
var baseCol = col;
col = Handsontable.hooks.execute(instance, 'modifyCol', col);
if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].title) {
return priv.settings.columns[col].title;
}
else if (Object.prototype.toString.call(priv.settings.colHeaders) === '[object Array]' && priv.settings.colHeaders[col] !== void 0) {
return priv.settings.colHeaders[col];
}
else if (typeof priv.settings.colHeaders === 'function') {
return priv.settings.colHeaders(col);
}
else if (priv.settings.colHeaders && typeof priv.settings.colHeaders !== 'string' && typeof priv.settings.colHeaders !== 'number') {
return Handsontable.helper.spreadsheetColumnLabel(baseCol); //see #1458
}
else {
return priv.settings.colHeaders;
}
}
};
/**
* Return column width from settings (no guessing). Private use intended
* @param {Number} col
* @return {Number}
*/
this._getColWidthFromSettings = function (col) {
var cellProperties = instance.getCellMeta(0, col);
var width = cellProperties.width;
if (width === void 0 || width === priv.settings.width) {
width = cellProperties.colWidths;
}
if (width !== void 0 && width !== null) {
switch (typeof width) {
case 'object': //array
width = width[col];
break;
case 'function':
width = width(col);
break;
}
if (typeof width === 'string') {
width = parseInt(width, 10);
}
}
return width;
};
/**
* Return column width
* @param {Number} col
* @return {Number}
*/
this.getColWidth = function (col) {
var width = instance._getColWidthFromSettings(col);
if (!width) {
width = 50;
}
width = Handsontable.hooks.execute(instance, 'modifyColWidth', width, col);
return width;
};
/**
* Return row height from settings (no guessing). Private use intended
* @param {Number} row
* @return {Number}
*/
this._getRowHeightFromSettings= function (row) {
/* inefficient
var cellProperties = instance.getCellMeta(0, row);
var height = cellProperties.height;
if (height === void 0 || height === priv.settings.height) {
height = cellProperties.rowHeights;
}
*/
var height = priv.settings.rowHeights; //only uses grid settings
if (height !== void 0 && height !== null) {
switch (typeof height) {
case 'object': //array
height = height[row];
break;
case 'function':
height = height(row);
break;
}
if (typeof height === 'string') {
height = parseInt(height, 10);
}
}
return height;
};
/**
* Return row height
* @param {Number} row
* @return {Number}
*/
this.getRowHeight = function (row) {
var height = instance._getRowHeightFromSettings(row);
height = Handsontable.hooks.execute(instance, 'modifyRowHeight', height, row);
return height;
};
/**
* Return total number of rows in grid
* @return {Number}
*/
this.countRows = function () {
return priv.settings.data.length;
};
/**
* Return total number of columns in grid
* @return {Number}
*/
this.countCols = function () {
if (instance.dataType === 'object' || instance.dataType === 'function') {
if (priv.settings.columns && priv.settings.columns.length) {
return priv.settings.columns.length;
}
else {
return datamap.colToPropCache.length;
}
}
else if (instance.dataType === 'array') {
if (priv.settings.columns && priv.settings.columns.length) {
return priv.settings.columns.length;
}
else if (priv.settings.data && priv.settings.data[0] && priv.settings.data[0].length) {
return priv.settings.data[0].length;
}
else {
return 0;
}
}
};
/**
* Return index of first visible row
* @return {Number}
*/
this.rowOffset = function () {
return instance.view.wt.getSetting('offsetRow');
};
/**
* Return index of first visible column
* @return {Number}
*/
this.colOffset = function () {
return instance.view.wt.getSetting('offsetColumn');
};
/**
* Return number of visible rows. Returns -1 if table is not visible
* @return {Number}
*/
this.countVisibleRows = function () {
return instance.view.wt.drawn ? instance.view.wt.wtTable.rowStrategy.countVisible() : -1;
};
/**
* Return number of visible columns. Returns -1 if table is not visible
* @return {Number}
*/
this.countVisibleCols = function () {
return instance.view.wt.drawn ? instance.view.wt.wtTable.columnStrategy.countVisible() : -1;
};
/**
* Return number of empty rows
* @return {Boolean} ending If true, will only count empty rows at the end of the data source
*/
this.countEmptyRows = function (ending) {
var i = instance.countRows() - 1
, empty = 0
, row;
while (i >= 0) {
row = Handsontable.hooks.execute(this, 'modifyRow', i);
if (instance.isEmptyRow(row)) {
empty++;
}
else if (ending) {
break;
}
i--;
}
return empty;
};
/**
* Return number of empty columns
* @return {Boolean} ending If true, will only count empty columns at the end of the data source row
*/
this.countEmptyCols = function (ending) {
if (instance.countRows() < 1) {
return 0;
}
var i = instance.countCols() - 1
, empty = 0;
while (i >= 0) {
if (instance.isEmptyCol(i)) {
empty++;
}
else if (ending) {
break;
}
i--;
}
return empty;
};
/**
* Return true if the row at the given index is empty, false otherwise
* @param {Number} r Row index
* @return {Boolean}
*/
this.isEmptyRow = function (r) {
return priv.settings.isEmptyRow.call(instance, r);
};
/**
* Return true if the column at the given index is empty, false otherwise
* @param {Number} c Column index
* @return {Boolean}
*/
this.isEmptyCol = function (c) {
return priv.settings.isEmptyCol.call(instance, c);
};
/**
* Selects cell on grid. Optionally selects range to another cell
* @param {Number} row
* @param {Number} col
* @param {Number} [endRow]
* @param {Number} [endCol]
* @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to the selection
* @public
* @return {Boolean}
*/
this.selectCell = function (row, col, endRow, endCol, scrollToCell) {
if (typeof row !== 'number' || row < 0 || row >= instance.countRows()) {
return false;
}
if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) {
return false;
}
if (typeof endRow !== "undefined") {
if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) {
return false;
}
if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) {
return false;
}
}
var coords = new WalkontableCellCoords(row, col);
priv.selRange = new WalkontableCellRange(coords, coords, coords);
if (document.activeElement && document.activeElement !== document.documentElement && document.activeElement !== document.body) {
document.activeElement.blur(); //needed or otherwise prepare won't focus the cell. selectionSpec tests this (should move focus to selected cell)
}
instance.listen();
if (typeof endRow === "undefined") {
selection.setRangeEnd(priv.selRange.from, scrollToCell);
}
else {
selection.setRangeEnd(new WalkontableCellCoords(endRow, endCol), scrollToCell);
}
instance.selection.finish();
return true;
};
this.selectCellByProp = function (row, prop, endRow, endProp, scrollToCell) {
arguments[1] = datamap.propToCol(arguments[1]);
if (typeof arguments[3] !== "undefined") {
arguments[3] = datamap.propToCol(arguments[3]);
}
return instance.selectCell.apply(instance, arguments);
};
/**
* Deselects current sell selection on grid
* @public
*/
this.deselectCell = function () {
selection.deselect();
};
/**
* Remove grid from DOM
* @public
*/
this.destroy = function () {
instance._clearTimeouts();
if (instance.view) { //in case HT is destroyed before initialization has finished
instance.view.wt.destroy();
}
instance.rootElement.empty();
instance.rootElement.removeData('handsontable');
instance.rootElement.off('.handsontable');
$(window).off('.' + instance.guid);
$document.off('.' + instance.guid);
$body.off('.' + instance.guid);
Handsontable.hooks.run(instance, 'afterDestroy');
};
/**
* Returns active editor object
* @returns {Object}
*/
this.getActiveEditor = function(){
return editorManager.getActiveEditor();
};
/**
* Return Handsontable instance
* @public
* @return {Object}
*/
this.getInstance = function () {
return instance;
};
this.addHook = function (key, fn) {
Handsontable.hooks.add(key, fn, instance);
};
this.addHookOnce = function (key, fn) {
Handsontable.hooks.once(key, fn, instance);
};
this.removeHook = function (key, fn) {
Handsontable.hooks.remove(key, fn, instance);
};
this.runHooks = function (key, p1, p2, p3, p4, p5) {
Handsontable.hooks.run(instance, key, p1, p2, p3, p4, p5);
};
this.runHooksAndReturn = function (key, p1, p2, p3, p4, p5) {
return Handsontable.hooks.execute(instance, key, p1, p2, p3, p4, p5);
};
this.timeouts = {};
/**
* Sets timeout. Purpose of this method is to clear all known timeouts when `destroy` method is called
* @public
*/
this._registerTimeout = function (key, handle, ms) {
clearTimeout(this.timeouts[key]);
this.timeouts[key] = setTimeout(handle, ms || 0);
};
/**
* Clears all known timeouts
* @public
*/
this._clearTimeouts = function () {
for (var key in this.timeouts) {
if (this.timeouts.hasOwnProperty(key)) {
clearTimeout(this.timeouts[key]);
}
}
};
/**
* Handsontable version
*/
this.version = '0.11.0-beta1'; //inserted by grunt from package.json
};
var DefaultSettings = function () {};
DefaultSettings.prototype = {
data: void 0,
width: void 0,
height: void 0,
startRows: 5,
startCols: 5,
rowHeaders: null,
colHeaders: null,
minRows: 0,
minCols: 0,
maxRows: Infinity,
maxCols: Infinity,
minSpareRows: 0,
minSpareCols: 0,
multiSelect: true,
fillHandle: true,
fixedRowsTop: 0,
fixedColumnsLeft: 0,
outsideClickDeselects: true,
enterBeginsEditing: true,
enterMoves: {row: 1, col: 0},
tabMoves: {row: 0, col: 1},
autoWrapRow: false,
autoWrapCol: false,
copyRowsLimit: 1000,
copyColsLimit: 1000,
pasteMode: 'overwrite',
currentRowClassName: void 0,
currentColClassName: void 0,
stretchH: 'hybrid',
isEmptyRow: function (r) {
var val;
for (var c = 0, clen = this.countCols(); c < clen; c++) {
val = this.getDataAtCell(r, c);
if (val !== '' && val !== null && typeof val !== 'undefined') {
return false;
}
}
return true;
},
isEmptyCol: function (c) {
var val;
for (var r = 0, rlen = this.countRows(); r < rlen; r++) {
val = this.getDataAtCell(r, c);
if (val !== '' && val !== null && typeof val !== 'undefined') {
return false;
}
}
return true;
},
observeDOMVisibility: true,
allowInvalid: true,
invalidCellClassName: 'htInvalid',
placeholderCellClassName: 'htPlaceholder',
readOnlyCellClassName: 'htDimmed',
fragmentSelection: false,
readOnly: false,
type: 'text',
copyable: true,
debug: false, //shows debug overlays in Walkontable
wordWrap: true,
noWordWrapClassName: 'htNoWrap'
};
Handsontable.DefaultSettings = DefaultSettings;
$.fn.handsontable = function (action) {
var i
, ilen
, args
, output
, userSettings
, $this = this.first() // Use only first element from list
, instance = $this.data('handsontable');
// Init case
if (typeof action !== 'string') {
userSettings = action || {};
if (instance) {
instance.updateSettings(userSettings);
}
else {
instance = new Handsontable.Core($this, userSettings);
$this.data('handsontable', instance);
instance.init();
}
return $this;
}
// Action case
else {
args = [];
if (arguments.length > 1) {
for (i = 1, ilen = arguments.length; i < ilen; i++) {
args.push(arguments[i]);
}
}
if (instance) {
if (typeof instance[action] !== 'undefined') {
output = instance[action].apply(instance, args);
}
else {
throw new Error('Handsontable do not provide action: ' + action);
}
}
return output;
}
};
(function (window) {
'use strict';
function MultiMap() {
var map = {
arrayMap: [],
weakMap: new WeakMap()
};
return {
'get': function (key) {
if (canBeAnArrayMapKey(key)) {
return map.arrayMap[key];
} else if (canBeAWeakMapKey(key)) {
return map.weakMap.get(key);
}
},
'set': function (key, value) {
if (canBeAnArrayMapKey(key)) {
map.arrayMap[key] = value;
} else if (canBeAWeakMapKey(key)) {
map.weakMap.set(key, value);
} else {
throw new Error('Invalid key type');
}
},
'delete': function (key) {
if (canBeAnArrayMapKey(key)) {
delete map.arrayMap[key];
} else if (canBeAWeakMapKey(key)) {
map.weakMap['delete'](key); //Delete must be called using square bracket notation, because IE8 does not handle using `delete` with dot notation
}
}
};
function canBeAnArrayMapKey(obj){
return obj !== null && !isNaNSymbol(obj) && (typeof obj == 'string' || typeof obj == 'number');
}
function canBeAWeakMapKey(obj){
return obj !== null && (typeof obj == 'object' || typeof obj == 'function');
}
function isNaNSymbol(obj){
return obj !== obj; // NaN === NaN is always false
}
}
if (!window.MultiMap){
window.MultiMap = MultiMap;
}
})(window);
/**
* DOM helper optimized for maximum performance
* It is recommended for Handsontable plugins and renderers, because it is much faster than jQuery
* @type {Object}
*/
if(!window.Handsontable) {
var Handsontable = {}; //required because Walkontable test suite uses this class directly
}
Handsontable.Dom = {};
//goes up the DOM tree (including given element) until it finds an element that matches the nodeName
Handsontable.Dom.closest = function (elem, nodeNames, until) {
while (elem != null && elem !== until) {
if (elem.nodeType === 1 && nodeNames.indexOf(elem.nodeName) > -1) {
return elem;
}
elem = elem.parentNode;
}
return null;
};
//goes up the DOM tree and checks if element is child of another element
Handsontable.Dom.isChildOf = function (child, parent) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
};
/**
* Counts index of element within its parent
* WARNING: for performance reasons, assumes there are only element nodes (no text nodes). This is true for Walkotnable
* Otherwise would need to check for nodeType or use previousElementSibling
* @see http://jsperf.com/sibling-index/10
* @param {Element} elem
* @return {Number}
*/
Handsontable.Dom.index = function (elem) {
var i = 0;
while (elem = elem.previousSibling) {
++i
}
return i;
};
if (document.documentElement.classList) {
// HTML5 classList API
Handsontable.Dom.hasClass = function (ele, cls) {
return ele.classList.contains(cls);
};
Handsontable.Dom.addClass = function (ele, cls) {
ele.classList.add(cls);
};
Handsontable.Dom.removeClass = function (ele, cls) {
ele.classList.remove(cls);
};
}
else {
//http://snipplr.com/view/3561/addclass-removeclass-hasclass/
Handsontable.Dom.hasClass = function (ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
};
Handsontable.Dom.addClass = function (ele, cls) {
if (!this.hasClass(ele, cls)) ele.className += " " + cls;
};
Handsontable.Dom.removeClass = function (ele, cls) {
if (this.hasClass(ele, cls)) { //is this really needed?
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ').trim(); //String.prototype.trim is defined in polyfill.js
}
};
}
/*//http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/
Handsontable.Dom.addEvent = (function () {
var that = this;
if (document.addEventListener) {
return function (elem, type, cb) {
if ((elem && !elem.length) || elem === window) {
elem.addEventListener(type, cb, false);
}
else if (elem && elem.length) {
var len = elem.length;
for (var i = 0; i < len; i++) {
that.addEvent(elem[i], type, cb);
}
}
};
}
else {
return function (elem, type, cb) {
if ((elem && !elem.length) || elem === window) {
elem.attachEvent('on' + type, function () {
//normalize
//http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization
var e = window['event'];
e.target = e.srcElement;
//e.offsetX = e.layerX;
//e.offsetY = e.layerY;
e.relatedTarget = e.relatedTarget || e.type == 'mouseover' ? e.fromElement : e.toElement;
if (e.target.nodeType === 3) e.target = e.target.parentNode; //Safari bug
return cb.call(elem, e)
});
}
else if (elem.length) {
var len = elem.length;
for (var i = 0; i < len; i++) {
that.addEvent(elem[i], type, cb);
}
}
};
}
})();
Handsontable.Dom.triggerEvent = function (element, eventName, target) {
var event;
if (document.createEvent) {
event = document.createEvent("MouseEvents");
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
event.target = target;
if (document.createEvent) {
target.dispatchEvent(event);
} else {
target.fireEvent("on" + event.eventType, event);
}
};*/
Handsontable.Dom.removeTextNodes = function (elem, parent) {
if (elem.nodeType === 3) {
parent.removeChild(elem); //bye text nodes!
}
else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(elem.nodeName) > -1) {
var childs = elem.childNodes;
for (var i = childs.length - 1; i >= 0; i--) {
this.removeTextNodes(childs[i], elem);
}
}
};
/**
* Remove childs function
* WARNING - this doesn't unload events and data attached by jQuery
* http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9
* http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/11 - no siginificant improvement with Chrome remove() method
* @param element
* @returns {void}
*/
//
Handsontable.Dom.empty = function (element) {
var child;
while (child = element.lastChild) {
element.removeChild(child);
}
};
Handsontable.Dom.HTML_CHARACTERS = /(<(.*)>|&(.*);)/;
/**
* Insert content into element trying avoid innerHTML method.
* @return {void}
*/
Handsontable.Dom.fastInnerHTML = function (element, content) {
if (this.HTML_CHARACTERS.test(content)) {
element.innerHTML = content;
}
else {
this.fastInnerText(element, content);
}
};
/**
* Insert text content into element
* @return {void}
*/
if (document.createTextNode('test').textContent) { //STANDARDS
Handsontable.Dom.fastInnerText = function (element, content) {
var child = element.firstChild;
if (child && child.nodeType === 3 && child.nextSibling === null) {
//fast lane - replace existing text node
//http://jsperf.com/replace-text-vs-reuse
child.textContent = content;
}
else {
//slow lane - empty element and insert a text node
this.empty(element);
element.appendChild(document.createTextNode(content));
}
};
}
else { //IE8
Handsontable.Dom.fastInnerText = function (element, content) {
var child = element.firstChild;
if (child && child.nodeType === 3 && child.nextSibling === null) {
//fast lane - replace existing text node
//http://jsperf.com/replace-text-vs-reuse
child.data = content;
}
else {
//slow lane - empty element and insert a text node
this.empty(element);
element.appendChild(document.createTextNode(content));
}
};
}
/**
* Returns true/false depending if element has offset parent
* @param elem
* @returns {boolean}
*/
/*if (document.createTextNode('test').textContent) { //STANDARDS
Handsontable.Dom.hasOffsetParent = function (elem) {
return !!elem.offsetParent;
}
}
else {
Handsontable.Dom.hasOffsetParent = function (elem) {
try {
if (!elem.offsetParent) {
return false;
}
}
catch (e) {
return false; //IE8 throws "Unspecified error" when offsetParent is not found - we catch it here
}
return true;
}
}*/
/**
* Returns true if element is attached to the DOM and visible, false otherwise
* @param elem
* @returns {boolean}
*/
Handsontable.Dom.isVisible = function (elem) {
//fast method according to benchmarks, but requires layout so slow in our case
/*
if (!Handsontable.Dom.hasOffsetParent(elem)) {
return false; //fixes problem with UI Bootstrap <tabs> directive
}
// if (elem.offsetWidth > 0 || (elem.parentNode && elem.parentNode.offsetWidth > 0)) { //IE10 was mistaken here
if (elem.offsetWidth > 0) {
return true;
}
*/
//slow method
var next = elem;
while (next !== document.documentElement) { //until <html> reached
if (next === null) { //parent detached from DOM
return false;
}
else if (next.nodeType === 11) { //nodeType == 1 -> DOCUMENT_FRAGMENT_NODE
if (next.host) { //this is Web Components Shadow DOM
//see: http://w3c.github.io/webcomponents/spec/shadow/#encapsulation
//according to spec, should be if (next.ownerDocument !== window.document), but that doesn't work yet
if (next.host.impl) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features disabled
return Handsontable.Dom.isVisible(next.host.impl);
}
else if (next.host) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features enabled
return Handsontable.Dom.isVisible(next.host);
}
else {
throw new Error("Lost in Web Components world");
}
}
else {
return false; //this is a node detached from document in IE8
}
}
else if (next.style.display === 'none') {
return false;
}
next = next.parentNode;
}
return true;
};
/**
* Returns elements top and left offset relative to the document. In our usage case compatible with jQuery but 2x faster
* @param {HTMLElement} elem
* @return {Object}
*/
Handsontable.Dom.offset = function (elem) {
if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
//fixes problem with Firefox ignoring <caption> in TABLE offset (see also Handsontable.Dom.outerHeight)
//http://jsperf.com/offset-vs-getboundingclientrect/8
var box = elem.getBoundingClientRect();
return {
top: box.top + (window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0),
left: box.left + (window.pageXOffset || document.documentElement.scrollLeft) - (document.documentElement.clientLeft || 0)
};
}
var offsetLeft = elem.offsetLeft
, offsetTop = elem.offsetTop
, lastElem = elem;
while (elem = elem.offsetParent) {
if (elem === document.body) { //from my observation, document.body always has scrollLeft/scrollTop == 0
break;
}
offsetLeft += elem.offsetLeft;
offsetTop += elem.offsetTop;
lastElem = elem;
}
if (lastElem && lastElem.style.position === 'fixed') { //slow - http://jsperf.com/offset-vs-getboundingclientrect/6
//if(lastElem !== document.body) { //faster but does gives false positive in Firefox
offsetLeft += window.pageXOffset || document.documentElement.scrollLeft;
offsetTop += window.pageYOffset || document.documentElement.scrollTop;
}
return {
left: offsetLeft,
top: offsetTop
};
};
Handsontable.Dom.getWindowScrollTop = function () {
var res = window.scrollY;
if (res == void 0) { //IE8-11
res = document.documentElement.scrollTop;
}
return res;
};
Handsontable.Dom.getWindowScrollLeft = function () {
var res = window.scrollX;
if (res == void 0) { //IE8-11
res = document.documentElement.scrollLeft;
}
return res;
};
Handsontable.Dom.getScrollTop = function (elem) {
if (elem === window) {
return Handsontable.Dom.getWindowScrollTop(elem);
}
else {
return elem.scrollTop;
}
};
Handsontable.Dom.getScrollLeft = function (elem) {
if (elem === window) {
return Handsontable.Dom.getWindowScrollLeft(elem);
}
else {
return elem.scrollLeft;
}
};
Handsontable.Dom.getComputedStyle = function (elem) {
return elem.currentStyle || document.defaultView.getComputedStyle(elem);
};
Handsontable.Dom.outerWidth = function (elem) {
return elem.offsetWidth;
};
Handsontable.Dom.outerHeight = function (elem) {
if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
//fixes problem with Firefox ignoring <caption> in TABLE.offsetHeight
//jQuery (1.10.1) still has this unsolved
//may be better to just switch to getBoundingClientRect
//http://bililite.com/blog/2009/03/27/finding-the-size-of-a-table/
//http://lists.w3.org/Archives/Public/www-style/2009Oct/0089.html
//http://bugs.jquery.com/ticket/2196
//http://lists.w3.org/Archives/Public/www-style/2009Oct/0140.html#start140
return elem.offsetHeight + elem.firstChild.offsetHeight;
}
else {
return elem.offsetHeight;
}
};
(function () {
var hasCaptionProblem;
function detectCaptionProblem() {
var TABLE = document.createElement('TABLE');
TABLE.style.borderSpacing = 0;
TABLE.style.borderWidth = 0;
TABLE.style.padding = 0;
var TBODY = document.createElement('TBODY');
TABLE.appendChild(TBODY);
TBODY.appendChild(document.createElement('TR'));
TBODY.firstChild.appendChild(document.createElement('TD'));
TBODY.firstChild.firstChild.innerHTML = '<tr><td>t<br>t</td></tr>';
var CAPTION = document.createElement('CAPTION');
CAPTION.innerHTML = 'c<br>c<br>c<br>c';
CAPTION.style.padding = 0;
CAPTION.style.margin = 0;
TABLE.insertBefore(CAPTION, TBODY);
document.body.appendChild(TABLE);
hasCaptionProblem = (TABLE.offsetHeight < 2 * TABLE.lastChild.offsetHeight); //boolean
document.body.removeChild(TABLE);
}
Handsontable.Dom.hasCaptionProblem = function () {
if (hasCaptionProblem === void 0) {
detectCaptionProblem();
}
return hasCaptionProblem;
};
/**
* Returns caret position in text input
* @author http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea
* @return {Number}
*/
Handsontable.Dom.getCaretPosition = function (el) {
if (el.selectionStart) {
return el.selectionStart;
}
else if (document.selection) { //IE8
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
};
/**
* Sets caret position in text input
* @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
* @param {Element} el
* @param {Number} pos
* @param {Number} endPos
*/
Handsontable.Dom.setCaretPosition = function (el, pos, endPos) {
if (endPos === void 0) {
endPos = pos;
}
if (el.setSelectionRange) {
el.focus();
el.setSelectionRange(pos, endPos);
}
else if (el.createTextRange) { //IE8
var range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', endPos);
range.moveStart('character', pos);
range.select();
}
};
var cachedScrollbarWidth;
//http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes
function walkontableCalculateScrollbarWidth() {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild(inner);
(document.body || document.documentElement).appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
(document.body || document.documentElement).removeChild(outer);
return (w1 - w2);
}
/**
* Returns the computed width of the native browser scroll bar
* @return {Number} width
*/
Handsontable.Dom.getScrollbarWidth = function () {
if (cachedScrollbarWidth === void 0) {
cachedScrollbarWidth = walkontableCalculateScrollbarWidth();
}
return cachedScrollbarWidth;
}
})();
/**
* Handsontable TableView constructor
* @param {Object} instance
*/
Handsontable.TableView = function (instance) {
var that = this
, $window = $(window)
, $documentElement = $(document.documentElement);
this.instance = instance;
this.settings = instance.getSettings();
instance.rootElement.data('originalStyle', instance.rootElement[0].getAttribute('style')); //needed to retrieve original style in jsFiddle link generator in HT examples. may be removed in future versions
// in IE7 getAttribute('style') returns an object instead of a string, but we only support IE8+
instance.rootElement.addClass('handsontable');
var table = document.createElement('TABLE');
table.className = 'htCore';
this.THEAD = document.createElement('THEAD');
table.appendChild(this.THEAD);
this.TBODY = document.createElement('TBODY');
table.appendChild(this.TBODY);
instance.$table = $(table);
instance.container.prepend(instance.$table);
instance.rootElement.on('mousedown.handsontable', function (event) {
if (!that.isTextSelectionAllowed(event.target)) {
clearTextSelection();
event.preventDefault();
window.focus(); //make sure that window that contains HOT is active. Important when HOT is in iframe.
}
});
$documentElement.on('keyup.' + instance.guid, function (event) {
if (instance.selection.isInProgress() && !event.shiftKey) {
instance.selection.finish();
}
});
var isMouseDown;
$documentElement.on('mouseup.' + instance.guid, function (event) {
if (instance.selection.isInProgress() && event.which === 1) { //is left mouse button
instance.selection.finish();
}
isMouseDown = false;
if (instance.autofill.handle && instance.autofill.handle.isDragged) {
if (instance.autofill.handle.isDragged > 1) {
instance.autofill.apply();
}
instance.autofill.handle.isDragged = 0;
}
if (Handsontable.helper.isOutsideInput(document.activeElement)) {
instance.unlisten();
}
});
$documentElement.on('mousedown.' + instance.guid, function (event) {
var next = event.target;
if (next.shadowRoot) {
return; //click inside Web Component
}
if (next !== that.wt.wtTable.spreader) { //immediate click on "spreader" means click on the right side of vertical scrollbar
while (next !== document.documentElement) {
if (next === null) {
return; //click on something that was a row but now is detached (possibly because your click triggered a rerender)
}
if (next === instance.rootElement[0]) {
return; //click inside container
}
next = next.parentNode;
}
}
//function did not return until here, we have an outside click!
if (that.settings.outsideClickDeselects) {
instance.deselectCell();
}
else {
instance.destroyEditor();
}
});
instance.$table.on('selectstart', function (event) {
if (that.settings.fragmentSelection) {
return;
}
//https://github.com/handsontable/jquery-handsontable/issues/160
//selectstart is IE only event. Prevent text from being selected when performing drag down in IE8
event.preventDefault();
});
var clearTextSelection = function () {
//http://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
};
var walkontableConfig = {
debug: function () {
return that.settings.debug;
},
table: table,
stretchH: this.settings.stretchH,
data: instance.getDataAtCell,
totalRows: instance.countRows,
totalColumns: instance.countCols,
offsetRow: 0,
offsetColumn: 0,
fixedColumnsLeft: function () {
return that.settings.fixedColumnsLeft;
},
fixedRowsTop: function () {
return that.settings.fixedRowsTop;
},
renderAllRows: that.settings.renderAllRows,
rowHeaders: function () {
return instance.hasRowHeaders() ? [function (index, TH) {
that.appendRowHeader(index, TH);
}] : []
},
columnHeaders: function () {
return instance.hasColHeaders() ? [function (index, TH) {
that.appendColHeader(index, TH);
}] : []
},
columnWidth: instance.getColWidth,
rowHeight: instance.getRowHeight,
cellRenderer: function (row, col, TD) {
var prop = that.instance.colToProp(col)
, cellProperties = that.instance.getCellMeta(row, col)
, renderer = that.instance.getCellRenderer(cellProperties);
var value = that.instance.getDataAtRowProp(row, prop);
renderer(that.instance, TD, row, col, prop, value, cellProperties);
Handsontable.hooks.run(that.instance, 'afterRenderer', TD, row, col, prop, value, cellProperties);
},
selections: {
current: {
className: 'current',
border: {
width: 2,
color: '#5292F7',
style: 'solid',
cornerVisible: function () {
return that.settings.fillHandle && !that.isCellEdited() && !instance.selection.isMultiple()
}
}
},
area: {
className: 'area',
border: {
width: 1,
color: '#89AFF9',
style: 'solid',
cornerVisible: function () {
return that.settings.fillHandle && !that.isCellEdited() && instance.selection.isMultiple()
}
}
},
highlight: {
highlightRowClassName: that.settings.currentRowClassName,
highlightColumnClassName: that.settings.currentColClassName
},
fill: {
className: 'fill',
border: {
width: 1,
color: 'red',
style: 'solid'
}
}
},
hideBorderOnMouseDownOver: function () {
return that.settings.fragmentSelection;
},
onCellMouseDown: function (event, coords, TD, wt) {
instance.listen();
that.activeWt = wt;
isMouseDown = true;
if (event.target.className === 'manualColumnMover') {
return;
}
if (event.button === 2 && instance.selection.inInSelection(coords)) { //right mouse button
//do nothing
}
else if (event.shiftKey) {
if (coords.row >= 0 && coords.col >= 0) {
instance.selection.setRangeEnd(coords);
}
}
else {
if (coords.row < 0 || coords.col < 0) {
if (coords.row < 0) {
instance.selectCell(0, coords.col, instance.countRows() - 1, coords.col);
}
if (coords.col < 0) {
instance.selectCell(coords.row, 0, coords.row, instance.countCols() - 1);
}
}
else {
instance.selection.setRangeStart(coords);
}
}
Handsontable.hooks.run(instance, 'afterOnCellMouseDown', event, coords, TD);
that.activeWt = that.wt;
},
/*onCellMouseOut: function (/*event, coords, TD* /) {
if (isMouseDown && that.settings.fragmentSelection === 'single') {
clearTextSelection(); //otherwise text selection blinks during multiple cells selection
}
},*/
onCellMouseOver: function (event, coords, TD, wt) {
that.activeWt = wt;
if (coords.row >= 0 && coords.col >= 0) { //is not a header
if (isMouseDown) {
/*if (that.settings.fragmentSelection === 'single') {
clearTextSelection(); //otherwise text selection blinks during multiple cells selection
}*/
instance.selection.setRangeEnd(coords);
}
else if (instance.autofill.handle && instance.autofill.handle.isDragged) {
instance.autofill.handle.isDragged++;
instance.autofill.showBorder(coords);
}
}
Handsontable.hooks.run(instance, 'afterOnCellMouseOver', event, coords, TD);
that.activeWt = that.wt;
},
onCellCornerMouseDown: function (event) {
instance.autofill.handle.isDragged = 1;
event.preventDefault();
Handsontable.hooks.run(instance, 'afterOnCellCornerMouseDown', event);
},
onCellCornerDblClick: function () {
instance.autofill.selectAdjacent();
},
beforeDraw: function (force) {
that.beforeRender(force);
},
onDraw: function(force){
that.onDraw(force);
},
onScrollVertically: function () {
instance.runHooks('afterScrollVertically');
},
onScrollHorizontally: function () {
instance.runHooks('afterScrollHorizontally');
}
};
Handsontable.hooks.run(instance, 'beforeInitWalkontable', walkontableConfig);
this.wt = new Walkontable(walkontableConfig);
this.activeWt = this.wt;
/*$window.on('resize.' + instance.guid, function () {
instance._registerTimeout('resizeTimeout', function () {
instance.forceFullRender = true;
that.render();
}, 60);
});*/
$(that.wt.wtTable.spreader).on('mousedown.handsontable, contextmenu.handsontable', function (event) {
if (event.target === that.wt.wtTable.spreader && event.which === 3) { //right mouse button exactly on spreader means right clickon the right hand side of vertical scrollbar
event.stopPropagation();
}
});
$documentElement.on('click.' + instance.guid, function () {
if (that.settings.observeDOMVisibility) {
if (that.wt.drawInterrupted) {
that.instance.forceFullRender = true;
that.render();
}
}
});
};
Handsontable.TableView.prototype.isTextSelectionAllowed = function (el) {
if ( Handsontable.helper.isInput(el) ) {
return (true);
}
if (this.settings.fragmentSelection && Handsontable.Dom.isChildOf(el, this.TBODY)) {
return (true);
}
return false;
};
Handsontable.TableView.prototype.isCellEdited = function () {
var activeEditor = this.instance.getActiveEditor();
return activeEditor && activeEditor.isOpened();
};
Handsontable.TableView.prototype.getWidth = function () {
return this.wt.wtViewport.getWorkspaceActualWidth();
};
Handsontable.TableView.prototype.getHeight = function () {
return this.wt.wtViewport.getWorkspaceActualHeight();
};
Handsontable.TableView.prototype.beforeRender = function (force) {
if (force) { //force = did Walkontable decide to do full render
Handsontable.hooks.run(this.instance, 'beforeRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render?
}
};
Handsontable.TableView.prototype.onDraw = function(force){
if (force) { //force = did Walkontable decide to do full render
Handsontable.hooks.run(this.instance, 'afterRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render?
}
};
Handsontable.TableView.prototype.render = function () {
this.wt.draw(!this.instance.forceFullRender);
this.instance.forceFullRender = false;
this.instance.rootElement.triggerHandler('render.handsontable');
};
/**
* Returns td object given coordinates
* @param {WalkontableCellCoords} coords
*/
Handsontable.TableView.prototype.getCellAtCoords = function (coords) {
var td = this.wt.wtTable.getCell(coords);
if (td < 0) { //there was an exit code (cell is out of bounds)
return null;
}
else {
return td;
}
};
/**
* Scroll viewport to selection
* @param {WalkontableCellCoords} coords
*/
Handsontable.TableView.prototype.scrollViewport = function (coords) {
this.wt.scrollViewport(coords);
};
/**
* Append row header to a TH element
* @param row
* @param TH
*/
Handsontable.TableView.prototype.appendRowHeader = function (row, TH) {
if (row > -1) {
Handsontable.Dom.fastInnerHTML(TH, this.instance.getRowHeader(row));
}
else {
var DIV = document.createElement('DIV');
DIV.className = 'relative';
Handsontable.Dom.fastInnerText(DIV, '\u00A0');
Handsontable.Dom.empty(TH);
TH.appendChild(DIV);
}
};
/**
* Append column header to a TH element
* @param col
* @param TH
*/
Handsontable.TableView.prototype.appendColHeader = function (col, TH) {
var DIV = document.createElement('DIV')
, SPAN = document.createElement('SPAN');
DIV.className = 'relative';
SPAN.className = 'colHeader';
Handsontable.Dom.fastInnerHTML(SPAN, this.instance.getColHeader(col));
DIV.appendChild(SPAN);
Handsontable.Dom.empty(TH);
TH.appendChild(DIV);
Handsontable.hooks.run(this.instance, 'afterGetColHeader', col, TH);
};
/**
* Given a element's left position relative to the viewport, returns maximum element width until the right edge of the viewport (before scrollbar)
* @param {Number} left
* @return {Number}
*/
Handsontable.TableView.prototype.maximumVisibleElementWidth = function (leftOffset) {
this.wt.wtScrollbars.horizontal.readWindowSize();
var workspaceWidth = this.wt.wtViewport.getWorkspaceWidth();
var maxWidth = workspaceWidth - leftOffset;
return maxWidth > 0 ? maxWidth : 0;
};
/**
* Given a element's top position relative to the viewport, returns maximum element height until the bottom edge of the viewport (before scrollbar)
* @param {Number} topOffset
* @return {Number}
*/
Handsontable.TableView.prototype.maximumVisibleElementHeight = function (topOffset) {
this.wt.wtScrollbars.vertical.readWindowSize();
var workspaceHeight = this.wt.wtViewport.getWorkspaceHeight();
var maxHeight = workspaceHeight - topOffset;
return maxHeight > 0 ? maxHeight : 0;
};
Handsontable.TableView.prototype.mainViewIsActive = function () {
return this.wt === this.activeWt;
};
/**
* Utility to register editors and common namespace for keeping reference to all editor classes
*/
(function (Handsontable) {
'use strict';
function RegisteredEditor(editorClass) {
var clazz, instances;
instances = {};
clazz = editorClass;
this.getInstance = function (hotInstance) {
if (!(hotInstance.guid in instances)) {
instances[hotInstance.guid] = new clazz(hotInstance);
}
return instances[hotInstance.guid];
}
}
var registeredEditorNames = {};
var registeredEditorClasses = new WeakMap();
Handsontable.editors = {
/**
* Registers editor under given name
* @param {String} editorName
* @param {Function} editorClass
*/
registerEditor: function (editorName, editorClass) {
var editor = new RegisteredEditor(editorClass);
if (typeof editorName === "string") {
registeredEditorNames[editorName] = editor;
}
registeredEditorClasses.set(editorClass, editor);
},
/**
* Returns instance (singleton) of editor class
* @param {String|Function} editorName/editorClass
* @returns {Function} editorClass
*/
getEditor: function (editorName, hotInstance) {
var editor;
if (typeof editorName == 'function') {
if (!(registeredEditorClasses.get(editorName))) {
this.registerEditor(null, editorName);
}
editor = registeredEditorClasses.get(editorName);
}
else if (typeof editorName == 'string') {
editor = registeredEditorNames[editorName];
}
else {
throw Error('Only strings and functions can be passed as "editor" parameter ');
}
if (!editor) {
throw Error('No editor registered under name "' + editorName + '"');
}
return editor.getInstance(hotInstance);
}
};
})(Handsontable);
(function(Handsontable){
'use strict';
Handsontable.EditorManager = function(instance, priv, selection){
var that = this;
var $document = $(document);
var keyCodes = Handsontable.helper.keyCode;
var activeEditor;
var init = function () {
function onKeyDown(event) {
if (!instance.isListening()) {
return;
}
if (priv.settings.beforeOnKeyDown) { // HOT in HOT Plugin
priv.settings.beforeOnKeyDown.call(instance, event);
}
Handsontable.hooks.run(instance, 'beforeKeyDown', event);
if (!event.isImmediatePropagationStopped()) {
priv.lastKeyCode = event.keyCode;
if (selection.isSelected()) {
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
if (!activeEditor.isWaiting()) {
if (!Handsontable.helper.isMetaKey(event.keyCode) && !ctrlDown && !that.isEditorOpened()) {
that.openEditor('');
event.stopPropagation(); //required by HandsontableEditor
return;
}
}
var rangeModifier = event.shiftKey ? selection.setRangeEnd : selection.setRangeStart;
switch (event.keyCode) {
case keyCodes.A:
if (ctrlDown) {
selection.selectAll(); //select all cells
event.preventDefault();
event.stopPropagation();
break;
}
case keyCodes.ARROW_UP:
if (that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionUp(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.ARROW_DOWN:
if (that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionDown(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.ARROW_RIGHT:
if(that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionRight(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.ARROW_LEFT:
if(that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionLeft(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.TAB:
var tabMoves = typeof priv.settings.tabMoves === 'function' ? priv.settings.tabMoves(event) : priv.settings.tabMoves;
if (event.shiftKey) {
selection.transformStart(-tabMoves.row, -tabMoves.col); //move selection left
}
else {
selection.transformStart(tabMoves.row, tabMoves.col, true); //move selection right (add a new column if needed)
}
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.BACKSPACE:
case keyCodes.DELETE:
selection.empty(event);
that.prepareEditor();
event.preventDefault();
break;
case keyCodes.F2: /* F2 */
that.openEditor();
event.preventDefault(); //prevent Opera from opening Go to Page dialog
break;
case keyCodes.ENTER: /* return/enter */
if(that.isEditorOpened()){
if (activeEditor.state !== Handsontable.EditorState.WAITING){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionAfterEnter(event.shiftKey);
} else {
if (instance.getSettings().enterBeginsEditing){
that.openEditor();
} else {
moveSelectionAfterEnter(event.shiftKey);
}
}
event.preventDefault(); //don't add newline to field
event.stopImmediatePropagation(); //required by HandsontableEditor
break;
case keyCodes.ESCAPE:
if(that.isEditorOpened()){
that.closeEditorAndRestoreOriginalValue(ctrlDown);
}
event.preventDefault();
break;
case keyCodes.HOME:
if (event.ctrlKey || event.metaKey) {
rangeModifier(new WalkontableCellCoords(0, priv.selRange.from.col));
}
else {
rangeModifier(new WalkontableCellCoords(priv.selRange.from.row, 0));
}
event.preventDefault(); //don't scroll the window
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.END:
if (event.ctrlKey || event.metaKey) {
rangeModifier(new WalkontableCellCoords(instance.countRows() - 1, priv.selRange.from.col));
}
else {
rangeModifier(new WalkontableCellCoords(priv.selRange.from.row, instance.countCols() - 1));
}
event.preventDefault(); //don't scroll the window
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.PAGE_UP:
selection.transformStart(-instance.countVisibleRows(), 0);
instance.view.wt.scrollVertical(-instance.countVisibleRows());
instance.view.render();
event.preventDefault(); //don't page up the window
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.PAGE_DOWN:
selection.transformStart(instance.countVisibleRows(), 0);
instance.view.wt.scrollVertical(instance.countVisibleRows());
instance.view.render();
event.preventDefault(); //don't page down the window
event.stopPropagation(); //required by HandsontableEditor
break;
default:
break;
}
}
}
}
$document.on('keydown.handsontable.' + instance.guid, onKeyDown);
function onDblClick(event, coords, elem) {
if(elem.nodeName == "TD") { //may be TD or TH
//that.instance.destroyEditor();
that.openEditor();
}
}
instance.view.wt.update('onCellDblClick', onDblClick);
instance.addHook('afterDestroy', function(){
$document.off('keydown.handsontable.' + instance.guid);
});
function moveSelectionAfterEnter(shiftKey){
var enterMoves = typeof priv.settings.enterMoves === 'function' ? priv.settings.enterMoves(event) : priv.settings.enterMoves;
if (shiftKey) {
selection.transformStart(-enterMoves.row, -enterMoves.col); //move selection up
}
else {
selection.transformStart(enterMoves.row, enterMoves.col, true); //move selection down (add a new row if needed)
}
}
function moveSelectionUp(shiftKey){
if (shiftKey) {
selection.transformEnd(-1, 0);
}
else {
selection.transformStart(-1, 0);
}
}
function moveSelectionDown(shiftKey){
if (shiftKey) {
selection.transformEnd(1, 0); //expanding selection down with shift
}
else {
selection.transformStart(1, 0); //move selection down
}
}
function moveSelectionRight(shiftKey){
if (shiftKey) {
selection.transformEnd(0, 1);
}
else {
selection.transformStart(0, 1);
}
}
function moveSelectionLeft(shiftKey){
if (shiftKey) {
selection.transformEnd(0, -1);
}
else {
selection.transformStart(0, -1);
}
}
};
/**
* Destroy current editor, if exists
* @param {Boolean} revertOriginal
*/
this.destroyEditor = function (revertOriginal) {
this.closeEditor(revertOriginal);
};
this.getActiveEditor = function () {
return activeEditor;
};
/**
* Prepare text input to be displayed at given grid cell
*/
this.prepareEditor = function () {
if (activeEditor && activeEditor.isWaiting()){
this.closeEditor(false, false, function(dataSaved){
if(dataSaved){
that.prepareEditor();
}
});
return;
}
var row = priv.selRange.highlight.row;
var col = priv.selRange.highlight.col;
var prop = instance.colToProp(col);
var td = instance.getCell(row, col);
var originalValue = instance.getDataAtCell(row, col);
var cellProperties = instance.getCellMeta(row, col);
var editorClass = instance.getCellEditor(cellProperties);
activeEditor = Handsontable.editors.getEditor(editorClass, instance);
activeEditor.prepare(row, col, prop, td, originalValue, cellProperties);
};
this.isEditorOpened = function () {
return activeEditor.isOpened();
};
this.openEditor = function (initialValue) {
if (!activeEditor.cellProperties.readOnly){
activeEditor.beginEditing(initialValue);
}
};
this.closeEditor = function (restoreOriginalValue, ctrlDown, callback) {
if (!activeEditor){
if(callback) {
callback(false);
}
}
else {
activeEditor.finishEditing(restoreOriginalValue, ctrlDown, callback);
}
};
this.closeEditorAndSaveChanges = function(ctrlDown){
return this.closeEditor(false, ctrlDown);
};
this.closeEditorAndRestoreOriginalValue = function(ctrlDown){
return this.closeEditor(true, ctrlDown);
};
init();
};
})(Handsontable);
/**
* Utility to register renderers and common namespace for keeping reference to all renderers classes
*/
(function (Handsontable) {
'use strict';
var registeredRenderers = {};
Handsontable.renderers = {
/**
* Registers renderer under given name
* @param {String} rendererName
* @param {Function} rendererFunction
*/
registerRenderer: function (rendererName, rendererFunction) {
registeredRenderers[rendererName] = rendererFunction
},
/**
* @param {String|Function} rendererName/rendererFunction
* @returns {Function} rendererFunction
*/
getRenderer: function (rendererName) {
if (typeof rendererName == 'function'){
return rendererName;
}
if (typeof rendererName != 'string'){
throw Error('Only strings and functions can be passed as "renderer" parameter ');
}
if (!(rendererName in registeredRenderers)) {
throw Error('No editor registered under name "' + rendererName + '"');
}
return registeredRenderers[rendererName];
}
};
})(Handsontable);
/**
* Returns true if keyCode represents a printable character
* @param {Number} keyCode
* @return {Boolean}
*/
Handsontable.helper.isPrintableChar = function (keyCode) {
return ((keyCode == 32) || //space
(keyCode >= 48 && keyCode <= 57) || //0-9
(keyCode >= 96 && keyCode <= 111) || //numpad
(keyCode >= 186 && keyCode <= 192) || //;=,-./`
(keyCode >= 219 && keyCode <= 222) || //[]{}\|"'
keyCode >= 226 || //special chars (229 for Asian chars)
(keyCode >= 65 && keyCode <= 90)); //a-z
};
Handsontable.helper.isMetaKey = function (keyCode) {
var keyCodes = Handsontable.helper.keyCode;
var metaKeys = [
keyCodes.ARROW_DOWN,
keyCodes.ARROW_UP,
keyCodes.ARROW_LEFT,
keyCodes.ARROW_RIGHT,
keyCodes.HOME,
keyCodes.END,
keyCodes.DELETE,
keyCodes.BACKSPACE,
keyCodes.F1,
keyCodes.F2,
keyCodes.F3,
keyCodes.F4,
keyCodes.F5,
keyCodes.F6,
keyCodes.F7,
keyCodes.F8,
keyCodes.F9,
keyCodes.F10,
keyCodes.F11,
keyCodes.F12,
keyCodes.TAB,
keyCodes.PAGE_DOWN,
keyCodes.PAGE_UP,
keyCodes.ENTER,
keyCodes.ESCAPE,
keyCodes.SHIFT,
keyCodes.CAPS_LOCK,
keyCodes.ALT
];
return metaKeys.indexOf(keyCode) != -1;
};
Handsontable.helper.isCtrlKey = function (keyCode) {
var keys = Handsontable.helper.keyCode;
return [keys.CONTROL_LEFT, 224, keys.COMMAND_LEFT, keys.COMMAND_RIGHT].indexOf(keyCode) != -1;
};
/**
* Converts a value to string
* @param value
* @return {String}
*/
Handsontable.helper.stringify = function (value) {
switch (typeof value) {
case 'string':
case 'number':
return value + '';
break;
case 'object':
if (value === null) {
return '';
}
else {
return value.toString();
}
break;
case 'undefined':
return '';
break;
default:
return value.toString();
}
};
/**
* Generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB, etc
* @param index
* @returns {String}
*/
Handsontable.helper.spreadsheetColumnLabel = function (index) {
var dividend = index + 1;
var columnLabel = '';
var modulo;
while (dividend > 0) {
modulo = (dividend - 1) % 26;
columnLabel = String.fromCharCode(65 + modulo) + columnLabel;
dividend = parseInt((dividend - modulo) / 26, 10);
}
return columnLabel;
};
/**
* Checks if value of n is a numeric one
* http://jsperf.com/isnan-vs-isnumeric/4
* @param n
* @returns {boolean}
*/
Handsontable.helper.isNumeric = function (n) {
var t = typeof n;
return t == 'number' ? !isNaN(n) && isFinite(n) :
t == 'string' ? !n.length ? false :
n.length == 1 ? /\d/.test(n) :
/^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) :
t == 'object' ? !!n && typeof n.valueOf() == "number" && !(n instanceof Date) : false;
};
Handsontable.helper.isArray = function (obj) {
return Object.prototype.toString.call(obj).match(/array/i) !== null;
};
/**
* Checks if child is a descendant of given parent node
* http://stackoverflow.com/questions/2234979/how-to-check-in-javascript-if-one-element-is-a-child-of-another
* @param parent
* @param child
* @returns {boolean}
*/
Handsontable.helper.isDescendant = function (parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
};
/**
* Generates a random hex string. Used as namespace for Handsontable instance events.
* @return {String} - 16 character random string: "92b1bfc74ec4"
*/
Handsontable.helper.randomString = function () {
return walkontableRandomString();
};
/**
* Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`.
* Creates temporary dummy function to call it as constructor.
* Described in ticket: https://github.com/handsontable/jquery-handsontable/pull/516
* @param {Object} Child child class
* @param {Object} Parent parent class
* @return {Object} extended Child
*/
Handsontable.helper.inherit = function (Child, Parent) {
Parent.prototype.constructor = Parent;
Child.prototype = new Parent();
Child.prototype.constructor = Child;
return Child;
};
/**
* Perform shallow extend of a target object with extension's own properties
* @param {Object} target An object that will receive the new properties
* @param {Object} extension An object containing additional properties to merge into the target
*/
Handsontable.helper.extend = function (target, extension) {
for (var i in extension) {
if (extension.hasOwnProperty(i)) {
target[i] = extension[i];
}
}
};
Handsontable.helper.getPrototypeOf = function (obj) {
var prototype;
if(typeof obj.__proto__ == "object"){
prototype = obj.__proto__;
} else {
var oldConstructor,
constructor = obj.constructor;
if (typeof obj.constructor == "function") {
oldConstructor = constructor;
if (delete obj.constructor){
constructor = obj.constructor; // get real constructor
obj.constructor = oldConstructor; // restore constructor
}
}
prototype = constructor ? constructor.prototype : null; // needed for IE
}
return prototype;
};
/**
* Factory for columns constructors.
* @param {Object} GridSettings
* @param {Array} conflictList
* @return {Object} ColumnSettings
*/
Handsontable.helper.columnFactory = function (GridSettings, conflictList) {
function ColumnSettings () {}
Handsontable.helper.inherit(ColumnSettings, GridSettings);
// Clear conflict settings
for (var i = 0, len = conflictList.length; i < len; i++) {
ColumnSettings.prototype[conflictList[i]] = void 0;
}
return ColumnSettings;
};
Handsontable.helper.translateRowsToColumns = function (input) {
var i
, ilen
, j
, jlen
, output = []
, olen = 0;
for (i = 0, ilen = input.length; i < ilen; i++) {
for (j = 0, jlen = input[i].length; j < jlen; j++) {
if (j == olen) {
output.push([]);
olen++;
}
output[j].push(input[i][j])
}
}
return output;
};
Handsontable.helper.to2dArray = function (arr) {
var i = 0
, ilen = arr.length;
while (i < ilen) {
arr[i] = [arr[i]];
i++;
}
};
Handsontable.helper.extendArray = function (arr, extension) {
var i = 0
, ilen = extension.length;
while (i < ilen) {
arr.push(extension[i]);
i++;
}
};
/**
* Determines if the given DOM element is an input field.
* Notice: By 'input' we mean input, textarea and select nodes
* @param element - DOM element
* @returns {boolean}
*/
Handsontable.helper.isInput = function (element) {
var inputs = ['INPUT', 'SELECT', 'TEXTAREA'];
return inputs.indexOf(element.nodeName) > -1;
}
/**
* Determines if the given DOM element is an input field placed OUTSIDE of HOT.
* Notice: By 'input' we mean input, textarea and select nodes
* @param element - DOM element
* @returns {boolean}
*/
Handsontable.helper.isOutsideInput = function (element) {
return Handsontable.helper.isInput(element) && element.className.indexOf('handsontableInput') == -1;
};
Handsontable.helper.keyCode = {
MOUSE_LEFT: 1,
MOUSE_RIGHT: 3,
MOUSE_MIDDLE: 2,
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
END: 35,
ENTER: 13,
ESCAPE: 27,
CONTROL_LEFT: 91,
COMMAND_LEFT: 17,
COMMAND_RIGHT: 93,
ALT: 18,
HOME: 36,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
SPACE: 32,
SHIFT: 16,
CAPS_LOCK: 20,
TAB: 9,
ARROW_RIGHT: 39,
ARROW_LEFT: 37,
ARROW_UP: 38,
ARROW_DOWN: 40,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F11: 122,
F12: 123,
A: 65,
X: 88,
C: 67,
V: 86
};
/**
* Determines whether given object is a plain Object.
* Note: String and Array are not plain Objects
* @param {*} obj
* @returns {boolean}
*/
Handsontable.helper.isObject = function (obj) {
return Object.prototype.toString.call(obj) == '[object Object]';
};
/**
* Determines whether given object is an Array.
* Note: String is not an Array
* @param {*} obj
* @returns {boolean}
*/
Handsontable.helper.isArray = function(obj){
return Array.isArray ? Array.isArray(obj) : Object.prototype.toString.call(obj) == '[object Array]';
};
Handsontable.helper.pivot = function (arr) {
var pivotedArr = [];
if(!arr || arr.length == 0 || !arr[0] || arr[0].length == 0){
return pivotedArr;
}
var rowCount = arr.length;
var colCount = arr[0].length;
for(var i = 0; i < rowCount; i++){
for(var j = 0; j < colCount; j++){
if(!pivotedArr[j]){
pivotedArr[j] = [];
}
pivotedArr[j][i] = arr[i][j];
}
}
return pivotedArr;
};
Handsontable.helper.proxy = function (fun, context) {
return function () {
return fun.apply(context, arguments);
};
};
/**
* Factory that produces a function for searching methods (or any properties) which could be defined directly in
* table configuration or implicitly, within cell type definition.
*
* For example: renderer can be defined explicitly using "renderer" property in column configuration or it can be
* defined implicitly using "type" property.
*
* Methods/properties defined explicitly always takes precedence over those defined through "type".
*
* If the method/property is not found in an object, searching is continued recursively through prototype chain, until
* it reaches the Object.prototype.
*
*
* @param methodName {String} name of the method/property to search (i.e. 'renderer', 'validator', 'copyable')
* @param allowUndefined {Boolean} [optional] if false, the search is continued if methodName has not been found in cell "type"
* @returns {Function}
*/
Handsontable.helper.cellMethodLookupFactory = function (methodName, allowUndefined) {
allowUndefined = typeof allowUndefined == 'undefined' ? true : allowUndefined;
return function cellMethodLookup (row, col) {
return (function getMethodFromProperties(properties) {
if (!properties){
return; //method not found
}
else if (properties.hasOwnProperty(methodName) && properties[methodName] !== void 0) { //check if it is own and is not empty
return properties[methodName]; //method defined directly
} else if (properties.hasOwnProperty('type') && properties.type) { //check if it is own and is not empty
var type;
if(typeof properties.type != 'string' ){
throw new Error('Cell type must be a string ');
}
type = translateTypeNameToObject(properties.type);
if (type.hasOwnProperty(methodName)) {
return type[methodName]; //method defined in type.
} else if (allowUndefined) {
return; //method does not defined in type (eg. validator), returns undefined
}
}
return getMethodFromProperties(Handsontable.helper.getPrototypeOf(properties));
})(typeof row == 'number' ? this.getCellMeta(row, col) : row);
};
function translateTypeNameToObject(typeName) {
var type = Handsontable.cellTypes[typeName];
if(typeof type == 'undefined'){
throw new Error('You declared cell type "' + typeName + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes');
}
return type;
}
};
Handsontable.helper.toString = function (obj) {
return '' + obj;
};
(function (Handsontable) {
'use strict';
/**
* Utility class that gets and saves data from/to the data source using mapping of columns numbers to object property names
* TODO refactor arguments of methods getRange, getText to be numbers (not objects)
* TODO remove priv, GridSettings from object constructor
*
* @param instance
* @param priv
* @param GridSettings
* @constructor
*/
Handsontable.DataMap = function (instance, priv, GridSettings) {
this.instance = instance;
this.priv = priv;
this.GridSettings = GridSettings;
this.dataSource = this.instance.getSettings().data;
if (this.dataSource[0]) {
this.duckSchema = this.recursiveDuckSchema(this.dataSource[0]);
}
else {
this.duckSchema = {};
}
this.createMap();
};
Handsontable.DataMap.prototype.DESTINATION_RENDERER = 1;
Handsontable.DataMap.prototype.DESTINATION_CLIPBOARD_GENERATOR = 2;
Handsontable.DataMap.prototype.recursiveDuckSchema = function (obj) {
var schema;
if ($.isPlainObject(obj)) {
schema = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if ($.isPlainObject(obj[i])) {
schema[i] = this.recursiveDuckSchema(obj[i]);
}
else {
schema[i] = null;
}
}
}
}
else {
schema = [];
}
return schema;
};
Handsontable.DataMap.prototype.recursiveDuckColumns = function (schema, lastCol, parent) {
var prop, i;
if (typeof lastCol === 'undefined') {
lastCol = 0;
parent = '';
}
if ($.isPlainObject(schema)) {
for (i in schema) {
if (schema.hasOwnProperty(i)) {
if (schema[i] === null) {
prop = parent + i;
this.colToPropCache.push(prop);
this.propToColCache.set(prop, lastCol);
lastCol++;
}
else {
lastCol = this.recursiveDuckColumns(schema[i], lastCol, i + '.');
}
}
}
}
return lastCol;
};
Handsontable.DataMap.prototype.createMap = function () {
if (typeof this.getSchema() === "undefined") {
throw new Error("trying to create `columns` definition but you didnt' provide `schema` nor `data`");
}
var i, ilen, schema = this.getSchema();
this.colToPropCache = [];
this.propToColCache = new MultiMap();
var columns = this.instance.getSettings().columns;
if (columns) {
for (i = 0, ilen = columns.length; i < ilen; i++) {
if (typeof columns[i].data != 'undefined'){
this.colToPropCache[i] = columns[i].data;
this.propToColCache.set(columns[i].data, i);
}
}
}
else {
this.recursiveDuckColumns(schema);
}
};
Handsontable.DataMap.prototype.colToProp = function (col) {
col = Handsontable.hooks.execute(this.instance, 'modifyCol', col);
if (this.colToPropCache && typeof this.colToPropCache[col] !== 'undefined') {
return this.colToPropCache[col];
}
else {
return col;
}
};
Handsontable.DataMap.prototype.propToCol = function (prop) {
var col;
if (typeof this.propToColCache.get(prop) !== 'undefined') {
col = this.propToColCache.get(prop);
} else {
col = prop;
}
col = Handsontable.hooks.execute(this.instance, 'modifyCol', col);
return col;
};
Handsontable.DataMap.prototype.getSchema = function () {
var schema = this.instance.getSettings().dataSchema;
if (schema) {
if (typeof schema === 'function') {
return schema();
}
return schema;
}
return this.duckSchema;
};
/**
* Creates row at the bottom of the data array
* @param {Number} [index] Optional. Index of the row before which the new row will be inserted
*/
Handsontable.DataMap.prototype.createRow = function (index, amount, createdAutomatically) {
var row
, colCount = this.instance.countCols()
, numberOfCreatedRows = 0
, currentIndex;
if (!amount) {
amount = 1;
}
if (typeof index !== 'number' || index >= this.instance.countRows()) {
index = this.instance.countRows();
}
currentIndex = index;
var maxRows = this.instance.getSettings().maxRows;
while (numberOfCreatedRows < amount && this.instance.countRows() < maxRows) {
if (this.instance.dataType === 'array') {
row = [];
for (var c = 0; c < colCount; c++) {
row.push(null);
}
}
else if (this.instance.dataType === 'function') {
row = this.instance.getSettings().dataSchema(index);
}
else {
row = $.extend(true, {}, this.getSchema());
}
if (index === this.instance.countRows()) {
this.dataSource.push(row);
}
else {
this.dataSource.splice(index, 0, row);
}
numberOfCreatedRows++;
currentIndex++;
}
Handsontable.hooks.run(this.instance, 'afterCreateRow', index, numberOfCreatedRows, createdAutomatically);
this.instance.forceFullRender = true; //used when data was changed
return numberOfCreatedRows;
};
/**
* Creates col at the right of the data array
* @param {Number} [index] Optional. Index of the column before which the new column will be inserted
* * @param {Number} [amount] Optional.
*/
Handsontable.DataMap.prototype.createCol = function (index, amount, createdAutomatically) {
if (this.instance.dataType === 'object' || this.instance.getSettings().columns) {
throw new Error("Cannot create new column. When data source in an object, " +
"you can only have as much columns as defined in first data row, data schema or in the 'columns' setting." +
"If you want to be able to add new columns, you have to use array datasource.");
}
var rlen = this.instance.countRows()
, data = this.dataSource
, constructor
, numberOfCreatedCols = 0
, currentIndex;
if (!amount) {
amount = 1;
}
currentIndex = index;
var maxCols = this.instance.getSettings().maxCols;
while (numberOfCreatedCols < amount && this.instance.countCols() < maxCols) {
constructor = Handsontable.helper.columnFactory(this.GridSettings, this.priv.columnsSettingConflicts);
if (typeof index !== 'number' || index >= this.instance.countCols()) {
for (var r = 0; r < rlen; r++) {
if (typeof data[r] === 'undefined') {
data[r] = [];
}
data[r].push(null);
}
// Add new column constructor
this.priv.columnSettings.push(constructor);
}
else {
for (var r = 0; r < rlen; r++) {
data[r].splice(currentIndex, 0, null);
}
// Add new column constructor at given index
this.priv.columnSettings.splice(currentIndex, 0, constructor);
}
numberOfCreatedCols++;
currentIndex++;
}
Handsontable.hooks.run(this.instance, 'afterCreateCol', index, numberOfCreatedCols, createdAutomatically);
this.instance.forceFullRender = true; //used when data was changed
return numberOfCreatedCols;
};
/**
* Removes row from the data array
* @param {Number} [index] Optional. Index of the row to be removed. If not provided, the last row will be removed
* @param {Number} [amount] Optional. Amount of the rows to be removed. If not provided, one row will be removed
*/
Handsontable.DataMap.prototype.removeRow = function (index, amount) {
if (!amount) {
amount = 1;
}
if (typeof index !== 'number') {
index = -amount;
}
index = (this.instance.countRows() + index) % this.instance.countRows();
// We have to map the physical row ids to logical and than perform removing with (possibly) new row id
var logicRows = this.physicalRowsToLogical(index, amount);
var actionWasNotCancelled = Handsontable.hooks.execute(this.instance, 'beforeRemoveRow', index, amount);
if (actionWasNotCancelled === false) {
return;
}
var data = this.dataSource;
var newData = data.filter(function (row, index) {
return logicRows.indexOf(index) == -1;
});
data.length = 0;
Array.prototype.push.apply(data, newData);
Handsontable.hooks.run(this.instance, 'afterRemoveRow', index, amount);
this.instance.forceFullRender = true; //used when data was changed
};
/**
* Removes column from the data array
* @param {Number} [index] Optional. Index of the column to be removed. If not provided, the last column will be removed
* @param {Number} [amount] Optional. Amount of the columns to be removed. If not provided, one column will be removed
*/
Handsontable.DataMap.prototype.removeCol = function (index, amount) {
if (this.instance.dataType === 'object' || this.instance.getSettings().columns) {
throw new Error("cannot remove column with object data source or columns option specified");
}
if (!amount) {
amount = 1;
}
if (typeof index !== 'number') {
index = -amount;
}
index = (this.instance.countCols() + index) % this.instance.countCols();
var actionWasNotCancelled = Handsontable.hooks.execute(this.instance, 'beforeRemoveCol', index, amount);
if (actionWasNotCancelled === false) {
return;
}
var data = this.dataSource;
for (var r = 0, rlen = this.instance.countRows(); r < rlen; r++) {
data[r].splice(index, amount);
}
this.priv.columnSettings.splice(index, amount);
Handsontable.hooks.run(this.instance, 'afterRemoveCol', index, amount);
this.instance.forceFullRender = true; //used when data was changed
};
/**
* Add / removes data from the column
* @param {Number} col Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
Handsontable.DataMap.prototype.spliceCol = function (col, index, amount/*, elements...*/) {
var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : [];
var colData = this.instance.getDataAtCol(col);
var removed = colData.slice(index, index + amount);
var after = colData.slice(index + amount);
Handsontable.helper.extendArray(elements, after);
var i = 0;
while (i < amount) {
elements.push(null); //add null in place of removed elements
i++;
}
Handsontable.helper.to2dArray(elements);
this.instance.populateFromArray(index, col, elements, null, null, 'spliceCol');
return removed;
};
/**
* Add / removes data from the row
* @param {Number} row Index of row in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
Handsontable.DataMap.prototype.spliceRow = function (row, index, amount/*, elements...*/) {
var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : [];
var rowData = this.instance.getDataAtRow(row);
var removed = rowData.slice(index, index + amount);
var after = rowData.slice(index + amount);
Handsontable.helper.extendArray(elements, after);
var i = 0;
while (i < amount) {
elements.push(null); //add null in place of removed elements
i++;
}
this.instance.populateFromArray(row, index, [elements], null, null, 'spliceRow');
return removed;
};
/**
* Returns single value from the data array
* @param {Number} row
* @param {Number} prop
*/
Handsontable.DataMap.prototype.get = function (row, prop) {
row = Handsontable.hooks.execute(this.instance, 'modifyRow', row);
if (typeof prop === 'string' && prop.indexOf('.') > -1) {
var sliced = prop.split(".");
var out = this.dataSource[row];
if (!out) {
return null;
}
for (var i = 0, ilen = sliced.length; i < ilen; i++) {
out = out[sliced[i]];
if (typeof out === 'undefined') {
return null;
}
}
return out;
}
else if (typeof prop === 'function') {
/**
* allows for interacting with complex structures, for example
* d3/jQuery getter/setter properties:
*
* {columns: [{
* data: function(row, value){
* if(arguments.length === 1){
* return row.property();
* }
* row.property(value);
* }
* }]}
*/
return prop(this.dataSource.slice(
row,
row + 1
)[0]);
}
else {
return this.dataSource[row] ? this.dataSource[row][prop] : null;
}
};
var copyableLookup = Handsontable.helper.cellMethodLookupFactory('copyable', false);
/**
* Returns single value from the data array (intended for clipboard copy to an external application)
* @param {Number} row
* @param {Number} prop
* @return {String}
*/
Handsontable.DataMap.prototype.getCopyable = function (row, prop) {
if (copyableLookup.call(this.instance, row, this.propToCol(prop))) {
return this.get(row, prop);
}
return '';
};
/**
* Saves single value to the data array
* @param {Number} row
* @param {Number} prop
* @param {String} value
* @param {String} [source] Optional. Source of hook runner.
*/
Handsontable.DataMap.prototype.set = function (row, prop, value, source) {
row = Handsontable.hooks.execute(this.instance, 'modifyRow', row, source || "datamapGet");
if (typeof prop === 'string' && prop.indexOf('.') > -1) {
var sliced = prop.split(".");
var out = this.dataSource[row];
for (var i = 0, ilen = sliced.length - 1; i < ilen; i++) {
out = out[sliced[i]];
}
out[sliced[i]] = value;
}
else if (typeof prop === 'function') {
/* see the `function` handler in `get` */
prop(this.dataSource.slice(
row,
row + 1
)[0], value);
}
else {
this.dataSource[row][prop] = value;
}
};
/**
* This ridiculous piece of code maps rows Id that are present in table data to those displayed for user.
* The trick is, the physical row id (stored in settings.data) is not necessary the same
* as the logical (displayed) row id (e.g. when sorting is applied).
*/
Handsontable.DataMap.prototype.physicalRowsToLogical = function (index, amount) {
var totalRows = this.instance.countRows();
var physicRow = (totalRows + index) % totalRows;
var logicRows = [];
var rowsToRemove = amount;
var row;
while (physicRow < totalRows && rowsToRemove) {
row = Handsontable.hooks.execute(this.instance, 'modifyRow', physicRow);
logicRows.push(row);
rowsToRemove--;
physicRow++;
}
return logicRows;
};
/**
* Clears the data array
*/
Handsontable.DataMap.prototype.clear = function () {
for (var r = 0; r < this.instance.countRows(); r++) {
for (var c = 0; c < this.instance.countCols(); c++) {
this.set(r, this.colToProp(c), '');
}
}
};
/**
* Returns the data array
* @return {Array}
*/
Handsontable.DataMap.prototype.getAll = function () {
return this.dataSource;
};
/**
* Returns data range as array
* @param {Object} start Start selection position
* @param {Object} end End selection position
* @param {Number} destination Destination of datamap.get
* @return {Array}
*/
Handsontable.DataMap.prototype.getRange = function (start, end, destination) {
var r, rlen, c, clen, output = [], row;
var getFn = destination === this.DESTINATION_CLIPBOARD_GENERATOR ? this.getCopyable : this.get;
rlen = Math.max(start.row, end.row);
clen = Math.max(start.col, end.col);
for (r = Math.min(start.row, end.row); r <= rlen; r++) {
row = [];
for (c = Math.min(start.col, end.col); c <= clen; c++) {
row.push(getFn.call(this, r, this.colToProp(c)));
}
output.push(row);
}
return output;
};
/**
* Return data as text (tab separated columns)
* @param {Object} start (Optional) Start selection position
* @param {Object} end (Optional) End selection position
* @return {String}
*/
Handsontable.DataMap.prototype.getText = function (start, end) {
return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_RENDERER));
};
/**
* Return data as copyable text (tab separated columns intended for clipboard copy to an external application)
* @param {Object} start (Optional) Start selection position
* @param {Object} end (Optional) End selection position
* @return {String}
*/
Handsontable.DataMap.prototype.getCopyableText = function (start, end) {
return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_CLIPBOARD_GENERATOR));
};
})(Handsontable);
(function (Handsontable) {
'use strict';
/*
Adds appropriate CSS class to table cell, based on cellProperties
*/
Handsontable.renderers.cellDecorator = function (instance, TD, row, col, prop, value, cellProperties) {
if (cellProperties.className) {
TD.className = cellProperties.className;
}
if (cellProperties.readOnly) {
Handsontable.Dom.addClass(TD, cellProperties.readOnlyCellClassName);
}
if (cellProperties.valid === false && cellProperties.invalidCellClassName) {
Handsontable.Dom.addClass(TD, cellProperties.invalidCellClassName);
}
if (cellProperties.wordWrap === false && cellProperties.noWordWrapClassName) {
Handsontable.Dom.addClass(TD, cellProperties.noWordWrapClassName);
}
if (!value && cellProperties.placeholder) {
Handsontable.Dom.addClass(TD, cellProperties.placeholderCellClassName);
}
}
})(Handsontable);
/**
* Default text renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
(function (Handsontable) {
'use strict';
var TextRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
Handsontable.renderers.cellDecorator.apply(this, arguments);
if (!value && cellProperties.placeholder) {
value = cellProperties.placeholder;
}
var escaped = Handsontable.helper.stringify(value);
if (cellProperties.rendererTemplate) {
Handsontable.Dom.empty(TD);
var TEMPLATE = document.createElement('TEMPLATE');
TEMPLATE.setAttribute('bind', '{{}}');
TEMPLATE.innerHTML = cellProperties.rendererTemplate;
HTMLTemplateElement.decorate(TEMPLATE);
TEMPLATE.model = instance.getDataAtRow(row);
TD.appendChild(TEMPLATE);
}
else {
Handsontable.Dom.fastInnerText(TD, escaped); //this is faster than innerHTML. See: https://github.com/handsontable/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
};
//Handsontable.TextRenderer = TextRenderer; //Left for backward compatibility
Handsontable.renderers.TextRenderer = TextRenderer;
Handsontable.renderers.registerRenderer('text', TextRenderer);
})(Handsontable);
(function (Handsontable) {
var clonableWRAPPER = document.createElement('DIV');
clonableWRAPPER.className = 'htAutocompleteWrapper';
var clonableARROW = document.createElement('DIV');
clonableARROW.className = 'htAutocompleteArrow';
clonableARROW.appendChild(document.createTextNode('\u25BC'));
//this is faster than innerHTML. See: https://github.com/handsontable/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
var wrapTdContentWithWrapper = function(TD, WRAPPER){
WRAPPER.innerHTML = TD.innerHTML;
Handsontable.Dom.empty(TD);
TD.appendChild(WRAPPER);
};
/**
* Autocomplete renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
var AutocompleteRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
var WRAPPER = clonableWRAPPER.cloneNode(true); //this is faster than createElement
var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement
Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties);
TD.appendChild(ARROW);
Handsontable.Dom.addClass(TD, 'htAutocomplete');
if (!TD.firstChild) { //http://jsperf.com/empty-node-if-needed
//otherwise empty fields appear borderless in demo/renderers.html (IE)
TD.appendChild(document.createTextNode('\u00A0')); //\u00A0 equals for a text node
//this is faster than innerHTML. See: https://github.com/handsontable/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
if (!instance.acArrowListener) {
//not very elegant but easy and fast
instance.acArrowListener = function () {
instance.view.wt.getSetting('onCellDblClick', null, new WalkontableCellCoords(row, col), TD);
};
instance.rootElement.on('mousedown.htAutocompleteArrow', '.htAutocompleteArrow', instance.acArrowListener); //this way we don't bind event listener to each arrow. We rely on propagation instead
//We need to unbind the listener after the table has been destroyed
instance.addHookOnce('afterDestroy', function () {
this.rootElement.off('mousedown.htAutocompleteArrow');
});
}
};
Handsontable.AutocompleteRenderer = AutocompleteRenderer;
Handsontable.renderers.AutocompleteRenderer = AutocompleteRenderer;
Handsontable.renderers.registerRenderer('autocomplete', AutocompleteRenderer);
})(Handsontable);
/**
* Checkbox renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
(function (Handsontable) {
'use strict';
var clonableINPUT = document.createElement('INPUT');
clonableINPUT.className = 'htCheckboxRendererInput';
clonableINPUT.type = 'checkbox';
clonableINPUT.setAttribute('autocomplete', 'off');
var CheckboxRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
if (typeof cellProperties.checkedTemplate === "undefined") {
cellProperties.checkedTemplate = true;
}
if (typeof cellProperties.uncheckedTemplate === "undefined") {
cellProperties.uncheckedTemplate = false;
}
Handsontable.Dom.empty(TD); //TODO identify under what circumstances this line can be removed
var INPUT = clonableINPUT.cloneNode(false); //this is faster than createElement
if (value === cellProperties.checkedTemplate || value === Handsontable.helper.stringify(cellProperties.checkedTemplate)) {
INPUT.checked = true;
TD.appendChild(INPUT);
}
else if (value === cellProperties.uncheckedTemplate || value === Handsontable.helper.stringify(cellProperties.uncheckedTemplate)) {
TD.appendChild(INPUT);
}
else if (value === null) { //default value
INPUT.className += ' noValue';
TD.appendChild(INPUT);
}
else {
Handsontable.Dom.fastInnerText(TD, '#bad value#'); //this is faster than innerHTML. See: https://github.com/handsontable/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
var $input = $(INPUT);
if (cellProperties.readOnly) {
$input.on('click', function (event) {
event.preventDefault();
});
}
else {
$input.on('mousedown', function (event) {
event.stopPropagation(); //otherwise can confuse cell mousedown handler
});
$input.on('mouseup', function (event) {
event.stopPropagation(); //otherwise can confuse cell dblclick handler
});
$input.on('change', function(){
if (this.checked) {
instance.setDataAtRowProp(row, prop, cellProperties.checkedTemplate);
}
else {
instance.setDataAtRowProp(row, prop, cellProperties.uncheckedTemplate);
}
});
}
if(!instance.CheckboxRenderer || !instance.CheckboxRenderer.beforeKeyDownHookBound){
instance.CheckboxRenderer = {
beforeKeyDownHookBound : true
};
instance.addHook('beforeKeyDown', function(event){
if(event.keyCode == Handsontable.helper.keyCode.SPACE){
var cell, checkbox, cellProperties;
var selRange = instance.getSelectedRange();
var topLeft = selRange.getTopLeftCorner();
var bottomRight = selRange.getBottomRightCorner();
for(var row = topLeft.row; row <= bottomRight.row; row++ ){
for(var col = topLeft.col; col <= bottomRight.col; col++){
cell = instance.getCell(row, col);
cellProperties = instance.getCellMeta(row, col);
checkbox = cell.querySelectorAll('input[type=checkbox]');
if(checkbox.length > 0 && !cellProperties.readOnly){
if(!event.isImmediatePropagationStopped()){
event.stopImmediatePropagation();
event.preventDefault();
}
for(var i = 0, len = checkbox.length; i < len; i++){
checkbox[i].checked = !checkbox[i].checked;
$(checkbox[i]).trigger('change');
}
}
}
}
}
});
}
};
Handsontable.CheckboxRenderer = CheckboxRenderer;
Handsontable.renderers.CheckboxRenderer = CheckboxRenderer;
Handsontable.renderers.registerRenderer('checkbox', CheckboxRenderer);
})(Handsontable);
/**
* Numeric cell renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
(function (Handsontable) {
'use strict';
var NumericRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
if (Handsontable.helper.isNumeric(value)) {
if (typeof cellProperties.language !== 'undefined') {
numeral.language(cellProperties.language)
}
value = numeral(value).format(cellProperties.format || '0'); //docs: http://numeraljs.com/
Handsontable.Dom.addClass(TD, 'htNumeric');
}
Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties);
};
Handsontable.NumericRenderer = NumericRenderer; //Left for backward compatibility with versions prior 0.10.0
Handsontable.renderers.NumericRenderer = NumericRenderer;
Handsontable.renderers.registerRenderer('numeric', NumericRenderer);
})(Handsontable);
(function(Handosntable){
'use strict';
var PasswordRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
Handsontable.renderers.TextRenderer.apply(this, arguments);
value = TD.innerHTML;
var hash;
var hashLength = cellProperties.hashLength || value.length;
var hashSymbol = cellProperties.hashSymbol || '*';
for( hash = ''; hash.split(hashSymbol).length - 1 < hashLength; hash += hashSymbol);
Handsontable.Dom.fastInnerHTML(TD, hash);
};
Handosntable.PasswordRenderer = PasswordRenderer;
Handosntable.renderers.PasswordRenderer = PasswordRenderer;
Handosntable.renderers.registerRenderer('password', PasswordRenderer);
})(Handsontable);
(function (Handsontable) {
function HtmlRenderer(instance, TD, row, col, prop, value, cellProperties){
Handsontable.renderers.cellDecorator.apply(this, arguments);
Handsontable.Dom.fastInnerHTML(TD, value);
}
Handsontable.renderers.registerRenderer('html', HtmlRenderer);
Handsontable.renderers.HtmlRenderer = HtmlRenderer;
})(Handsontable);
(function (Handsontable) {
'use strict';
Handsontable.EditorState = {
VIRGIN: 'STATE_VIRGIN', //before editing
EDITING: 'STATE_EDITING',
WAITING: 'STATE_WAITING', //waiting for async validation
FINISHED: 'STATE_FINISHED'
};
function BaseEditor(instance) {
this.instance = instance;
this.state = Handsontable.EditorState.VIRGIN;
this._opened = false;
this._closeCallback = null;
this.init();
}
BaseEditor.prototype._fireCallbacks = function(result) {
if(this._closeCallback){
this._closeCallback(result);
this._closeCallback = null;
}
}
BaseEditor.prototype.init = function(){};
BaseEditor.prototype.getValue = function(){
throw Error('Editor getValue() method unimplemented');
};
BaseEditor.prototype.setValue = function(newValue){
throw Error('Editor setValue() method unimplemented');
};
BaseEditor.prototype.open = function(){
throw Error('Editor open() method unimplemented');
};
BaseEditor.prototype.close = function(){
throw Error('Editor close() method unimplemented');
};
BaseEditor.prototype.prepare = function(row, col, prop, td, originalValue, cellProperties){
this.TD = td;
this.row = row;
this.col = col;
this.prop = prop;
this.originalValue = originalValue;
this.cellProperties = cellProperties;
this.state = Handsontable.EditorState.VIRGIN;
};
BaseEditor.prototype.extend = function(){
var baseClass = this.constructor;
function Editor(){
baseClass.apply(this, arguments);
}
function inherit(Child, Parent){
function Bridge() {
}
Bridge.prototype = Parent.prototype;
Child.prototype = new Bridge();
Child.prototype.constructor = Child;
return Child;
}
return inherit(Editor, baseClass);
};
BaseEditor.prototype.saveValue = function (val, ctrlDown) {
if (ctrlDown) { //if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells)
var sel = this.instance.getSelected();
this.instance.populateFromArray(sel[0], sel[1], val, sel[2], sel[3], 'edit');
}
else {
this.instance.populateFromArray(this.row, this.col, val, null, null, 'edit');
}
};
BaseEditor.prototype.beginEditing = function(initialValue){
if (this.state != Handsontable.EditorState.VIRGIN) {
return;
}
this.instance.view.scrollViewport(new WalkontableCellCoords(this.row, this.col));
this.instance.view.render();
this.state = Handsontable.EditorState.EDITING;
initialValue = typeof initialValue == 'string' ? initialValue : this.originalValue;
this.setValue(Handsontable.helper.stringify(initialValue));
this.open();
this._opened = true;
this.focus();
this.instance.view.render(); //only rerender the selections (FillHandle should disappear when beginediting is triggered)
};
BaseEditor.prototype.finishEditing = function (restoreOriginalValue, ctrlDown, callback) {
if (callback) {
var previousCloseCallback = this._closeCallback;
this._closeCallback = function (result) {
if(previousCloseCallback){
previousCloseCallback(result);
}
callback(result);
};
}
if (this.isWaiting()) {
return;
}
if (this.state == Handsontable.EditorState.VIRGIN) {
var that = this;
setTimeout(function () {
that._fireCallbacks(true);
});
return;
}
if (this.state == Handsontable.EditorState.EDITING) {
if (restoreOriginalValue) {
this.cancelChanges();
return;
}
var val = [
[String.prototype.trim.call(this.getValue())] //String.prototype.trim is defined in Walkontable polyfill.js
];
this.state = Handsontable.EditorState.WAITING;
this.saveValue(val, ctrlDown);
if(this.instance.getCellValidator(this.cellProperties)){
var that = this;
this.instance.addHookOnce('afterValidate', function (result) {
that.state = Handsontable.EditorState.FINISHED;
that.discardEditor(result);
});
} else {
this.state = Handsontable.EditorState.FINISHED;
this.discardEditor(true);
}
}
};
BaseEditor.prototype.cancelChanges = function () {
this.state = Handsontable.EditorState.FINISHED;
this.discardEditor();
};
BaseEditor.prototype.discardEditor = function (result) {
if (this.state !== Handsontable.EditorState.FINISHED) {
return;
}
if (result === false && this.cellProperties.allowInvalid !== true) { //validator was defined and failed
this.instance.selectCell(this.row, this.col);
this.focus();
this.state = Handsontable.EditorState.EDITING;
this._fireCallbacks(false);
}
else {
this.close();
this._opened = false;
this.state = Handsontable.EditorState.VIRGIN;
this._fireCallbacks(true);
}
};
BaseEditor.prototype.isOpened = function(){
return this._opened;
};
BaseEditor.prototype.isWaiting = function () {
return this.state === Handsontable.EditorState.WAITING;
};
Handsontable.editors.BaseEditor = BaseEditor;
})(Handsontable);
(function(Handsontable){
var TextEditor = Handsontable.editors.BaseEditor.prototype.extend();
TextEditor.prototype.init = function(){
this.createElements();
this.bindEvents();
};
TextEditor.prototype.getValue = function(){
return this.TEXTAREA.value
};
TextEditor.prototype.setValue = function(newValue){
this.TEXTAREA.value = newValue;
};
var onBeforeKeyDown = function onBeforeKeyDown(event){
var instance = this;
var that = instance.getActiveEditor();
var keyCodes = Handsontable.helper.keyCode;
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
//Process only events that have been fired in the editor
if (event.target !== that.TEXTAREA || event.isImmediatePropagationStopped()){
return;
}
if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) {
//when CTRL or its equivalent is pressed and cell is edited, don't prepare selectable text in textarea
event.stopImmediatePropagation();
return;
}
switch (event.keyCode) {
case keyCodes.ARROW_RIGHT:
if (Handsontable.Dom.getCaretPosition(that.TEXTAREA) !== that.TEXTAREA.value.length) {
event.stopImmediatePropagation();
}
break;
case keyCodes.ARROW_LEFT: /* arrow left */
if (Handsontable.Dom.getCaretPosition(that.TEXTAREA) !== 0) {
event.stopImmediatePropagation();
}
break;
case keyCodes.ENTER:
var selected = that.instance.getSelected();
var isMultipleSelection = !(selected[0] === selected[2] && selected[1] === selected[3]);
if ((ctrlDown && !isMultipleSelection) || event.altKey) { //if ctrl+enter or alt+enter, add new line
if(that.isOpened()){
that.setValue(that.getValue() + '\n');
that.focus();
} else {
that.beginEditing(that.originalValue + '\n')
}
event.stopImmediatePropagation();
}
event.preventDefault(); //don't add newline to field
break;
case keyCodes.A:
case keyCodes.X:
case keyCodes.C:
case keyCodes.V:
if(ctrlDown){
event.stopImmediatePropagation(); //CTRL+A, CTRL+C, CTRL+V, CTRL+X should only work locally when cell is edited (not in table context)
break;
}
case keyCodes.BACKSPACE:
case keyCodes.DELETE:
case keyCodes.HOME:
case keyCodes.END:
event.stopImmediatePropagation(); //backspace, delete, home, end should only work locally when cell is edited (not in table context)
break;
}
};
TextEditor.prototype.open = function(){
this.refreshDimensions(); //need it instantly, to prevent https://github.com/handsontable/jquery-handsontable/issues/348
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
};
TextEditor.prototype.close = function(){
this.textareaParentStyle.display = 'none';
if (document.activeElement === this.TEXTAREA) {
this.instance.listen(); //don't refocus the table if user focused some cell outside of HT on purpose
}
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
TextEditor.prototype.focus = function(){
this.TEXTAREA.focus();
Handsontable.Dom.setCaretPosition(this.TEXTAREA, this.TEXTAREA.value.length);
};
TextEditor.prototype.createElements = function () {
this.$body = $(document.body);
this.TEXTAREA = document.createElement('TEXTAREA');
this.$textarea = $(this.TEXTAREA);
Handsontable.Dom.addClass(this.TEXTAREA, 'handsontableInput');
this.textareaStyle = this.TEXTAREA.style;
this.textareaStyle.width = 0;
this.textareaStyle.height = 0;
this.TEXTAREA_PARENT = document.createElement('DIV');
Handsontable.Dom.addClass(this.TEXTAREA_PARENT, 'handsontableInputHolder');
this.textareaParentStyle = this.TEXTAREA_PARENT.style;
this.textareaParentStyle.top = 0;
this.textareaParentStyle.left = 0;
this.textareaParentStyle.display = 'none';
this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);
this.instance.rootElement[0].appendChild(this.TEXTAREA_PARENT);
var that = this;
Handsontable.hooks.add('afterRender', function () {
that.instance._registerTimeout('refresh_editor_dimensions', function () {
that.refreshDimensions();
}, 0);
});
};
TextEditor.prototype.refreshDimensions = function () {
if (this.state !== Handsontable.EditorState.EDITING) {
return;
}
///start prepare textarea position
this.TD = this.instance.getCell(this.row, this.col);
if (!this.TD) {
//TD is outside of the viewport. Otherwise throws exception when scrolling the table while a cell is edited
return;
}
var $td = $(this.TD); //because old td may have been scrolled out with scrollViewport
var currentOffset = Handsontable.Dom.offset(this.TD);
var containerOffset = Handsontable.Dom.offset(this.instance.rootElement[0]);
var editTop = currentOffset.top - containerOffset.top - 1;
var editLeft = currentOffset.left - containerOffset.left - 1;
var settings = this.instance.getSettings();
var rowHeadersCount = settings.rowHeaders === false ? 0 : 1;
var colHeadersCount = settings.colHeaders === false ? 0 : 1;
if (editTop < 0) {
editTop = 0;
}
if (editLeft < 0) {
editLeft = 0;
}
if (rowHeadersCount > 0 && parseInt($td.css('border-top-width'), 10) > 0) {
editTop += 1;
}
if (colHeadersCount > 0 && parseInt($td.css('border-left-width'), 10) > 0) {
editLeft += 1;
}
this.textareaParentStyle.top = editTop + 'px';
this.textareaParentStyle.left = editLeft + 'px';
///end prepare textarea position
var cellTopOffset = this.TD.offsetTop,
cellLeftOffset = this.TD.offsetLeft - this.instance.view.wt.wtScrollbars.horizontal.getScrollPosition();
var width = $td.width()
, maxWidth = this.instance.view.maximumVisibleElementWidth(cellLeftOffset) - 10 //10 is TEXTAREAs border and padding
, height = $td.outerHeight() - 4
, maxHeight = this.instance.view.maximumVisibleElementHeight(cellTopOffset)-2; //10 is TEXTAREAs border and padding
if (parseInt($td.css('border-top-width'), 10) > 0) {
height -= 1;
}
if (parseInt($td.css('border-left-width'), 10) > 0) {
if (rowHeadersCount > 0) {
width -= 1;
}
}
//in future may change to pure JS http://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize
this.$textarea.autoResize({
minHeight: Math.min(height, maxHeight),
maxHeight: maxHeight, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
minWidth: Math.min(width, maxWidth),
maxWidth: maxWidth, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
animate: false,
extraSpace: 0
});
this.textareaParentStyle.display = 'block';
};
TextEditor.prototype.bindEvents = function () {
this.$textarea.on('cut.editor', function (event) {
event.stopPropagation();
});
this.$textarea.on('paste.editor', function (event) {
event.stopPropagation();
});
};
Handsontable.editors.TextEditor = TextEditor;
Handsontable.editors.registerEditor('text', Handsontable.editors.TextEditor);
})(Handsontable);
(function(Handsontable){
//Blank editor, because all the work is done by renderer
var CheckboxEditor = Handsontable.editors.BaseEditor.prototype.extend();
CheckboxEditor.prototype.beginEditing = function () {
var checkbox = this.TD.querySelector('input[type="checkbox"]');
if (checkbox) {
$(checkbox).trigger('click');
}
};
CheckboxEditor.prototype.finishEditing = function () {};
CheckboxEditor.prototype.init = function () {};
CheckboxEditor.prototype.open = function () {};
CheckboxEditor.prototype.close = function () {};
CheckboxEditor.prototype.getValue = function () {};
CheckboxEditor.prototype.setValue = function () {};
CheckboxEditor.prototype.focus = function () {};
Handsontable.editors.CheckboxEditor = CheckboxEditor;
Handsontable.editors.registerEditor('checkbox', CheckboxEditor);
})(Handsontable);
(function (Handsontable) {
var DateEditor = Handsontable.editors.TextEditor.prototype.extend();
DateEditor.prototype.init = function () {
if (!$.datepicker) {
throw new Error("jQuery UI Datepicker dependency not found. Did you forget to include jquery-ui.custom.js or its substitute?");
}
Handsontable.editors.TextEditor.prototype.init.apply(this, arguments);
this.isCellEdited = false;
var that = this;
this.instance.addHook('afterDestroy', function () {
that.destroyElements();
})
};
DateEditor.prototype.createElements = function () {
Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);
this.datePicker = document.createElement('DIV');
Handsontable.Dom.addClass(this.datePicker, 'htDatepickerHolder');
this.datePickerStyle = this.datePicker.style;
this.datePickerStyle.position = 'absolute';
this.datePickerStyle.top = 0;
this.datePickerStyle.left = 0;
this.datePickerStyle.zIndex = 99;
document.body.appendChild(this.datePicker);
this.$datePicker = $(this.datePicker);
var that = this;
var defaultOptions = {
dateFormat: "yy-mm-dd",
showButtonPanel: true,
changeMonth: true,
changeYear: true,
onSelect: function (dateStr) {
that.setValue(dateStr);
that.finishEditing(false);
}
};
this.$datePicker.datepicker(defaultOptions);
/**
* Prevent recognizing clicking on jQuery Datepicker as clicking outside of table
*/
this.$datePicker.on('mousedown', function (event) {
event.stopPropagation();
});
this.hideDatepicker();
};
DateEditor.prototype.destroyElements = function () {
this.$datePicker.datepicker('destroy');
this.$datePicker.remove();
};
DateEditor.prototype.open = function () {
Handsontable.editors.TextEditor.prototype.open.call(this);
this.showDatepicker();
};
DateEditor.prototype.finishEditing = function (isCancelled, ctrlDown) {
this.hideDatepicker();
Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments);
};
DateEditor.prototype.showDatepicker = function () {
var $td = $(this.TD);
var offset = $td.offset();
this.datePickerStyle.top = (offset.top + $td.height()) + 'px';
this.datePickerStyle.left = offset.left + 'px';
var dateOptions = {
defaultDate: this.originalValue || void 0
};
$.extend(dateOptions, this.cellProperties);
this.$datePicker.datepicker("option", dateOptions);
if (this.originalValue) {
this.$datePicker.datepicker("setDate", this.originalValue);
}
this.datePickerStyle.display = 'block';
};
DateEditor.prototype.hideDatepicker = function () {
this.datePickerStyle.display = 'none';
};
Handsontable.editors.DateEditor = DateEditor;
Handsontable.editors.registerEditor('date', DateEditor);
})(Handsontable);
/**
* This is inception. Using Handsontable as Handsontable editor
*/
(function (Handsontable) {
"use strict";
var HandsontableEditor = Handsontable.editors.TextEditor.prototype.extend();
HandsontableEditor.prototype.createElements = function () {
Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);
var DIV = document.createElement('DIV');
DIV.className = 'handsontableEditor';
this.TEXTAREA_PARENT.appendChild(DIV);
this.$htContainer = $(DIV);
this.$htContainer.handsontable();
};
HandsontableEditor.prototype.prepare = function (td, row, col, prop, value, cellProperties) {
Handsontable.editors.TextEditor.prototype.prepare.apply(this, arguments);
var parent = this;
var options = {
startRows: 0,
startCols: 0,
minRows: 0,
minCols: 0,
className: 'listbox',
copyPaste: false,
cells: function () {
return {
readOnly: true
}
},
fillHandle: false,
afterOnCellMouseDown: function () {
var value = this.getValue();
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
parent.setValue(value);
}
parent.instance.destroyEditor();
},
beforeOnKeyDown: function (event) {
var instance = this;
switch (event.keyCode) {
case Handsontable.helper.keyCode.ESCAPE:
parent.instance.destroyEditor(true);
event.stopImmediatePropagation();
event.preventDefault();
break;
case Handsontable.helper.keyCode.ENTER: //enter
var sel = instance.getSelected();
var value = this.getDataAtCell(sel[0], sel[1]);
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
parent.setValue(value);
}
parent.instance.destroyEditor();
break;
case Handsontable.helper.keyCode.ARROW_UP:
if (instance.getSelected() && instance.getSelected()[0] == 0 && !parent.cellProperties.strict){
instance.deselectCell();
parent.instance.listen();
parent.focus();
event.preventDefault();
event.stopImmediatePropagation();
}
break;
}
}
};
if (this.cellProperties.handsontable) {
options = $.extend(options, cellProperties.handsontable);
}
this.$htContainer.handsontable('destroy');
this.$htContainer.handsontable(options);
};
var onBeforeKeyDown = function (event) {
if (event.isImmediatePropagationStopped()) {
return;
}
var editor = this.getActiveEditor();
var innerHOT = editor.$htContainer.handsontable('getInstance');
if (event.keyCode == Handsontable.helper.keyCode.ARROW_DOWN) {
if (!innerHOT.getSelected()){
innerHOT.selectCell(0, 0);
} else {
var selectedRow = innerHOT.getSelected()[0];
var rowToSelect = selectedRow < innerHOT.countRows() - 1 ? selectedRow + 1 : selectedRow;
innerHOT.selectCell(rowToSelect, 0);
}
event.preventDefault();
event.stopImmediatePropagation();
}
};
HandsontableEditor.prototype.open = function () {
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
Handsontable.editors.TextEditor.prototype.open.apply(this, arguments);
this.$htContainer.handsontable('render');
if (this.cellProperties.strict) {
this.$htContainer.handsontable('selectCell', 0, 0);
this.$textarea[0].style.visibility = 'hidden';
} else {
this.$htContainer.handsontable('deselectCell');
this.$textarea[0].style.visibility = 'visible';
}
Handsontable.Dom.setCaretPosition(this.$textarea[0], 0, this.$textarea[0].value.length);
};
HandsontableEditor.prototype.close = function () {
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
this.instance.listen();
Handsontable.editors.TextEditor.prototype.close.apply(this, arguments);
};
HandsontableEditor.prototype.focus = function () {
this.instance.listen();
Handsontable.editors.TextEditor.prototype.focus.apply(this, arguments);
};
HandsontableEditor.prototype.beginEditing = function (initialValue) {
var onBeginEditing = this.instance.getSettings().onBeginEditing;
if (onBeginEditing && onBeginEditing() === false) {
return;
}
Handsontable.editors.TextEditor.prototype.beginEditing.apply(this, arguments);
};
HandsontableEditor.prototype.finishEditing = function (isCancelled, ctrlDown) {
if (this.$htContainer.handsontable('isListening')) { //if focus is still in the HOT editor
this.instance.listen(); //return the focus to the parent HOT instance
}
if (this.$htContainer.handsontable('getSelected')) {
var value = this.$htContainer.handsontable('getInstance').getValue();
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
this.setValue(value);
}
}
return Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments);
};
Handsontable.editors.HandsontableEditor = HandsontableEditor;
Handsontable.editors.registerEditor('handsontable', HandsontableEditor);
})(Handsontable);
(function (Handsontable) {
var AutocompleteEditor = Handsontable.editors.HandsontableEditor.prototype.extend();
AutocompleteEditor.prototype.init = function () {
Handsontable.editors.HandsontableEditor.prototype.init.apply(this, arguments);
this.$htContainer.handsontable('updateSettings', {height: this.getDropdownHeight()});
this.query = null;
this.choices = [];
};
AutocompleteEditor.prototype.createElements = function(){
Handsontable.editors.HandsontableEditor.prototype.createElements.apply(this, arguments);
this.$htContainer.addClass('autocompleteEditor');
};
AutocompleteEditor.prototype.bindEvents = function(){
var that = this;
this.$textarea.on('keydown.autocompleteEditor', function(event){
if(!Handsontable.helper.isMetaKey(event.keyCode) || [Handsontable.helper.keyCode.BACKSPACE, Handsontable.helper.keyCode.DELETE].indexOf(event.keyCode) != -1){
setTimeout(function () {
that.queryChoices(that.$textarea.val());
});
} else if (event.keyCode == Handsontable.helper.keyCode.ENTER && that.cellProperties.strict !== true){
that.$htContainer.handsontable('deselectCell');
}
});
this.$htContainer.on('mouseleave', function () {
if(that.cellProperties.strict === true){
that.highlightBestMatchingChoice();
}
});
this.$htContainer.on('mouseenter', function () {
that.$htContainer.handsontable('deselectCell');
});
Handsontable.editors.HandsontableEditor.prototype.bindEvents.apply(this, arguments);
};
var onBeforeKeyDownInner;
AutocompleteEditor.prototype.open = function () {
Handsontable.editors.HandsontableEditor.prototype.open.apply(this, arguments);
this.$textarea[0].style.visibility = 'visible';
this.focus();
var choicesListHot = this.$htContainer.handsontable('getInstance');
var that = this;
choicesListHot.updateSettings({
'colWidths': [Handsontable.Dom.outerWidth(this.TEXTAREA) - 2],
afterRenderer: function (TD, row, col, prop, value) {
var caseSensitive = this.getCellMeta(row, col).filteringCaseSensitive === true;
var indexOfMatch = caseSensitive ? value.indexOf(this.query) : value.toLowerCase().indexOf(that.query.toLowerCase());
if(indexOfMatch != -1){
var match = value.substr(indexOfMatch, that.query.length);
TD.innerHTML = value.replace(match, '<strong>' + match + '</strong>');
}
}
});
onBeforeKeyDownInner = function (event) {
var instance = this;
if (event.keyCode == Handsontable.helper.keyCode.ARROW_UP){
if (instance.getSelected() && instance.getSelected()[0] == 0){
if(!parent.cellProperties.strict){
instance.deselectCell();
}
parent.instance.listen();
parent.focus();
event.preventDefault();
event.stopImmediatePropagation();
}
}
};
choicesListHot.addHook('beforeKeyDown', onBeforeKeyDownInner);
this.queryChoices(this.TEXTAREA.value);
};
AutocompleteEditor.prototype.close = function () {
this.$htContainer.handsontable('getInstance').removeHook('beforeKeyDown', onBeforeKeyDownInner);
Handsontable.editors.HandsontableEditor.prototype.close.apply(this, arguments);
};
AutocompleteEditor.prototype.queryChoices = function(query){
this.query = query;
if (typeof this.cellProperties.source == 'function'){
var that = this;
this.cellProperties.source(query, function(choices){
that.updateChoicesList(choices)
});
} else if (Handsontable.helper.isArray(this.cellProperties.source)) {
var choices;
if(!query || this.cellProperties.filter === false){
choices = this.cellProperties.source;
} else {
var filteringCaseSensitive = this.cellProperties.filteringCaseSensitive === true;
var lowerCaseQuery = query.toLowerCase();
choices = this.cellProperties.source.filter(function(choice){
if (filteringCaseSensitive) {
return choice.indexOf(query) != -1;
} else {
return choice.toLowerCase().indexOf(lowerCaseQuery) != -1;
}
});
}
this.updateChoicesList(choices)
} else {
this.updateChoicesList([]);
}
};
AutocompleteEditor.prototype.updateChoicesList = function (choices) {
this.choices = choices;
this.$htContainer.handsontable('loadData', Handsontable.helper.pivot([choices]));
if(this.cellProperties.strict === true){
this.highlightBestMatchingChoice();
}
this.focus();
};
AutocompleteEditor.prototype.highlightBestMatchingChoice = function () {
var bestMatchingChoice = this.findBestMatchingChoice();
if ( typeof bestMatchingChoice == 'undefined' && this.cellProperties.allowInvalid === false){
bestMatchingChoice = 0;
}
if(typeof bestMatchingChoice == 'undefined'){
this.$htContainer.handsontable('deselectCell');
} else {
this.$htContainer.handsontable('selectCell', bestMatchingChoice, 0);
}
};
AutocompleteEditor.prototype.findBestMatchingChoice = function(){
var bestMatch = {};
var valueLength = this.getValue().length;
var currentItem;
var indexOfValue;
var charsLeft;
for(var i = 0, len = this.choices.length; i < len; i++){
currentItem = this.choices[i];
if(valueLength > 0){
indexOfValue = currentItem.indexOf(this.getValue())
} else {
indexOfValue = currentItem === this.getValue() ? 0 : -1;
}
if(indexOfValue == -1) continue;
charsLeft = currentItem.length - indexOfValue - valueLength;
if( typeof bestMatch.indexOfValue == 'undefined'
|| bestMatch.indexOfValue > indexOfValue
|| ( bestMatch.indexOfValue == indexOfValue && bestMatch.charsLeft > charsLeft ) ){
bestMatch.indexOfValue = indexOfValue;
bestMatch.charsLeft = charsLeft;
bestMatch.index = i;
}
}
return bestMatch.index;
};
AutocompleteEditor.prototype.getDropdownHeight = function(){
//return 10 * this.$htContainer.handsontable('getInstance').getRowHeight(0);
//sorry, we can't measure row height before it was rendered. Let's use fixed height for now
return 230;
};
Handsontable.editors.AutocompleteEditor = AutocompleteEditor;
Handsontable.editors.registerEditor('autocomplete', AutocompleteEditor);
})(Handsontable);
(function(Handsontable){
var PasswordEditor = Handsontable.editors.TextEditor.prototype.extend();
PasswordEditor.prototype.createElements = function () {
Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);
this.TEXTAREA = document.createElement('input');
this.TEXTAREA.setAttribute('type', 'password');
this.TEXTAREA.className = 'handsontableInput';
this.textareaStyle = this.TEXTAREA.style;
this.textareaStyle.width = 0;
this.textareaStyle.height = 0;
this.$textarea = $(this.TEXTAREA);
Handsontable.Dom.empty(this.TEXTAREA_PARENT);
this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);
};
Handsontable.editors.PasswordEditor = PasswordEditor;
Handsontable.editors.registerEditor('password', PasswordEditor);
})(Handsontable);
(function (Handsontable) {
var SelectEditor = Handsontable.editors.BaseEditor.prototype.extend();
SelectEditor.prototype.init = function(){
this.select = document.createElement('SELECT');
Handsontable.Dom.addClass(this.select, 'htSelectEditor');
this.select.style.display = 'none';
this.instance.rootElement[0].appendChild(this.select);
};
SelectEditor.prototype.prepare = function(){
Handsontable.editors.BaseEditor.prototype.prepare.apply(this, arguments);
var selectOptions = this.cellProperties.selectOptions;
var options;
if (typeof selectOptions == 'function'){
options = this.prepareOptions(selectOptions(this.row, this.col, this.prop))
} else {
options = this.prepareOptions(selectOptions);
}
Handsontable.Dom.empty(this.select);
for (var option in options){
if (options.hasOwnProperty(option)){
var optionElement = document.createElement('OPTION');
optionElement.value = option;
Handsontable.Dom.fastInnerHTML(optionElement, options[option]);
this.select.appendChild(optionElement);
}
}
};
SelectEditor.prototype.prepareOptions = function(optionsToPrepare){
var preparedOptions = {};
if (Handsontable.helper.isArray(optionsToPrepare)){
for(var i = 0, len = optionsToPrepare.length; i < len; i++){
preparedOptions[optionsToPrepare[i]] = optionsToPrepare[i];
}
}
else if (typeof optionsToPrepare == 'object') {
preparedOptions = optionsToPrepare;
}
return preparedOptions;
};
SelectEditor.prototype.getValue = function () {
return this.select.value;
};
SelectEditor.prototype.setValue = function (value) {
this.select.value = value;
};
var onBeforeKeyDown = function (event) {
var instance = this;
var editor = instance.getActiveEditor();
switch (event.keyCode){
case Handsontable.helper.keyCode.ARROW_UP:
var previousOption = editor.select.find('option:selected').prev();
if (previousOption.length == 1){
previousOption.prop('selected', true);
}
event.stopImmediatePropagation();
event.preventDefault();
break;
case Handsontable.helper.keyCode.ARROW_DOWN:
var nextOption = editor.select.find('option:selected').next();
if (nextOption.length == 1){
nextOption.prop('selected', true);
}
event.stopImmediatePropagation();
event.preventDefault();
break;
}
};
SelectEditor.prototype.open = function () {
var width = Handsontable.Dom.outerWidth(this.TD); //important - group layout reads together for better performance
var height = Handsontable.Dom.outerHeight(this.TD);
var rootOffset = Handsontable.Dom.offset(this.instance.rootElement[0]);
var tdOffset = Handsontable.Dom.offset(this.TD);
this.select.style.height = height + 'px';
this.select.style.minWidth = width + 'px';
this.select.style.top = tdOffset.top - rootOffset.top + 'px';
this.select.style.left = tdOffset.left - rootOffset.left - 2 + 'px'; //2 is cell border
this.select.style.display = '';
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
};
SelectEditor.prototype.close = function () {
this.select.style.display = 'none';
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
SelectEditor.prototype.focus = function () {
this.select.focus();
};
Handsontable.editors.SelectEditor = SelectEditor;
Handsontable.editors.registerEditor('select', SelectEditor);
})(Handsontable);
(function (Handsontable) {
var DropdownEditor = Handsontable.editors.AutocompleteEditor.prototype.extend();
DropdownEditor.prototype.prepare = function () {
Handsontable.editors.AutocompleteEditor.prototype.prepare.apply(this, arguments);
this.cellProperties.filter = false;
this.cellProperties.strict = true;
};
Handsontable.editors.DropdownEditor = DropdownEditor;
Handsontable.editors.registerEditor('dropdown', DropdownEditor);
})(Handsontable);
/**
* Numeric cell validator
* @param {*} value - Value of edited cell
* @param {*} callback - Callback called with validation result
*/
Handsontable.NumericValidator = function (value, callback) {
if (value === null) {
value = '';
}
callback(/^-?\d*(\.|\,)?\d*$/.test(value));
};
/**
* Function responsible for validation of autocomplete value
* @param {*} value - Value of edited cell
* @param {*} calback - Callback called with validation result
*/
var process = function (value, callback) {
var originalVal = value;
var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null;
return function (source) {
var found = false;
for (var s = 0, slen = source.length; s < slen; s++) {
if (originalVal === source[s]) {
found = true; //perfect match
break;
}
else if (lowercaseVal === source[s].toLowerCase()) {
// changes[i][3] = source[s]; //good match, fix the case << TODO?
found = true;
break;
}
}
callback(found);
}
};
/**
* Autocomplete cell validator
* @param {*} value - Value of edited cell
* @param {*} calback - Callback called with validation result
*/
Handsontable.AutocompleteValidator = function (value, callback) {
if (this.strict && this.source) {
typeof this.source === 'function' ? this.source(value, process(value, callback)) : process(value, callback)(this.source);
} else {
callback(true);
}
};
/**
* Cell type is just a shortcut for setting bunch of cellProperties (used in getCellMeta)
*/
Handsontable.AutocompleteCell = {
editor: Handsontable.editors.AutocompleteEditor,
renderer: Handsontable.renderers.AutocompleteRenderer,
validator: Handsontable.AutocompleteValidator
};
Handsontable.CheckboxCell = {
editor: Handsontable.editors.CheckboxEditor,
renderer: Handsontable.renderers.CheckboxRenderer
};
Handsontable.TextCell = {
editor: Handsontable.editors.TextEditor,
renderer: Handsontable.renderers.TextRenderer
};
Handsontable.NumericCell = {
editor: Handsontable.editors.TextEditor,
renderer: Handsontable.renderers.NumericRenderer,
validator: Handsontable.NumericValidator,
dataType: 'number'
};
Handsontable.DateCell = {
editor: Handsontable.editors.DateEditor,
renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell
};
Handsontable.HandsontableCell = {
editor: Handsontable.editors.HandsontableEditor,
renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell
};
Handsontable.PasswordCell = {
editor: Handsontable.editors.PasswordEditor,
renderer: Handsontable.renderers.PasswordRenderer,
copyable: false
};
Handsontable.DropdownCell = {
editor: Handsontable.editors.DropdownEditor,
renderer: Handsontable.renderers.AutocompleteRenderer, //displays small gray arrow on right side of the cell
validator: Handsontable.AutocompleteValidator
};
//here setup the friendly aliases that are used by cellProperties.type
Handsontable.cellTypes = {
text: Handsontable.TextCell,
date: Handsontable.DateCell,
numeric: Handsontable.NumericCell,
checkbox: Handsontable.CheckboxCell,
autocomplete: Handsontable.AutocompleteCell,
handsontable: Handsontable.HandsontableCell,
password: Handsontable.PasswordCell,
dropdown: Handsontable.DropdownCell
};
//here setup the friendly aliases that are used by cellProperties.renderer and cellProperties.editor
Handsontable.cellLookup = {
validator: {
numeric: Handsontable.NumericValidator,
autocomplete: Handsontable.AutocompleteValidator
}
};
/*
* jQuery.fn.autoResize 1.1+
* --
* https://github.com/warpech/jQuery.fn.autoResize
*
* This fork differs from others in a way that it autoresizes textarea in 2-dimensions (horizontally and vertically).
* It was originally forked from alexbardas's repo but maybe should be merged with dpashkevich's repo in future.
*
* originally forked from:
* https://github.com/jamespadolsey/jQuery.fn.autoResize
* which is now located here:
* https://github.com/alexbardas/jQuery.fn.autoResize
* though the mostly maintained for is here:
* https://github.com/dpashkevich/jQuery.fn.autoResize/network
*
* --
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details. */
(function($){
autoResize.defaults = {
onResize: function(){},
animate: {
duration: 200,
complete: function(){}
},
extraSpace: 50,
minHeight: 'original',
maxHeight: 500,
minWidth: 'original',
maxWidth: 500
};
autoResize.cloneCSSProperties = [
'lineHeight', 'textDecoration', 'letterSpacing',
'fontSize', 'fontFamily', 'fontStyle', 'fontWeight',
'textTransform', 'textAlign', 'direction', 'wordSpacing', 'fontSizeAdjust',
'padding'
];
autoResize.cloneCSSValues = {
position: 'absolute',
top: -9999,
left: -9999,
opacity: 0,
overflow: 'hidden',
overflowX: 'hidden',
overflowY: 'hidden',
border: '1px solid black',
padding: '0.49em' //this must be about the width of caps W character
};
autoResize.resizableFilterSelector = 'textarea,input:not(input[type]),input[type=text],input[type=password]';
autoResize.AutoResizer = AutoResizer;
$.fn.autoResize = autoResize;
function autoResize(config) {
this.filter(autoResize.resizableFilterSelector).each(function(){
new AutoResizer( $(this), config );
});
return this;
}
function AutoResizer(el, config) {
if(this.clones) return;
this.config = $.extend({}, autoResize.defaults, config);
this.el = el;
this.nodeName = el[0].nodeName.toLowerCase();
this.previousScrollTop = null;
if (config.maxWidth === 'original') config.maxWidth = el.width();
if (config.minWidth === 'original') config.minWidth = el.width();
if (config.maxHeight === 'original') config.maxHeight = el.height();
if (config.minHeight === 'original') config.minHeight = el.height();
if (this.nodeName === 'textarea') {
el.css({
resize: 'none',
overflowY: 'none'
});
}
el.data('AutoResizer', this);
this.createClone();
this.injectClone();
this.bind();
}
AutoResizer.prototype = {
bind: function() {
var check = $.proxy(function(){
this.check();
return true;
}, this);
this.unbind();
this.el
.bind('keyup.autoResize', check)
//.bind('keydown.autoResize', check)
.bind('change.autoResize', check);
this.check(null, true);
},
unbind: function() {
this.el.unbind('.autoResize');
},
createClone: function() {
var el = this.el,
self = this,
config = this.config;
this.clones = $();
if (config.minHeight !== 'original' || config.maxHeight !== 'original') {
this.hClone = el.clone().height('auto');
this.clones = this.clones.add(this.hClone);
}
if (config.minWidth !== 'original' || config.maxWidth !== 'original') {
this.wClone = $('<div/>').width('auto').css({
whiteSpace: 'nowrap',
'float': 'left'
});
this.clones = this.clones.add(this.wClone);
}
$.each(autoResize.cloneCSSProperties, function(i, p){
self.clones.css(p, el.css(p));
});
this.clones
.removeAttr('name')
.removeAttr('id')
.attr('tabIndex', -1)
.css(autoResize.cloneCSSValues)
.css('overflowY', 'scroll');
},
check: function(e, immediate) {
var config = this.config,
wClone = this.wClone,
hClone = this.hClone,
el = this.el,
value = el.val();
if (wClone) {
wClone.text(value);
// Calculate new width + whether to change
var cloneWidth = wClone.outerWidth(),
newWidth = (cloneWidth + config.extraSpace) >= config.minWidth ?
cloneWidth + config.extraSpace : config.minWidth,
currentWidth = el.width();
newWidth = Math.min(newWidth, config.maxWidth);
if (
(newWidth < currentWidth && newWidth >= config.minWidth) ||
(newWidth >= config.minWidth && newWidth <= config.maxWidth)
) {
config.onResize.call(el);
el.scrollLeft(0);
config.animate && !immediate ?
el.stop(1,1).animate({
width: newWidth
}, config.animate)
: el.width(newWidth);
}
}
if (hClone) {
if (newWidth) {
hClone.width(newWidth);
}
hClone.height(0).val(value).scrollTop(10000);
var scrollTop = hClone[0].scrollTop + config.extraSpace;
// Don't do anything if scrollTop hasen't changed:
if (this.previousScrollTop === scrollTop) {
return;
}
this.previousScrollTop = scrollTop;
if (scrollTop >= config.maxHeight) {
scrollTop = config.maxHeight;
}
if (scrollTop < config.minHeight) {
scrollTop = config.minHeight;
}
if(scrollTop == config.maxHeight && newWidth == config.maxWidth) {
el.css('overflowY', 'scroll');
}
else {
el.css('overflowY', 'hidden');
}
config.onResize.call(el);
// Either animate or directly apply height:
config.animate && !immediate ?
el.stop(1,1).animate({
height: scrollTop
}, config.animate)
: el.height(scrollTop);
}
},
destroy: function() {
this.unbind();
this.el.removeData('AutoResizer');
this.clones.remove();
delete this.el;
delete this.hClone;
delete this.wClone;
delete this.clones;
},
injectClone: function() {
(
autoResize.cloneContainer ||
(autoResize.cloneContainer = $('<arclones/>').appendTo('body'))
).empty().append(this.clones); //this should be refactored so that a node is never cloned more than once
}
};
})(jQuery);
/**
* SheetClip - Spreadsheet Clipboard Parser
* version 0.2
*
* This tiny library transforms JavaScript arrays to strings that are pasteable by LibreOffice, OpenOffice,
* Google Docs and Microsoft Excel.
*
* Copyright 2012, Marcin Warpechowski
* Licensed under the MIT license.
* http://github.com/warpech/sheetclip/
*/
/*jslint white: true*/
(function (global) {
"use strict";
function countQuotes(str) {
return str.split('"').length - 1;
}
global.SheetClip = {
parse: function (str) {
var r, rlen, rows, arr = [], a = 0, c, clen, multiline, last;
rows = str.split('\n');
if (rows.length > 1 && rows[rows.length - 1] === '') {
rows.pop();
}
for (r = 0, rlen = rows.length; r < rlen; r += 1) {
rows[r] = rows[r].split('\t');
for (c = 0, clen = rows[r].length; c < clen; c += 1) {
if (!arr[a]) {
arr[a] = [];
}
if (multiline && c === 0) {
last = arr[a].length - 1;
arr[a][last] = arr[a][last] + '\n' + rows[r][0];
if (multiline && (countQuotes(rows[r][0]) & 1)) { //& 1 is a bitwise way of performing mod 2
multiline = false;
arr[a][last] = arr[a][last].substring(0, arr[a][last].length - 1).replace(/""/g, '"');
}
}
else {
if (c === clen - 1 && rows[r][c].indexOf('"') === 0) {
arr[a].push(rows[r][c].substring(1).replace(/""/g, '"'));
multiline = true;
}
else {
arr[a].push(rows[r][c].replace(/""/g, '"'));
multiline = false;
}
}
}
if (!multiline) {
a += 1;
}
}
return arr;
},
stringify: function (arr) {
var r, rlen, c, clen, str = '', val;
for (r = 0, rlen = arr.length; r < rlen; r += 1) {
for (c = 0, clen = arr[r].length; c < clen; c += 1) {
if (c > 0) {
str += '\t';
}
val = arr[r][c];
if (typeof val === 'string') {
if (val.indexOf('\n') > -1) {
str += '"' + val.replace(/"/g, '""') + '"';
}
else {
str += val;
}
}
else if (val === null || val === void 0) { //void 0 resolves to undefined
str += '';
}
else {
str += val;
}
}
str += '\n';
}
return str;
}
};
}(window));
/**
* CopyPaste.js
* Creates a textarea that stays hidden on the page and gets focused when user presses CTRL while not having a form input focused
* In future we may implement a better driver when better APIs are available
* @constructor
*/
var CopyPaste = (function () {
var instance;
return {
getInstance: function () {
if (!instance) {
instance = new CopyPasteClass();
} else if (instance.hasBeenDestroyed()){
instance.init();
}
instance.refCounter++;
return instance;
}
};
})();
function CopyPasteClass() {
this.refCounter = 0;
this.init();
}
CopyPasteClass.prototype.init = function () {
var that = this
, style
, parent;
this.copyCallbacks = [];
this.cutCallbacks = [];
this.pasteCallbacks = [];
this.listenerElement = document.documentElement;
parent = document.body;
if (document.getElementById('CopyPasteDiv')) {
this.elDiv = document.getElementById('CopyPasteDiv');
this.elTextarea = this.elDiv.firstChild;
}
else {
this.elDiv = document.createElement('DIV');
this.elDiv.id = 'CopyPasteDiv';
style = this.elDiv.style;
style.position = 'fixed';
style.top = '-10000px';
style.left = '-10000px';
parent.appendChild(this.elDiv);
this.elTextarea = document.createElement('TEXTAREA');
this.elTextarea.className = 'copyPaste';
style = this.elTextarea.style;
style.width = '10000px';
style.height = '10000px';
style.overflow = 'hidden';
this.elDiv.appendChild(this.elTextarea);
if (typeof style.opacity !== 'undefined') {
style.opacity = 0;
}
else {
/*@cc_on @if (@_jscript)
if(typeof style.filter === 'string') {
style.filter = 'alpha(opacity=0)';
}
@end @*/
}
}
this.keydownListener = function (event) {
var isCtrlDown = false;
if (event.metaKey) { //mac
isCtrlDown = true;
}
else if (event.ctrlKey && navigator.userAgent.indexOf('Mac') === -1) { //pc
isCtrlDown = true;
}
if (isCtrlDown) {
if (document.activeElement !== that.elTextarea && (that.getSelectionText() != '' || ['INPUT', 'SELECT', 'TEXTAREA'].indexOf(document.activeElement.nodeName) != -1)) {
return; //this is needed by fragmentSelection in Handsontable. Ignore copypaste.js behavior if fragment of cell text is selected
}
that.selectNodeText(that.elTextarea);
setTimeout(function () {
that.selectNodeText(that.elTextarea);
}, 0);
}
/* 67 = c
* 86 = v
* 88 = x
*/
if (isCtrlDown && (event.keyCode === 67 || event.keyCode === 86 || event.keyCode === 88)) {
// that.selectNodeText(that.elTextarea);
if (event.keyCode === 88) { //works in all browsers, incl. Opera < 12.12
setTimeout(function () {
that.triggerCut(event);
}, 0);
}
else if (event.keyCode === 86) {
setTimeout(function () {
that.triggerPaste(event);
}, 0);
}
}
}
this._bindEvent(this.listenerElement, 'keydown', this.keydownListener);
};
//http://jsperf.com/textara-selection
//http://stackoverflow.com/questions/1502385/how-can-i-make-this-code-work-in-ie
CopyPasteClass.prototype.selectNodeText = function (el) {
el.select();
};
//http://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text
CopyPasteClass.prototype.getSelectionText = function () {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
};
CopyPasteClass.prototype.copyable = function (str) {
if (typeof str !== 'string' && str.toString === void 0) {
throw new Error('copyable requires string parameter');
}
this.elTextarea.value = str;
};
/*CopyPasteClass.prototype.onCopy = function (fn) {
this.copyCallbacks.push(fn);
};*/
CopyPasteClass.prototype.onCut = function (fn) {
this.cutCallbacks.push(fn);
};
CopyPasteClass.prototype.onPaste = function (fn) {
this.pasteCallbacks.push(fn);
};
CopyPasteClass.prototype.removeCallback = function (fn) {
var i, ilen;
for (i = 0, ilen = this.copyCallbacks.length; i < ilen; i++) {
if (this.copyCallbacks[i] === fn) {
this.copyCallbacks.splice(i, 1);
return true;
}
}
for (i = 0, ilen = this.cutCallbacks.length; i < ilen; i++) {
if (this.cutCallbacks[i] === fn) {
this.cutCallbacks.splice(i, 1);
return true;
}
}
for (i = 0, ilen = this.pasteCallbacks.length; i < ilen; i++) {
if (this.pasteCallbacks[i] === fn) {
this.pasteCallbacks.splice(i, 1);
return true;
}
}
return false;
};
CopyPasteClass.prototype.triggerCut = function (event) {
var that = this;
if (that.cutCallbacks) {
setTimeout(function () {
for (var i = 0, ilen = that.cutCallbacks.length; i < ilen; i++) {
that.cutCallbacks[i](event);
}
}, 50);
}
};
CopyPasteClass.prototype.triggerPaste = function (event, str) {
var that = this;
if (that.pasteCallbacks) {
setTimeout(function () {
var val = (str || that.elTextarea.value).replace(/\n$/, ''); //remove trailing newline
for (var i = 0, ilen = that.pasteCallbacks.length; i < ilen; i++) {
that.pasteCallbacks[i](val, event);
}
}, 50);
}
};
CopyPasteClass.prototype.destroy = function () {
if(!this.hasBeenDestroyed() && --this.refCounter == 0){
if (this.elDiv && this.elDiv.parentNode) {
this.elDiv.parentNode.removeChild(this.elDiv);
}
this._unbindEvent(this.listenerElement, 'keydown', this.keydownListener);
}
};
CopyPasteClass.prototype.hasBeenDestroyed = function () {
return !this.refCounter;
};
//old version used this:
// - http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/
// - http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization
//but that cannot work with jQuery.trigger
CopyPasteClass.prototype._bindEvent = (function () {
if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests)
return function (elem, type, cb) {
$(elem).on(type + '.copypaste', cb);
};
}
else {
return function (elem, type, cb) {
elem.addEventListener(type, cb, false); //sorry, IE8 will only work with jQuery
};
}
})();
CopyPasteClass.prototype._unbindEvent = (function () {
if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests)
return function (elem, type, cb) {
$(elem).off(type + '.copypaste', cb);
};
}
else {
return function (elem, type, cb) {
elem.removeEventListener(type, cb, false); //sorry, IE8 will only work with jQuery
};
}
})();
// json-patch-duplex.js 0.3.6
// (c) 2013 Joachim Wester
// MIT license
var jsonpatch;
(function (jsonpatch) {
var objOps = {
add: function (obj, key) {
obj[key] = this.value;
return true;
},
remove: function (obj, key) {
delete obj[key];
return true;
},
replace: function (obj, key) {
obj[key] = this.value;
return true;
},
move: function (obj, key, tree) {
var temp = { op: "_get", path: this.from };
apply(tree, [temp]);
apply(tree, [
{ op: "remove", path: this.from }
]);
apply(tree, [
{ op: "add", path: this.path, value: temp.value }
]);
return true;
},
copy: function (obj, key, tree) {
var temp = { op: "_get", path: this.from };
apply(tree, [temp]);
apply(tree, [
{ op: "add", path: this.path, value: temp.value }
]);
return true;
},
test: function (obj, key) {
return (JSON.stringify(obj[key]) === JSON.stringify(this.value));
},
_get: function (obj, key) {
this.value = obj[key];
}
};
var arrOps = {
add: function (arr, i) {
arr.splice(i, 0, this.value);
return true;
},
remove: function (arr, i) {
arr.splice(i, 1);
return true;
},
replace: function (arr, i) {
arr[i] = this.value;
return true;
},
move: objOps.move,
copy: objOps.copy,
test: objOps.test,
_get: objOps._get
};
var observeOps = {
add: function (patches, path) {
var patch = {
op: "add",
path: path + escapePathComponent(this.name),
value: this.object[this.name]
};
patches.push(patch);
},
'delete': function (patches, path) {
var patch = {
op: "remove",
path: path + escapePathComponent(this.name)
};
patches.push(patch);
},
update: function (patches, path) {
var patch = {
op: "replace",
path: path + escapePathComponent(this.name),
value: this.object[this.name]
};
patches.push(patch);
}
};
function escapePathComponent(str) {
if (str.indexOf('/') === -1 && str.indexOf('~') === -1)
return str;
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
function _getPathRecursive(root, obj) {
var found;
for (var key in root) {
if (root.hasOwnProperty(key)) {
if (root[key] === obj) {
return escapePathComponent(key) + '/';
} else if (typeof root[key] === 'object') {
found = _getPathRecursive(root[key], obj);
if (found != '') {
return escapePathComponent(key) + '/' + found;
}
}
}
}
return '';
}
function getPath(root, obj) {
if (root === obj) {
return '/';
}
var path = _getPathRecursive(root, obj);
if (path === '') {
throw new Error("Object not found in root");
}
return '/' + path;
}
var beforeDict = [];
jsonpatch.intervals;
var Mirror = (function () {
function Mirror(obj) {
this.observers = [];
this.obj = obj;
}
return Mirror;
})();
var ObserverInfo = (function () {
function ObserverInfo(callback, observer) {
this.callback = callback;
this.observer = observer;
}
return ObserverInfo;
})();
function getMirror(obj) {
for (var i = 0, ilen = beforeDict.length; i < ilen; i++) {
if (beforeDict[i].obj === obj) {
return beforeDict[i];
}
}
}
function getObserverFromMirror(mirror, callback) {
for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) {
if (mirror.observers[j].callback === callback) {
return mirror.observers[j].observer;
}
}
}
function removeObserverFromMirror(mirror, observer) {
for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) {
if (mirror.observers[j].observer === observer) {
mirror.observers.splice(j, 1);
return;
}
}
}
function unobserve(root, observer) {
generate(observer);
if (Object.observe) {
_unobserve(observer, root);
} else {
clearTimeout(observer.next);
}
var mirror = getMirror(root);
removeObserverFromMirror(mirror, observer);
}
jsonpatch.unobserve = unobserve;
function observe(obj, callback) {
var patches = [];
var root = obj;
var observer;
var mirror = getMirror(obj);
if (!mirror) {
mirror = new Mirror(obj);
beforeDict.push(mirror);
} else {
observer = getObserverFromMirror(mirror, callback);
}
if (observer) {
return observer;
}
if (Object.observe) {
observer = function (arr) {
//This "refresh" is needed to begin observing new object properties
_unobserve(observer, obj);
_observe(observer, obj);
var a = 0, alen = arr.length;
while (a < alen) {
if (!(arr[a].name === 'length' && _isArray(arr[a].object)) && !(arr[a].name === '__Jasmine_been_here_before__')) {
var type = arr[a].type;
switch (type) {
case 'new':
type = 'add';
break;
case 'deleted':
type = 'delete';
break;
case 'updated':
type = 'update';
break;
}
observeOps[type].call(arr[a], patches, getPath(root, arr[a].object));
}
a++;
}
if (patches) {
if (callback) {
callback(patches);
}
}
observer.patches = patches;
patches = [];
};
} else {
observer = {};
mirror.value = JSON.parse(JSON.stringify(obj));
if (callback) {
//callbacks.push(callback); this has no purpose
observer.callback = callback;
observer.next = null;
var intervals = this.intervals || [100, 1000, 10000, 60000];
var currentInterval = 0;
var dirtyCheck = function () {
generate(observer);
};
var fastCheck = function () {
clearTimeout(observer.next);
observer.next = setTimeout(function () {
dirtyCheck();
currentInterval = 0;
observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
}, 0);
};
var slowCheck = function () {
dirtyCheck();
if (currentInterval == intervals.length)
currentInterval = intervals.length - 1;
observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
};
if (typeof window !== 'undefined') {
if (window.addEventListener) {
window.addEventListener('mousedown', fastCheck);
window.addEventListener('mouseup', fastCheck);
window.addEventListener('keydown', fastCheck);
} else {
window.attachEvent('onmousedown', fastCheck);
window.attachEvent('onmouseup', fastCheck);
window.attachEvent('onkeydown', fastCheck);
}
}
observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
}
}
observer.patches = patches;
observer.object = obj;
mirror.observers.push(new ObserverInfo(callback, observer));
return _observe(observer, obj);
}
jsonpatch.observe = observe;
/// Listen to changes on an object tree, accumulate patches
function _observe(observer, obj) {
if (Object.observe) {
Object.observe(obj, observer);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var v = obj[key];
if (v && typeof (v) === "object") {
_observe(observer, v);
}
}
}
}
return observer;
}
function _unobserve(observer, obj) {
if (Object.observe) {
Object.unobserve(obj, observer);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var v = obj[key];
if (v && typeof (v) === "object") {
_unobserve(observer, v);
}
}
}
}
return observer;
}
function generate(observer) {
if (Object.observe) {
Object.deliverChangeRecords(observer);
} else {
var mirror;
for (var i = 0, ilen = beforeDict.length; i < ilen; i++) {
if (beforeDict[i].obj === observer.object) {
mirror = beforeDict[i];
break;
}
}
_generate(mirror.value, observer.object, observer.patches, "");
}
var temp = observer.patches;
if (temp.length > 0) {
observer.patches = [];
if (observer.callback) {
observer.callback(temp);
}
}
return temp;
}
jsonpatch.generate = generate;
var _objectKeys;
if (Object.keys) {
_objectKeys = Object.keys;
} else {
_objectKeys = function (obj) {
var keys = [];
for (var o in obj) {
if (obj.hasOwnProperty(o)) {
keys.push(o);
}
}
return keys;
};
}
// Dirty check if obj is different from mirror, generate patches and update mirror
function _generate(mirror, obj, patches, path) {
var newKeys = _objectKeys(obj);
var oldKeys = _objectKeys(mirror);
var changed = false;
var deleted = false;
for (var t = oldKeys.length - 1; t >= 0; t--) {
var key = oldKeys[t];
var oldVal = mirror[key];
if (obj.hasOwnProperty(key)) {
var newVal = obj[key];
if (oldVal instanceof Object) {
_generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key));
} else {
if (oldVal != newVal) {
changed = true;
patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: newVal });
mirror[key] = newVal;
}
}
} else {
patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) });
delete mirror[key];
deleted = true;
}
}
if (!deleted && newKeys.length == oldKeys.length) {
return;
}
for (var t = 0; t < newKeys.length; t++) {
var key = newKeys[t];
if (!mirror.hasOwnProperty(key)) {
patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: obj[key] });
mirror[key] = JSON.parse(JSON.stringify(obj[key]));
}
}
}
var _isArray;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function (obj) {
return obj.push && typeof obj.length === 'number';
};
}
/// Apply a json-patch operation on an object tree
function apply(tree, patches) {
var result = false, p = 0, plen = patches.length, patch;
while (p < plen) {
patch = patches[p];
// Find the object
var keys = patch.path.split('/');
var obj = tree;
var t = 1;
var len = keys.length;
while (true) {
if (_isArray(obj)) {
var index = parseInt(keys[t], 10);
t++;
if (t >= len) {
result = arrOps[patch.op].call(patch, obj, index, tree);
break;
}
obj = obj[index];
} else {
var key = keys[t];
if (key.indexOf('~') != -1)
key = key.replace(/~1/g, '/').replace(/~0/g, '~');
t++;
if (t >= len) {
result = objOps[patch.op].call(patch, obj, key, tree);
break;
}
obj = obj[key];
}
}
p++;
}
return result;
}
jsonpatch.apply = apply;
})(jsonpatch || (jsonpatch = {}));
if (typeof exports !== "undefined") {
exports.apply = jsonpatch.apply;
exports.observe = jsonpatch.observe;
exports.unobserve = jsonpatch.unobserve;
exports.generate = jsonpatch.generate;
}
Handsontable.PluginHookClass = (function () {
var Hooks = function () {
return {
// Hooks
beforeInitWalkontable: [],
beforeInit: [],
beforeRender: [],
beforeSetRangeEnd: [],
beforeChange: [],
beforeChangeRender: [],
beforeRemoveCol: [],
beforeRemoveRow: [],
beforeValidate: [],
beforeGetCellMeta: [],
beforeAutofill: [],
beforeKeyDown: [],
afterInit : [],
afterLoadData : [],
afterUpdateSettings: [],
afterRender : [],
afterRenderer : [],
afterChange : [],
afterValidate: [],
afterGetCellMeta: [],
afterSetCellMeta: [],
afterGetColHeader: [],
afterDestroy: [],
afterRemoveRow: [],
afterCreateRow: [],
afterRemoveCol: [],
afterCreateCol: [],
afterDeselect: [],
afterSelection: [],
afterSelectionByProp: [],
afterSelectionEnd: [],
afterSelectionEndByProp: [],
afterOnCellMouseDown: [],
afterOnCellMouseOver: [],
afterOnCellCornerMouseDown: [],
afterScrollVertically: [],
afterScrollHorizontally: [],
afterCellMetaReset:[],
// Modifiers
modifyColWidth: [],
modifyRowHeight: [],
modifyRow: [],
modifyCol: []
}
};
var legacy = {
onBeforeChange: "beforeChange",
onChange: "afterChange",
onCreateRow: "afterCreateRow",
onCreateCol: "afterCreateCol",
onSelection: "afterSelection",
onCopyLimit: "afterCopyLimit",
onSelectionEnd: "afterSelectionEnd",
onSelectionByProp: "afterSelectionByProp",
onSelectionEndByProp: "afterSelectionEndByProp"
};
function PluginHookClass() {
this.hooks = Hooks();
this.globalBucket = {};
this.legacy = legacy;
}
PluginHookClass.prototype.getBucket = function (instance) {
if(instance) {
if(!instance.pluginHookBucket) {
instance.pluginHookBucket = {};
}
return instance.pluginHookBucket;
}
return this.globalBucket;
};
PluginHookClass.prototype.add = function (key, fn, instance) {
//if fn is array, run this for all the array items
if (Handsontable.helper.isArray(fn)) {
for (var i = 0, len = fn.length; i < len; i++) {
this.add(key, fn[i]);
}
}
else {
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
var bucket = this.getBucket(instance);
if (typeof bucket[key] === "undefined") {
bucket[key] = [];
}
fn.skip = false;
if (bucket[key].indexOf(fn) == -1) {
bucket[key].push(fn); //only add a hook if it has not already be added (adding the same hook twice is now silently ignored)
}
}
return this;
};
PluginHookClass.prototype.once = function(key, fn, instance){
if(Handsontable.helper.isArray(fn)){
for(var i = 0, len = fn.length; i < len; i++){
fn[i].runOnce = true;
this.add(key, fn[i], instance);
}
} else {
fn.runOnce = true;
this.add(key, fn, instance);
}
};
PluginHookClass.prototype.remove = function (key, fn, instance) {
var status = false;
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
var bucket = this.getBucket(instance);
if (typeof bucket[key] !== 'undefined') {
for (var i = 0, leni = bucket[key].length; i < leni; i++) {
if (bucket[key][i] == fn) {
bucket[key][i].skip = true;
status = true;
break;
}
}
}
return status;
};
PluginHookClass.prototype.run = function (instance, key, p1, p2, p3, p4, p5) {
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
this._runBucket(this.globalBucket, instance, key, p1, p2, p3, p4, p5);
this._runBucket(this.getBucket(instance), instance, key, p1, p2, p3, p4, p5);
};
PluginHookClass.prototype._runBucket = function (bucket, instance, key, p1, p2, p3, p4, p5) {
var handlers = bucket[key];
if (handlers) {
for (var i = 0, leni = handlers.length; i < leni; i++) {
if (!handlers[i].skip) {
handlers[i].call(instance, p1, p2, p3, p4, p5);
if (handlers[i].runOnce) {
this.remove(key, handlers[i], bucket === this.globalBucket ? null : instance);
}
}
}
}
};
PluginHookClass.prototype.execute = function (instance, key, p1, p2, p3, p4, p5) {
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
p1 = this._executeBucket(this.globalBucket, instance, key, p1, p2, p3, p4, p5);
p1 = this._executeBucket(this.getBucket(instance), instance, key, p1, p2, p3, p4, p5);
return p1;
};
PluginHookClass.prototype._executeBucket = function (bucket, instance, key, p1, p2, p3, p4, p5) {
var res,
handlers = bucket[key];
//performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture
if (handlers) {
for (var i = 0, leni = handlers.length; i < leni; i++) {
if (!handlers[i].skip) {
res = handlers[i].call(instance, p1, p2, p3, p4, p5);
if (res !== void 0) {
p1 = res;
}
if (handlers[i].runOnce) {
this.remove(key, handlers[i], bucket === this.globalBucket ? null : instance);
}
if (res === false) { //if any handler returned false
return false; //event has been cancelled and further execution of handler queue is being aborted
}
}
}
}
return p1;
};
/**
* Registers a hook name (adds it to the list of the known hook names). Used by plugins. It is not neccessary to call,
* register, but if you use it, your plugin hook will be used returned by getRegistered
* (which itself is used in the demo http://handsontable.com/demo/callbacks.html)
* @param key {String}
*/
PluginHookClass.prototype.register = function (key) {
if (!this.isRegistered(key)) {
this.hooks[key] = [];
}
};
/**
* Deregisters a hook name (removes it from the list of known hook names)
* @param key {String}
*/
PluginHookClass.prototype.deregister = function (key) {
delete this.hooks[key];
};
/**
* Returns boolean information if a hook by such name has been registered
* @param key {String}
*/
PluginHookClass.prototype.isRegistered = function (key) {
return (typeof this.hooks[key] !== "undefined");
};
/**
* Returns an array of registered hooks
* @returns {Array}
*/
PluginHookClass.prototype.getRegistered = function () {
return Object.keys(this.hooks);
};
return PluginHookClass;
})();
Handsontable.hooks = new Handsontable.PluginHookClass();
Handsontable.PluginHooks = Handsontable.hooks; //in future move this line to legacy.js
(function (Handsontable) {
function HandsontableAutoColumnSize() {
var plugin = this
, sampleCount = 5; //number of samples to take of each value length
this.beforeInit = function () {
var instance = this;
instance.autoColumnWidths = [];
if (instance.getSettings().autoColumnSize !== false) {
if (!instance.autoColumnSizeTmp) {
instance.autoColumnSizeTmp = {
table: null,
tableStyle: null,
theadTh: null,
tbody: null,
container: null,
containerStyle: null,
determineBeforeNextRender: true
};
instance.addHook('beforeRender', htAutoColumnSize.determineIfChanged);
instance.addHook('modifyColWidth', htAutoColumnSize.modifyColWidth);
instance.addHook('afterDestroy', htAutoColumnSize.afterDestroy);
instance.determineColumnWidth = plugin.determineColumnWidth;
}
} else {
if (instance.autoColumnSizeTmp) {
instance.removeHook('beforeRender', htAutoColumnSize.determineIfChanged);
instance.removeHook('modifyColWidth', htAutoColumnSize.modifyColWidth);
instance.removeHook('afterDestroy', htAutoColumnSize.afterDestroy);
delete instance.determineColumnWidth;
plugin.afterDestroy.call(instance);
}
}
};
this.determineIfChanged = function (force) {
if (force) {
htAutoColumnSize.determineColumnsWidth.apply(this, arguments);
}
};
this.determineColumnWidth = function (col) {
var instance = this
, tmp = instance.autoColumnSizeTmp;
if (!tmp.container) {
createTmpContainer.call(tmp, instance);
}
tmp.container.className = instance.rootElement[0].className + ' htAutoColumnSize';
tmp.table.className = instance.$table[0].className;
var rows = instance.countRows();
var samples = {};
var maxLen = 0;
for (var r = 0; r < rows; r++) {
var value = Handsontable.helper.stringify(instance.getDataAtCell(r, col));
var len = value.length;
if (len > maxLen) {
maxLen = len;
}
if (!samples[len]) {
samples[len] = {
needed: sampleCount,
strings: []
};
}
if (samples[len].needed) {
samples[len].strings.push({value: value, row: r});
samples[len].needed--;
}
}
var settings = instance.getSettings();
if (settings.colHeaders) {
instance.view.appendColHeader(col, tmp.theadTh); //TH innerHTML
}
Handsontable.Dom.empty(tmp.tbody);
for (var i in samples) {
if (samples.hasOwnProperty(i)) {
for (var j = 0, jlen = samples[i].strings.length; j < jlen; j++) {
var row = samples[i].strings[j].row;
var cellProperties = instance.getCellMeta(row, col);
cellProperties.col = col;
cellProperties.row = row;
var renderer = instance.getCellRenderer(cellProperties);
var tr = document.createElement('tr');
var td = document.createElement('td');
renderer(instance, td, row, col, instance.colToProp(col), samples[i].strings[j].value, cellProperties);
r++;
tr.appendChild(td);
tmp.tbody.appendChild(tr);
}
}
}
var parent = instance.rootElement[0].parentNode;
parent.appendChild(tmp.container);
var width = Handsontable.Dom.outerWidth(tmp.table);
parent.removeChild(tmp.container);
return width;
};
this.determineColumnsWidth = function () {
var instance = this;
var settings = this.getSettings();
if (settings.autoColumnSize || !settings.colWidths) {
var cols = this.countCols();
for (var c = 0; c < cols; c++) {
if (!instance._getColWidthFromSettings(c)) {
this.autoColumnWidths[c] = plugin.determineColumnWidth.call(instance, c);
}
}
}
};
this.modifyColWidth = function (width, col) {
if (this.autoColumnWidths[col] && this.autoColumnWidths[col] > width) {
return this.autoColumnWidths[col];
}
return width;
};
this.afterDestroy = function () {
var instance = this;
if (instance.autoColumnSizeTmp && instance.autoColumnSizeTmp.container && instance.autoColumnSizeTmp.container.parentNode) {
instance.autoColumnSizeTmp.container.parentNode.removeChild(instance.autoColumnSizeTmp.container);
}
instance.autoColumnSizeTmp = null;
};
function createTmpContainer(instance) {
var d = document
, tmp = this;
tmp.table = d.createElement('table');
tmp.theadTh = d.createElement('th');
tmp.table.appendChild(d.createElement('thead')).appendChild(d.createElement('tr')).appendChild(tmp.theadTh);
tmp.tableStyle = tmp.table.style;
tmp.tableStyle.tableLayout = 'auto';
tmp.tableStyle.width = 'auto';
tmp.tbody = d.createElement('tbody');
tmp.table.appendChild(tmp.tbody);
tmp.container = d.createElement('div');
tmp.container.className = instance.rootElement[0].className + ' hidden';
tmp.containerStyle = tmp.container.style;
tmp.container.appendChild(tmp.table);
}
}
var htAutoColumnSize = new HandsontableAutoColumnSize();
Handsontable.hooks.add('beforeInit', htAutoColumnSize.beforeInit);
Handsontable.hooks.add('afterUpdateSettings', htAutoColumnSize.beforeInit);
})(Handsontable);
/**
* This plugin sorts the view by a column (but does not sort the data source!)
* @constructor
*/
function HandsontableColumnSorting() {
var plugin = this;
this.init = function (source) {
var instance = this;
var sortingSettings = instance.getSettings().columnSorting;
var sortingColumn, sortingOrder;
instance.sortingEnabled = !!(sortingSettings);
if (instance.sortingEnabled) {
instance.sortIndex = [];
var loadedSortingState = loadSortingState.call(instance);
if (typeof loadedSortingState != 'undefined') {
sortingColumn = loadedSortingState.sortColumn;
sortingOrder = loadedSortingState.sortOrder;
} else {
sortingColumn = sortingSettings.column;
sortingOrder = sortingSettings.sortOrder;
}
plugin.sortByColumn.call(instance, sortingColumn, sortingOrder);
instance.sort = function(){
var args = Array.prototype.slice.call(arguments);
return plugin.sortByColumn.apply(instance, args)
};
if (typeof instance.getSettings().observeChanges == 'undefined'){
enableObserveChangesPlugin.call(instance);
}
if (source == 'afterInit') {
bindColumnSortingAfterClick.call(instance);
instance.addHook('afterCreateRow', plugin.afterCreateRow);
instance.addHook('afterRemoveRow', plugin.afterRemoveRow);
instance.addHook('afterLoadData', plugin.init);
}
} else {
delete instance.sort;
instance.removeHook('afterCreateRow', plugin.afterCreateRow);
instance.removeHook('afterRemoveRow', plugin.afterRemoveRow);
instance.removeHook('afterLoadData', plugin.init);
}
};
this.setSortingColumn = function (col, order) {
var instance = this;
if (typeof col == 'undefined') {
delete instance.sortColumn;
delete instance.sortOrder;
return;
} else if (instance.sortColumn === col && typeof order == 'undefined') {
instance.sortOrder = !instance.sortOrder;
} else {
instance.sortOrder = typeof order != 'undefined' ? order : true;
}
instance.sortColumn = col;
};
this.sortByColumn = function (col, order) {
var instance = this;
plugin.setSortingColumn.call(instance, col, order);
if(typeof instance.sortColumn == 'undefined'){
return;
}
Handsontable.hooks.run(instance, 'beforeColumnSort', instance.sortColumn, instance.sortOrder);
plugin.sort.call(instance);
instance.render();
saveSortingState.call(instance);
Handsontable.hooks.run(instance, 'afterColumnSort', instance.sortColumn, instance.sortOrder);
};
var saveSortingState = function () {
var instance = this;
var sortingState = {};
if (typeof instance.sortColumn != 'undefined') {
sortingState.sortColumn = instance.sortColumn;
}
if (typeof instance.sortOrder != 'undefined') {
sortingState.sortOrder = instance.sortOrder;
}
if (sortingState.hasOwnProperty('sortColumn') || sortingState.hasOwnProperty('sortOrder')) {
Handsontable.hooks.run(instance, 'persistentStateSave', 'columnSorting', sortingState);
}
};
var loadSortingState = function () {
var instance = this;
var storedState = {};
Handsontable.hooks.run(instance, 'persistentStateLoad', 'columnSorting', storedState);
return storedState.value;
};
var bindColumnSortingAfterClick = function () {
var instance = this;
instance.rootElement.on('click.handsontable', '.columnSorting', function (e) {
if (Handsontable.Dom.hasClass(e.target, 'columnSorting')) {
var col = getColumn(e.target);
plugin.sortByColumn.call(instance, col);
}
});
function countRowHeaders() {
var THs = instance.view.TBODY.querySelector('tr').querySelectorAll('th');
return THs.length;
}
function getColumn(target) {
var TH = Handsontable.Dom.closest(target, 'TH');
return Handsontable.Dom.index(TH) - countRowHeaders();
}
};
function enableObserveChangesPlugin () {
var instance = this;
instance._registerTimeout('enableObserveChanges', function(){
instance.updateSettings({
observeChanges: true
});
}, 0);
}
function defaultSort(sortOrder) {
return function (a, b) {
if (a[1] === b[1]) {
return 0;
}
if (a[1] === null) {
return 1;
}
if (b[1] === null) {
return -1;
}
if (a[1] < b[1]) return sortOrder ? -1 : 1;
if (a[1] > b[1]) return sortOrder ? 1 : -1;
return 0;
}
}
function dateSort(sortOrder) {
return function (a, b) {
if (a[1] === b[1]) {
return 0;
}
if (a[1] === null) {
return 1;
}
if (b[1] === null) {
return -1;
}
var aDate = new Date(a[1]);
var bDate = new Date(b[1]);
if (aDate < bDate) return sortOrder ? -1 : 1;
if (aDate > bDate) return sortOrder ? 1 : -1;
return 0;
}
}
this.sort = function () {
var instance = this;
if (typeof instance.sortOrder == 'undefined') {
return;
}
instance.sortingEnabled = false; //this is required by translateRow plugin hook
instance.sortIndex.length = 0;
var colOffset = this.colOffset();
for (var i = 0, ilen = this.countRows() - instance.getSettings()['minSpareRows']; i < ilen; i++) {
this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]);
}
var colMeta = instance.getCellMeta(0, instance.sortColumn);
var sortFunction;
switch (colMeta.type) {
case 'date':
sortFunction = dateSort;
break;
default:
sortFunction = defaultSort;
}
this.sortIndex.sort(sortFunction(instance.sortOrder));
//Append spareRows
for(var i = this.sortIndex.length; i < instance.countRows(); i++){
this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]);
}
instance.sortingEnabled = true; //this is required by translateRow plugin hook
};
this.translateRow = function (row) {
var instance = this;
if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length && instance.sortIndex[row]) {
return instance.sortIndex[row][0];
}
return row;
};
this.untranslateRow = function (row) {
var instance = this;
if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length) {
for (var i = 0; i < instance.sortIndex.length; i++) {
if (instance.sortIndex[i][0] == row) {
return i;
}
}
}
};
this.getColHeader = function (col, TH) {
if (this.getSettings().columnSorting) {
Handsontable.Dom.addClass(TH.querySelector('.colHeader'), 'columnSorting');
}
};
function isSorted(instance){
return typeof instance.sortColumn != 'undefined';
}
this.afterCreateRow = function(index, amount){
var instance = this;
if(!isSorted(instance)){
return;
}
for(var i = 0; i < instance.sortIndex.length; i++){
if (instance.sortIndex[i][0] >= index){
instance.sortIndex[i][0] += amount;
}
}
for(var i=0; i < amount; i++){
instance.sortIndex.splice(index+i, 0, [index+i, instance.getData()[index+i][instance.sortColumn + instance.colOffset()]]);
}
saveSortingState.call(instance);
};
this.afterRemoveRow = function(index, amount){
var instance = this;
if(!isSorted(instance)){
return;
}
var physicalRemovedIndex = plugin.translateRow.call(instance, index);
instance.sortIndex.splice(index, amount);
for(var i = 0; i < instance.sortIndex.length; i++){
if (instance.sortIndex[i][0] > physicalRemovedIndex){
instance.sortIndex[i][0] -= amount;
}
}
saveSortingState.call(instance);
};
this.afterChangeSort = function (changes/*, source*/) {
var instance = this;
var sortColumnChanged = false;
var selection = {};
if (!changes) {
return;
}
for (var i = 0; i < changes.length; i++) {
if (changes[i][1] == instance.sortColumn) {
sortColumnChanged = true;
selection.row = plugin.translateRow.call(instance, changes[i][0]);
selection.col = changes[i][1];
break;
}
}
if (sortColumnChanged) {
setTimeout(function () {
plugin.sort.call(instance);
instance.render();
instance.selectCell(plugin.untranslateRow.call(instance, selection.row), selection.col);
}, 0);
}
};
}
var htSortColumn = new HandsontableColumnSorting();
Handsontable.hooks.add('afterInit', function () {
htSortColumn.init.call(this, 'afterInit')
});
Handsontable.hooks.add('afterUpdateSettings', function () {
htSortColumn.init.call(this, 'afterUpdateSettings')
});
Handsontable.hooks.add('modifyRow', htSortColumn.translateRow);
Handsontable.hooks.add('afterGetColHeader', htSortColumn.getColHeader);
Handsontable.hooks.register('beforeColumnSort');
Handsontable.hooks.register('afterColumnSort');
(function (Handsontable) {
'use strict';
function prepareVerticalAlignClass (className, alignment) {
if (className.indexOf(alignment)!= -1){
return className;
}
className = className
.replace('htTop','')
.replace('htMiddle','')
.replace('htBottom','')
.replace(' ','');
className += " " + alignment;
return className;
}
function prepareHorizontalAlignClass (className, alignment) {
if (className.indexOf(alignment)!= -1){
return className;
}
className = className
.replace('htLeft','')
.replace('htCenter','')
.replace('htRight','')
.replace('htJustify','')
.replace(' ','');
className += " " + alignment;
return className;
}
function doAlign (row, col, type, alignment) {
var cellMeta = this.getCellMeta(row, col),
className = alignment;
if (cellMeta.className) {
if(type === 'vertical') {
className = prepareVerticalAlignClass(cellMeta.className, alignment);
} else {
className = prepareHorizontalAlignClass(cellMeta.className, alignment);
}
}
this.setCellMeta(row, col, 'className',className);
this.render();
}
function align (range, type, alignment) {
// if (range.from.row < 0) {
// range.from = new WalkontableCellCoords(0,range.from.col);
// range.to = new WalkontableCellCoords(this.view.wt.wtTable.getRowStrategy().cellCount - 1, range.to.col);
// }
// if (range.from.col < 0) {
// range.from = new WalkontableCellCoords(range.from.row, 0);
// range.to = new WalkontableCellCoords(range.to.row, this.view.wt.wtTable.getColumnStrategy().cellCount - 1);
// }
if (range.from.row == range.to.row && range.from.col == range.to.col){
doAlign.call(this,range.from.row, range.from.col, type, alignment);
} else {
for(var row = range.from.row; row<= range.to.row; row++) {
for (var col = range.from.col; col <= range.to.col; col++) {
doAlign.call(this,row, col, type, alignment);
}
}
}
}
function ContextMenu(instance, customOptions){
this.instance = instance;
var contextMenu = this;
this.menu = createMenu();
this.enabled = true;
this.bindMouseEvents();
this.instance.addHook('afterDestroy', function () {
contextMenu.destroy();
});
this.defaultOptions = {
items: {
'row_above': {
name: 'Insert row above',
callback: function(key, selection){
this.alter("insert_row", selection.start.row);
},
disabled: function () {
var selected = this.getSelected(),
entireColumnSelection = [0,selected[1],this.view.wt.wtTable.getRowStrategy().cellCount-1,selected[1]],
columnSelected = entireColumnSelection.join(',') == selected.join(',');
return selected[0] < 0 || this.countRows() >= this.getSettings().maxRows || columnSelected;
}
},
'row_below': {
name: 'Insert row below',
callback: function(key, selection){
this.alter("insert_row", selection.end.row + 1);
},
disabled: function () {
var selected = this.getSelected(),
entireColumnSelection = [0,selected[1],this.view.wt.wtTable.getRowStrategy().cellCount-1,selected[1]],
columnSelected = entireColumnSelection.join(',') == selected.join(',');
return this.getSelected()[0] < 0 || this.countRows() >= this.getSettings().maxRows || columnSelected;
}
},
"hsep1": ContextMenu.SEPARATOR,
'col_left': {
name: 'Insert column on the left',
callback: function(key, selection){
this.alter("insert_col", selection.start.col);
},
disabled: function () {
var selected = this.getSelected(),
entireRowSelection = [selected[0],0, selected[0],this.view.wt.wtTable.getColumnStrategy().cellCount-1],
rowSelected = entireRowSelection.join(',') == selected.join(',');
return this.getSelected()[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected;
}
},
'col_right': {
name: 'Insert column on the right',
callback: function(key, selection){
this.alter("insert_col", selection.end.col + 1);
},
disabled: function () {
var selected = this.getSelected(),
entireRowSelection = [selected[0],0, selected[0],this.view.wt.wtTable.getColumnStrategy().cellCount-1],
rowSelected = entireRowSelection.join(',') == selected.join(',');
return selected[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected;
}
},
"hsep2": ContextMenu.SEPARATOR,
'remove_row': {
name: 'Remove row',
callback: function(key, selection){
var amount = selection.end.row - selection.start.row + 1;
this.alter("remove_row", selection.start.row, amount);
},
disabled: function () {
var selected = this.getSelected(),
entireColumnSelection = [0,selected[1],this.view.wt.wtTable.getRowStrategy().cellCount-1,selected[1]],
columnSelected = entireColumnSelection.join(',') == selected.join(',');
return (selected[0] < 0 || columnSelected);
}
},
'remove_col': {
name: 'Remove column',
callback: function(key, selection){
var amount = selection.end.col - selection.start.col + 1;
this.alter("remove_col", selection.start.col, amount);
},
disabled: function (){
var selected = this.getSelected(),
entireRowSelection = [selected[0],0, selected[0],this.view.wt.wtTable.getColumnStrategy().cellCount-1],
rowSelected = entireRowSelection.join(',') == selected.join(',');
return (selected[1] < 0 || rowSelected);
}
},
"hsep3": ContextMenu.SEPARATOR,
'undo': {
name: 'Undo',
callback: function(){
this.undo();
},
disabled: function () {
return this.undoRedo && !this.undoRedo.isUndoAvailable();
}
},
'redo': {
name: 'Redo',
callback: function(){
this.redo();
},
disabled: function () {
return this.undoRedo && !this.undoRedo.isRedoAvailable();
}
},
"hsep4": ContextMenu.SEPARATOR,
'make_read_only': {
name: function() {
var atLeastOneReadOnly = contextMenu.checkSelectionReadOnlyConsistency(this);
if(!atLeastOneReadOnly) {
return "Make read-only";
} else {
return "Make writable";
}
},
callback: function() {
var atLeastOneReadOnly = contextMenu.checkSelectionReadOnlyConsistency(this);
var that = this;
this.getSelectedRange().forAll(function(r, c) {
that.getCellMeta(r, c).readOnly = atLeastOneReadOnly ? false : true;
});
this.render();
}
},
"hsep5": ContextMenu.SEPARATOR,
'horizontal_alignment': {
name: function () {
var div = document.createElement('div'),
button = document.createElement('button'),
lButton = button.cloneNode(true),
rButton = button.cloneNode(true),
cButton = button.cloneNode(true),
jButton = button.cloneNode(true),
lText = document.createTextNode('left'),
cText = document.createTextNode('center'),
rText = document.createTextNode('right'),
jText = document.createTextNode('justify');
lButton.appendChild(lText);
cButton.appendChild(cText);
rButton.appendChild(rText);
jButton.appendChild(jText);
Handsontable.Dom.addClass(lButton,'Left');
Handsontable.Dom.addClass(cButton,'Center');
Handsontable.Dom.addClass(rButton,'Right');
Handsontable.Dom.addClass(jButton,'Justify');
div.appendChild(lButton);
div.appendChild(cButton);
div.appendChild(rButton);
div.appendChild(jButton);
return div.outerHTML;
},
callback: function (key, selection ,event) {
var className = event.target.className,
type = event.target.tagName;
if (type === "BUTTON") {
if(className) {
align.call(this, this.getSelectedRange(),'horizontal','ht' + className );
}
}
},
disabled: function () {
return false;
}
},
"hsep6": ContextMenu.SEPARATOR,
'vertical_alignment': {
name: function () {
var div = document.createElement('div'),
button = document.createElement('button'),
tButton = button.cloneNode(true),
mButton = button.cloneNode(true),
bButton = button.cloneNode(true),
tText = document.createTextNode('top'),
mText = document.createTextNode('middle'),
bText = document.createTextNode('bottom');
tButton.appendChild(tText);
mButton.appendChild(mText);
bButton.appendChild(bText);
Handsontable.Dom.addClass(tButton,'Top');
Handsontable.Dom.addClass(mButton,'Middle');
Handsontable.Dom.addClass(bButton,'Bottom');
div.appendChild(tButton);
div.appendChild(mButton);
div.appendChild(bButton);
return div.outerHTML;
},
callback: function (key, selection ,event) {
var className = event.target.className,
type = event.target.tagName;
if (type === "BUTTON") {
if(className) {
align.call(this, this.getSelectedRange(),'vertical','ht' + className );
}
}
},
disabled: function () {
return false;
}
}
}
};
this.checkSelectionReadOnlyConsistency = function(hot) {
var atLeastOneReadOnly = false;
hot.getSelectedRange().forAll(function(r, c) {
if(hot.getCellMeta(r, c).readOnly) {
atLeastOneReadOnly = true;
return false; //breaks forAll
}
});
return atLeastOneReadOnly;
};
Handsontable.hooks.run(instance, 'afterContextMenuDefaultOptions', this.defaultOptions);
this.options = {};
Handsontable.helper.extend(this.options, this.defaultOptions);
this.updateOptions(customOptions);
function createMenu(){
var menu = $('body > .htContextMenu')[0];
if(!menu){
menu = document.createElement('DIV');
Handsontable.Dom.addClass(menu, 'htContextMenu');
document.getElementsByTagName('body')[0].appendChild(menu);
}
return menu;
}
}
ContextMenu.prototype.bindMouseEvents = function (){
function contextMenuOpenListener(event){
event.preventDefault();
var showRowHeaders = this.instance.getSettings().rowHeaders,
showColHeaders = this.instance.getSettings().colHeaders;
if(!(showRowHeaders || showColHeaders)) {
if(event.target.nodeName != 'TD' && !(Handsontable.Dom.hasClass(event.target, 'current') && Handsontable.Dom.hasClass(event.target, 'wtBorder'))){
return;
}
}
//if(event.target.nodeName != 'TD' && !(Handsontable.Dom.hasClass(event.target, 'current') && Handsontable.Dom.hasClass(event.target, 'wtBorder'))){
// return;
//}
this.show(event.pageY, event.pageX);
$(document).on('mousedown.htContextMenu', Handsontable.helper.proxy(ContextMenu.prototype.close, this));
}
this.instance.rootElement.on('contextmenu.htContextMenu', Handsontable.helper.proxy(contextMenuOpenListener, this));
};
ContextMenu.prototype.bindTableEvents = function () {
var that = this;
this._afterScrollCallback = function () {
that.close();
};
this.instance.addHook('afterScrollVertically', this._afterScrollCallback);
this.instance.addHook('afterScrollHorizontally', this._afterScrollCallback);
};
ContextMenu.prototype.unbindTableEvents = function () {
if(this._afterScrollCallback){
this.instance.removeHook('afterScrollVertically', this._afterScrollCallback);
this.instance.removeHook('afterScrollHorizontally', this._afterScrollCallback);
this._afterScrollCallback = null;
}
};
ContextMenu.prototype.performAction = function (event){
var hot = $(this.menu).handsontable('getInstance');
var selectedItemIndex = hot.getSelected()[0];
var selectedItem = hot.getData()[selectedItemIndex];
if (selectedItem.disabled === true || (typeof selectedItem.disabled == 'function' && selectedItem.disabled.call(this.instance) === true)){
return;
}
if(typeof selectedItem.callback != 'function'){
return;
}
var selRange = this.instance.getSelectedRange();
var normalizedSelection = ContextMenu.utils.normalizeSelection(selRange);
selectedItem.callback.call(this.instance, selectedItem.key, normalizedSelection, event);
};
ContextMenu.prototype.unbindMouseEvents = function () {
this.instance.rootElement.off('contextmenu.htContextMenu');
$(document).off('mousedown.htContextMenu');
};
ContextMenu.prototype.show = function(top, left){
this.menu.style.display = 'block';
$(this.menu)
.off('mousedown.htContextMenu')
.on('mousedown.htContextMenu', Handsontable.helper.proxy(this.performAction, this));
$(this.menu).handsontable({
data: ContextMenu.utils.convertItemsToArray(this.getItems()),
colHeaders: false,
colWidths: [160],
readOnly: true,
copyPaste: false,
columns: [
{
data: 'name',
renderer: Handsontable.helper.proxy(this.renderer, this)
}
],
beforeKeyDown: Handsontable.helper.proxy(this.onBeforeKeyDown, this),
renderAllRows: true
});
this.bindTableEvents();
this.setMenuPosition(top, left);
$(this.menu).handsontable('listen');
};
ContextMenu.prototype.close = function () {
this.hide();
$(document).off('mousedown.htContextMenu');
this.unbindTableEvents();
this.instance.listen();
};
ContextMenu.prototype.hide = function(){
this.menu.style.display = 'none';
$(this.menu).handsontable('destroy');
};
ContextMenu.prototype.renderer = function(instance, TD, row, col, prop, value, cellProperties){
var contextMenu = this;
var item = instance.getData()[row];
var wrapper = document.createElement('DIV');
if(typeof value === 'function') {
value = value.call(this.instance);
}
Handsontable.Dom.empty(TD);
TD.appendChild(wrapper);
if(itemIsSeparator(item)){
Handsontable.Dom.addClass(TD, 'htSeparator');
} else {
Handsontable.Dom.fastInnerHTML(wrapper, value);
}
if (itemIsDisabled(item)){
Handsontable.Dom.addClass(TD, 'htDisabled');
$(wrapper).on('mouseenter', function () {
instance.deselectCell();
});
} else {
Handsontable.Dom.removeClass(TD, 'htDisabled');
$(wrapper).on('mouseenter', function () {
instance.selectCell(row, col);
});
}
function itemIsSeparator(item){
return new RegExp(ContextMenu.SEPARATOR, 'i').test(item.name);
}
function itemIsDisabled(item){
return item.disabled === true || (typeof item.disabled == 'function' && item.disabled.call(contextMenu.instance) === true);
}
};
ContextMenu.prototype.onBeforeKeyDown = function (event) {
var contextMenu = this;
var instance = $(contextMenu.menu).handsontable('getInstance');
var selection = instance.getSelected();
switch(event.keyCode){
case Handsontable.helper.keyCode.ESCAPE:
contextMenu.close();
event.preventDefault();
event.stopImmediatePropagation();
break;
case Handsontable.helper.keyCode.ENTER:
if(instance.getSelected()){
contextMenu.performAction();
contextMenu.close();
}
break;
case Handsontable.helper.keyCode.ARROW_DOWN:
if(!selection){
selectFirstCell(instance);
} else {
selectNextCell(selection[0], selection[1], instance);
}
event.preventDefault();
event.stopImmediatePropagation();
break;
case Handsontable.helper.keyCode.ARROW_UP:
if(!selection){
selectLastCell(instance);
} else {
selectPrevCell(selection[0], selection[1], instance);
}
event.preventDefault();
event.stopImmediatePropagation();
break;
}
function selectFirstCell(instance) {
var firstCell = instance.getCell(0, 0);
if(ContextMenu.utils.isSeparator(firstCell) || ContextMenu.utils.isDisabled(firstCell)){
selectNextCell(0, 0, instance);
} else {
instance.selectCell(0, 0);
}
}
function selectLastCell(instance) {
var lastRow = instance.countRows() - 1;
var lastCell = instance.getCell(lastRow, 0);
if(ContextMenu.utils.isSeparator(lastCell) || ContextMenu.utils.isDisabled(lastCell)){
selectPrevCell(lastRow, 0, instance);
} else {
instance.selectCell(lastRow, 0);
}
}
function selectNextCell(row, col, instance){
var nextRow = row + 1;
var nextCell = nextRow < instance.countRows() ? instance.getCell(nextRow, col) : null;
if(!nextCell){
return;
}
if(ContextMenu.utils.isSeparator(nextCell) || ContextMenu.utils.isDisabled(nextCell)){
selectNextCell(nextRow, col, instance);
} else {
instance.selectCell(nextRow, col);
}
}
function selectPrevCell(row, col, instance) {
var prevRow = row - 1;
var prevCell = prevRow >= 0 ? instance.getCell(prevRow, col) : null;
if (!prevCell) {
return;
}
if(ContextMenu.utils.isSeparator(prevCell) || ContextMenu.utils.isDisabled(prevCell)){
selectPrevCell(prevRow, col, instance);
} else {
instance.selectCell(prevRow, col);
}
}
};
ContextMenu.prototype.getItems = function () {
var items = {};
function Item(rawItem){
if(typeof rawItem == 'string'){
this.name = rawItem;
} else {
Handsontable.helper.extend(this, rawItem);
}
}
Item.prototype = this.options;
for(var itemName in this.options.items){
if(this.options.items.hasOwnProperty(itemName) && (!this.itemsFilter || this.itemsFilter.indexOf(itemName) != -1)){
items[itemName] = new Item(this.options.items[itemName]);
}
}
return items;
};
ContextMenu.prototype.updateOptions = function(newOptions){
newOptions = newOptions || {};
if(newOptions.items){
for(var itemName in newOptions.items){
var item = {};
if(newOptions.items.hasOwnProperty(itemName)) {
if(this.defaultOptions.items.hasOwnProperty(itemName)
&& Handsontable.helper.isObject(newOptions.items[itemName])){
Handsontable.helper.extend(item, this.defaultOptions.items[itemName]);
Handsontable.helper.extend(item, newOptions.items[itemName]);
newOptions.items[itemName] = item;
}
}
}
}
Handsontable.helper.extend(this.options, newOptions);
};
ContextMenu.prototype.setMenuPosition = function (cursorY, cursorX) {
var scrollTop = Handsontable.Dom.getWindowScrollTop();
var scrollLeft = Handsontable.Dom.getWindowScrollLeft();
var cursor = {
top: cursorY,
topRelative: cursorY - scrollTop,
left: cursorX,
leftRelative:cursorX - scrollLeft,
scrollTop: scrollTop,
scrollLeft: scrollLeft
};
if(this.menuFitsBelowCursor(cursor)){
this.positionMenuBelowCursor(cursor);
} else {
if (this.menuFitsAboveCursor(cursor)) {
this.positionMenuAboveCursor(cursor);
} else {
this.positionMenuBelowCursor(cursor);
}
}
if(this.menuFitsOnRightOfCursor(cursor)){
this.positionMenuOnRightOfCursor(cursor);
} else {
this.positionMenuOnLeftOfCursor(cursor);
}
};
ContextMenu.prototype.menuFitsAboveCursor = function (cursor) {
return cursor.topRelative >= this.menu.offsetHeight;
};
ContextMenu.prototype.menuFitsBelowCursor = function (cursor) {
return cursor.topRelative + this.menu.offsetHeight <= cursor.scrollTop + document.body.clientHeight;
};
ContextMenu.prototype.menuFitsOnRightOfCursor = function (cursor) {
return cursor.leftRelative + this.menu.offsetWidth <= cursor.scrollLeft + document.body.clientWidth;
};
ContextMenu.prototype.positionMenuBelowCursor = function (cursor) {
this.menu.style.top = cursor.top + 'px';
};
ContextMenu.prototype.positionMenuAboveCursor = function (cursor) {
this.menu.style.top = (cursor.top - this.menu.offsetHeight) + 'px';
};
ContextMenu.prototype.positionMenuOnRightOfCursor = function (cursor) {
this.menu.style.left = cursor.left + 'px';
};
ContextMenu.prototype.positionMenuOnLeftOfCursor = function (cursor) {
this.menu.style.left = (cursor.left - this.menu.offsetWidth) + 'px';
};
ContextMenu.utils = {};
ContextMenu.utils.convertItemsToArray = function (items) {
var itemArray = [];
var item;
for(var itemName in items){
if(items.hasOwnProperty(itemName)){
if(typeof items[itemName] == 'string'){
item = {name: items[itemName]};
} else if (items[itemName].visible !== false) {
item = items[itemName];
} else {
continue;
}
item.key = itemName;
itemArray.push(item);
}
}
return itemArray;
};
ContextMenu.utils.normalizeSelection = function(selRange){
return {
start: selRange.getTopLeftCorner(),
end: selRange.getBottomRightCorner()
};
};
ContextMenu.utils.isSeparator = function (cell) {
return Handsontable.Dom.hasClass(cell, 'htSeparator');
};
ContextMenu.utils.isDisabled = function (cell) {
return Handsontable.Dom.hasClass(cell, 'htDisabled');
};
ContextMenu.prototype.enable = function () {
if(!this.enabled){
this.enabled = true;
this.bindMouseEvents();
}
};
ContextMenu.prototype.disable = function () {
if(this.enabled){
this.enabled = false;
this.close();
this.unbindMouseEvents();
this.unbindTableEvents();
}
};
ContextMenu.prototype.destroy = function () {
this.close();
this.unbindMouseEvents();
this.unbindTableEvents();
if(!this.isMenuEnabledByOtherHotInstance()){
this.removeMenu();
}
};
ContextMenu.prototype.isMenuEnabledByOtherHotInstance = function () {
var hotContainers = $('.handsontable');
var menuEnabled = false;
for(var i = 0, len = hotContainers.length; i < len; i++){
var instance = $(hotContainers[i]).handsontable('getInstance');
if(instance && instance.getSettings().contextMenu){
menuEnabled = true;
break;
}
}
return menuEnabled;
};
ContextMenu.prototype.removeMenu = function () {
if(this.menu.parentNode){
this.menu.parentNode.removeChild(this.menu);
}
};
ContextMenu.prototype.filterItems = function(itemsToLeave){
this.itemsFilter = itemsToLeave;
};
ContextMenu.SEPARATOR = "---------";
function updateHeight() {
if(this.rootElement[0].className.indexOf('htContextMenu')) {
return;
}
var realSeparatorHeight = 0,
realEntrySize = 0,
dataSize = this.getSettings().data.length;
for(var i = 0; i < dataSize; i++) {
if(this.getSettings().data[i].name == ContextMenu.SEPARATOR) {
realSeparatorHeight += 2;
} else {
realEntrySize += 26;
}
}
this.view.wt.wtScrollbars.vertical.fixedContainer.style.height = realEntrySize + realSeparatorHeight + "px";
}
function init(){
var instance = this;
var contextMenuSetting = instance.getSettings().contextMenu;
var customOptions = Handsontable.helper.isObject(contextMenuSetting) ? contextMenuSetting : {};
if(contextMenuSetting){
if(!instance.contextMenu){
instance.contextMenu = new ContextMenu(instance, customOptions);
}
instance.contextMenu.enable();
if(Handsontable.helper.isArray(contextMenuSetting)){
instance.contextMenu.filterItems(contextMenuSetting);
}
} else if(instance.contextMenu){
instance.contextMenu.destroy();
delete instance.contextMenu;
}
}
Handsontable.hooks.add('afterInit', init);
Handsontable.hooks.add('afterUpdateSettings', init);
Handsontable.hooks.add('afterInit',updateHeight);
if(Handsontable.PluginHooks.register) { //HOT 0.11+
Handsontable.PluginHooks.register('afterContextMenuDefaultOptions');
}
Handsontable.ContextMenu = ContextMenu;
})(Handsontable);
function HandsontableManualColumnMove() {
var pressed
, startCol
, endCol
, startX
, startOffset;
var ghost = document.createElement('DIV')
, ghostStyle = ghost.style;
ghost.className = 'ghost';
ghostStyle.position = 'absolute';
ghostStyle.top = '25px';
ghostStyle.left = 0;
ghostStyle.width = '10px';
ghostStyle.height = '10px';
ghostStyle.backgroundColor = '#CCC';
ghostStyle.opacity = 0.7;
var saveManualColumnPositions = function () {
var instance = this;
Handsontable.hooks.run(instance, 'persistentStateSave', 'manualColumnPositions', instance.manualColumnPositions);
};
var loadManualColumnPositions = function () {
var instance = this;
var storedState = {};
Handsontable.hooks.run(instance, 'persistentStateLoad', 'manualColumnPositions', storedState);
return storedState.value;
};
var bindMoveColEvents = function () {
var instance = this;
instance.rootElement.on('mousemove.manualColumnMove', function (e) {
if (pressed) {
ghostStyle.left = startOffset + e.pageX - startX + 6 + 'px';
if (ghostStyle.display === 'none') {
ghostStyle.display = 'block';
}
}
});
instance.rootElement.on('mouseup.manualColumnMove', function () {
if (pressed) {
if (startCol < endCol) {
endCol--;
}
if (instance.getSettings().rowHeaders) {
startCol--;
endCol--;
}
instance.manualColumnPositions.splice(endCol, 0, instance.manualColumnPositions.splice(startCol, 1)[0]);
$('.manualColumnMover.active').removeClass('active');
pressed = false;
instance.forceFullRender = true;
instance.view.render(); //updates all
ghostStyle.display = 'none';
saveManualColumnPositions.call(instance);
Handsontable.hooks.run(instance, 'afterColumnMove', startCol, endCol);
}
});
instance.rootElement.on('mousedown.manualColumnMove', '.manualColumnMover', function (e) {
var mover = e.currentTarget;
var TH = Handsontable.Dom.closest(mover, 'TH');
startCol = Handsontable.Dom.index(TH) + instance.colOffset();
endCol = startCol;
pressed = true;
startX = e.pageX;
var TABLE = instance.$table[0];
TABLE.parentNode.appendChild(ghost);
ghostStyle.width = Handsontable.Dom.outerWidth(TH) + 'px';
ghostStyle.height = Handsontable.Dom.outerHeight(TABLE) + 'px';
startOffset = parseInt(Handsontable.Dom.offset(TH).left - Handsontable.Dom.offset(TABLE).left, 10);
ghostStyle.left = startOffset + 6 + 'px';
});
instance.rootElement.on('mouseenter.manualColumnMove', 'td, th', function () {
if (pressed) {
var active = instance.view.THEAD.querySelector('.manualColumnMover.active');
if (active) {
Handsontable.Dom.removeClass(active, 'active');
}
endCol = Handsontable.Dom.index(this) + instance.colOffset();
var THs = instance.view.THEAD.querySelectorAll('th');
var mover = THs[endCol].querySelector('.manualColumnMover');
Handsontable.Dom.addClass(mover, 'active');
}
});
instance.addHook('afterDestroy', unbindMoveColEvents);
};
var unbindMoveColEvents = function(){
var instance = this;
instance.rootElement.off('mouseup.manualColumnMove');
instance.rootElement.off('mousemove.manualColumnMove');
instance.rootElement.off('mousedown.manualColumnMove');
instance.rootElement.off('mouseenter.manualColumnMove');
};
this.beforeInit = function () {
this.manualColumnPositions = [];
};
this.init = function (source) {
var instance = this;
var manualColMoveEnabled = !!(this.getSettings().manualColumnMove);
if (manualColMoveEnabled) {
var initialManualColumnPositions = this.getSettings().manualColumnMove;
var loadedManualColumnPositions = loadManualColumnPositions.call(instance);
if (typeof loadedManualColumnPositions != 'undefined') {
this.manualColumnPositions = loadedManualColumnPositions;
} else if (initialManualColumnPositions instanceof Array) {
this.manualColumnPositions = initialManualColumnPositions;
} else {
this.manualColumnPositions = [];
}
instance.forceFullRender = true;
if (source == 'afterInit') {
bindMoveColEvents.call(this);
if (this.manualColumnPositions.length > 0) {
this.forceFullRender = true;
this.render();
}
}
} else {
unbindMoveColEvents.call(this);
this.manualColumnPositions = [];
}
};
this.modifyCol = function (col) {
//TODO test performance: http://jsperf.com/object-wrapper-vs-primitive/2
if (this.getSettings().manualColumnMove) {
if (typeof this.manualColumnPositions[col] === 'undefined') {
this.manualColumnPositions[col] = col;
}
return this.manualColumnPositions[col];
}
return col;
};
this.getColHeader = function (col, TH) {
if (this.getSettings().manualColumnMove) {
var DIV = document.createElement('DIV');
DIV.className = 'manualColumnMover';
TH.firstChild.appendChild(DIV);
}
};
}
var htManualColumnMove = new HandsontableManualColumnMove();
Handsontable.hooks.add('beforeInit', htManualColumnMove.beforeInit);
Handsontable.hooks.add('afterInit', function () {
htManualColumnMove.init.call(this, 'afterInit')
});
Handsontable.hooks.add('afterUpdateSettings', function () {
htManualColumnMove.init.call(this, 'afterUpdateSettings')
});
Handsontable.hooks.add('afterGetColHeader', htManualColumnMove.getColHeader);
Handsontable.hooks.add('modifyCol', htManualColumnMove.modifyCol);
Handsontable.hooks.register('afterColumnMove');
function HandsontableManualColumnResize() {
var pressed
, currentTH
, currentCol
, currentWidth
, instance
, newSize
, startX
, startWidth
, startOffset
, scrollTop = 0
, scrollLeft = 0
, resizer = document.createElement('DIV')
, handle = document.createElement('DIV')
, line = document.createElement('DIV')
, lineStyle = line.style;
resizer.className = 'manualColumnResizer';
handle.className = 'manualColumnResizerHandle';
resizer.appendChild(handle);
line.className = 'manualColumnResizerLine';
resizer.appendChild(line);
var $document = $(document);
$document.mousemove(function (e) {
if (pressed) {
currentWidth = startWidth + (e.pageX - startX);
newSize = setManualSize(currentCol, currentWidth); //save col width
resizer.style.left = startOffset + currentWidth + 'px';
}
});
$document.mouseup(function () {
if (pressed) {
Handsontable.Dom.removeClass(resizer, 'active');
pressed = false;
if(newSize != startWidth){
instance.forceFullRender = true;
instance.view.render(); //updates all
saveManualColumnWidths.call(instance);
Handsontable.hooks.run(instance, 'afterColumnResize', currentCol, newSize);
}
refreshResizerPosition.call(instance, currentTH);
}
});
var saveManualColumnWidths = function () {
var instance = this;
Handsontable.hooks.run(instance, 'persistentStateSave', 'manualColumnWidths', instance.manualColumnWidths);
};
var loadManualColumnWidths = function () {
var instance = this;
var storedState = {};
Handsontable.hooks.run(instance, 'persistentStateLoad', 'manualColumnWidths', storedState);
return storedState.value;
};
function refreshResizerPosition(TH) {
instance = this;
currentTH = TH;
var col = this.view.wt.wtTable.getCoords(TH).col; //getCoords returns WalkontableCellCoords
if (col >= 0) { //if not row header
currentCol = col;
var rootOffset = Handsontable.Dom.offset(this.rootElement[0]).left;
var thOffset = Handsontable.Dom.offset(TH).left;
startOffset = (thOffset - rootOffset) - 6 + scrollLeft;
resizer.style.left = startOffset + parseInt(Handsontable.Dom.outerWidth(TH), 10) + 'px';
resizer.style.top = scrollTop + 'px';
this.rootElement[0].appendChild(resizer);
}
}
function refreshLinePosition() {
var instance = this;
startWidth = parseInt(Handsontable.Dom.outerWidth(currentTH), 10);
Handsontable.Dom.addClass(resizer, 'active');
lineStyle.height = Handsontable.Dom.outerHeight(instance.$table[0]) + 'px';
pressed = instance;
}
var bindManualColumnWidthEvents = function () {
var instance = this;
var dblclick = 0;
var autoresizeTimeout = null;
this.rootElement.on('mouseenter.handsontable', 'table thead tr > th', function (e) {
if (!pressed) {
refreshResizerPosition.call(instance, e.currentTarget);
}
});
this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function () {
if (autoresizeTimeout == null) {
autoresizeTimeout = setTimeout(function () {
if (dblclick >= 2) {
newSize = instance.determineColumnWidth.call(instance, currentCol);
setManualSize(currentCol, newSize);
instance.forceFullRender = true;
instance.view.render(); //updates all
Handsontable.hooks.run(instance, 'afterColumnResize', currentCol, newSize);
}
dblclick = 0;
autoresizeTimeout = null;
}, 500);
}
dblclick++;
});
this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function (e) {
startX = e.pageX;
refreshLinePosition.call(instance);
newSize = startWidth;
});
};
this.beforeInit = function () {
this.manualColumnWidths = [];
};
this.init = function (source) {
var instance = this;
var manualColumnWidthEnabled = !!(this.getSettings().manualColumnResize);
if (manualColumnWidthEnabled) {
var initialColumnWidths = this.getSettings().manualColumnResize;
var loadedManualColumnWidths = loadManualColumnWidths.call(instance);
if (typeof loadedManualColumnWidths != 'undefined') {
this.manualColumnWidths = loadedManualColumnWidths;
} else if (initialColumnWidths instanceof Array) {
this.manualColumnWidths = initialColumnWidths;
} else {
this.manualColumnWidths = [];
}
if (source == 'afterInit') {
bindManualColumnWidthEvents.call(this);
instance.forceFullRender = true;
instance.render();
Handsontable.hooks.add('afterScrollVertically', afterScrollVertically);
Handsontable.hooks.add('afterScrollHorizontally', afterScrollHorizontally);
}
}
};
var setManualSize = function (col, width) {
width = Math.max(width, 20);
/**
* We need to run col through modifyCol hook, in case the order of displayed columns is different than the order
* in data source. For instance, this order can be modified by manualColumnMove plugin.
*/
col = Handsontable.hooks.execute(instance, 'modifyCol', col);
instance.manualColumnWidths[col] = width;
return width;
};
this.modifyColWidth = function (width, col) {
col = this.runHooksAndReturn('modifyCol', col);
if (this.getSettings().manualColumnResize && this.manualColumnWidths[col]) {
return this.manualColumnWidths[col];
}
return width;
};
var afterScrollVertically = function () {
scrollTop = Handsontable.Dom.getScrollTop(this.rootElement[0]);
};
var afterScrollHorizontally = function () {
scrollLeft = Handsontable.Dom.getScrollLeft(this.rootElement[0]);
}
}
var htManualColumnResize = new HandsontableManualColumnResize();
Handsontable.hooks.add('beforeInit', htManualColumnResize.beforeInit);
Handsontable.hooks.add('afterInit', function () {
htManualColumnResize.init.call(this, 'afterInit')
});
Handsontable.hooks.add('afterUpdateSettings', function () {
htManualColumnResize.init.call(this, 'afterUpdateSettings')
});
Handsontable.hooks.add('modifyColWidth', htManualColumnResize.modifyColWidth);
Handsontable.hooks.register('afterColumnResize');
(function (Handsontable) {
function HandsontableManualRowResize () {
var pressed
, currentTH
, currentRow
, currentHeight
, instance
, newSize
, startY
, startHeight
, startOffset
, scrollTop = 0
, scrollLeft = 0
, resizer = document.createElement('DIV')
, handle = document.createElement('DIV')
, line = document.createElement('DIV')
, lineStyle = line.style;
resizer.className = 'manualRowResizer';
handle.className = 'manualRowResizerHandle';
resizer.appendChild(handle);
line.className = 'manualRowResizerLine';
resizer.appendChild(line);
var $document = $(document);
$document.mousemove(function (e) {
if (pressed) {
currentHeight = startHeight + (e.pageY - startY);
newSize = setManualSize(currentRow, currentHeight);
resizer.style.top = startOffset + currentHeight + 'px';
}
});
$document.mouseup(function () {
if (pressed) {
Handsontable.Dom.removeClass(resizer, 'active');
pressed = false;
if (newSize != startHeight) {
instance.forceFullRender = true;
instance.view.render();
saveManualRowHeights.call(instance);
Handsontable.hooks.run(instance, 'afterRowResize', currentRow, newSize);
}
refreshResizerPosition.call(instance, currentTH);
}
});
var saveManualRowHeights = function () {
var instance = this;
Handsontable.hooks.run(instance, 'persistentStateSave', 'manualRowHeights', instance.manualRowHeights);
};
var loadManualRowHeights = function () {
var instance = this
, storedState = {};
Handsontable.hooks.run(instance, 'persistentStateLoad', 'manualRowHeights', storedState);
return storedState.value;
};
var refreshResizerPosition = function(TH) {
instance = this;
currentTH = TH;
var row = this.view.wt.wtTable.getCoords(TH).row; //getCoords returns WalkontableCellCoords
if (row >= 0) { //if not row header
currentRow = row;
var rootOffset = Handsontable.Dom.offset(this.rootElement[0]).top;
var thOffset = Handsontable.Dom.offset(TH).top;
startOffset = (thOffset - rootOffset) + scrollTop - 4;
resizer.style.top = startOffset + parseInt(Handsontable.Dom.outerHeight(TH), 10) + 'px';
resizer.style.left = scrollLeft + 'px';
this.rootElement[0].appendChild(resizer);
}
}
var refreshLinePosition = function() {
var instance = this;
startHeight = parseInt(Handsontable.Dom.outerHeight(currentTH), 10);
Handsontable.Dom.addClass(resizer, 'active');
lineStyle.width = Handsontable.Dom.outerWidth(instance.$table[0]) + 'px';
pressed = instance;
}
var bindManualRowHeightEvents = function () {
var instance = this,
autoresizeTimeout = null,
dblclick = 0;
instance.rootElement.on('mouseenter.handsontable', 'table tbody tr > th', function (e) {
if (!pressed) {
refreshResizerPosition.call(instance, e.currentTarget);
}
});
instance.rootElement.on('mousedown.handsontable', '.manualRowResizer', function () {
if (autoresizeTimeout == null) {
autoresizeTimeout = setTimeout(function () {
if (dblclick >= 2) {
setManualSize(currentRow, null); //double click sets auto row size
instance.forceFullRender = true;
instance.view.render();
Handsontable.hooks.run(instance, 'afterRowResize', currentRow, newSize);
}
dblclick = 0;
autoresizeTimeout = null;
}, 200);
}
dblclick++;
});
instance.rootElement.on('mousedown.handsontable', '.manualRowResizer', function (e) {
startY = e.pageY;
refreshLinePosition.call(instance);
newSize = startHeight;
});
};
this.beforeInit = function () {
this.manualRowHeights = [];
};
this.init = function (source) {
var instance = this;
var manualColumnHeightEnabled = !!(this.getSettings().manualRowResize);
if (manualColumnHeightEnabled) {
var initialRowHeights = this.getSettings().manualRowResize;
var loadedManualRowHeights = loadManualRowHeights.call(instance);
if (typeof loadedManualRowHeights != 'undefined') {
this.manualRowHeights = loadedManualRowHeights;
} else if (initialRowHeights instanceof Array) {
this.manualRowHeights = initialRowHeights;
} else {
this.manualRowHeights = [];
}
if (source === 'afterInit') {
bindManualRowHeightEvents.call(this);
instance.forceFullRender = true;
instance.render();
Handsontable.hooks.add('afterScrollVertically', afterScrollVertically);
Handsontable.hooks.add('afterScrollHorizontally', afterScrollHorizontally);
}
}
};
var setManualSize = function (row, height) {
row = Handsontable.hooks.execute(instance, 'modifyRow', row);
instance.manualRowHeights[row] = height;
return height;
};
this.modifyRowHeight = function (height, row) {
if (this.getSettings().manualRowResize) {
row = this.runHooksAndReturn('modifyRow', row);
if (this.manualRowHeights[row] !== void 0) {
return this.manualRowHeights[row];
}
}
return height;
};
var afterScrollVertically = function () {
scrollTop = Handsontable.Dom.getScrollTop(this.rootElement[0]);
};
var afterScrollHorizontally = function () {
scrollLeft = Handsontable.Dom.getScrollLeft(this.rootElement[0]);
}
}
var htManualRowResize = new HandsontableManualRowResize();
Handsontable.hooks.add('beforeInit', htManualRowResize.beforeInit);
Handsontable.hooks.add('afterInit', function () {
htManualRowResize.init.call(this, 'afterInit');
});
Handsontable.hooks.add('afterUpdateSettings', function () {
htManualRowResize.init.call(this, 'afterUpdateSettings')
});
Handsontable.hooks.add('modifyRowHeight', htManualRowResize.modifyRowHeight);
Handsontable.hooks.register('afterRowResize');
})(Handsontable);
(function HandsontableObserveChanges() {
Handsontable.hooks.add('afterLoadData', init);
Handsontable.hooks.add('afterUpdateSettings', init);
Handsontable.hooks.register('afterChangesObserved');
function init() {
var instance = this;
var pluginEnabled = instance.getSettings().observeChanges;
if (pluginEnabled) {
if(instance.observer) {
destroy.call(instance); //destroy observer for old data object
}
createObserver.call(instance);
bindEvents.call(instance);
} else if (!pluginEnabled){
destroy.call(instance);
}
}
function createObserver(){
var instance = this;
instance.observeChangesActive = true;
instance.pauseObservingChanges = function(){
instance.observeChangesActive = false;
};
instance.resumeObservingChanges = function(){
instance.observeChangesActive = true;
};
instance.observedData = instance.getData();
instance.observer = jsonpatch.observe(instance.observedData, function (patches) {
if(instance.observeChangesActive){
runHookForOperation.call(instance, patches);
instance.render();
}
instance.runHooks('afterChangesObserved');
});
}
function runHookForOperation(rawPatches){
var instance = this;
var patches = cleanPatches(rawPatches);
for(var i = 0, len = patches.length; i < len; i++){
var patch = patches[i];
var parsedPath = parsePath(patch.path);
switch(patch.op){
case 'add':
if(isNaN(parsedPath.col)){
instance.runHooks('afterCreateRow', parsedPath.row);
} else {
instance.runHooks('afterCreateCol', parsedPath.col);
}
break;
case 'remove':
if(isNaN(parsedPath.col)){
instance.runHooks('afterRemoveRow', parsedPath.row, 1);
} else {
instance.runHooks('afterRemoveCol', parsedPath.col, 1);
}
break;
case 'replace':
instance.runHooks('afterChange', [parsedPath.row, parsedPath.col, null, patch.value], 'external');
break;
}
}
function cleanPatches(rawPatches){
var patches;
patches = removeLengthRelatedPatches(rawPatches);
patches = removeMultipleAddOrRemoveColPatches(patches);
return patches;
}
/**
* Removing or adding column will produce one patch for each table row.
* This function leaves only one patch for each column add/remove operation
*/
function removeMultipleAddOrRemoveColPatches(rawPatches){
var newOrRemovedColumns = [];
return rawPatches.filter(function(patch){
var parsedPath = parsePath(patch.path);
if(['add', 'remove'].indexOf(patch.op) != -1 && !isNaN(parsedPath.col)){
if(newOrRemovedColumns.indexOf(parsedPath.col) != -1){
return false;
} else {
newOrRemovedColumns.push(parsedPath.col);
}
}
return true;
});
}
/**
* If observeChanges uses native Object.observe method, then it produces patches for length property.
* This function removes them.
*/
function removeLengthRelatedPatches(rawPatches){
return rawPatches.filter(function(patch){
return !/[/]length/ig.test(patch.path);
})
}
function parsePath(path){
var match = path.match(/^\/(\d+)\/?(.*)?$/);
return {
row: parseInt(match[1], 10),
col: /^\d*$/.test(match[2]) ? parseInt(match[2], 10) : match[2]
}
}
}
function destroy(){
var instance = this;
if (instance.observer){
destroyObserver.call(instance);
unbindEvents.call(instance);
}
}
function destroyObserver(){
var instance = this;
jsonpatch.unobserve(instance.observedData, instance.observer);
delete instance.observeChangesActive;
delete instance.pauseObservingChanges;
delete instance.resumeObservingChanges;
}
function bindEvents(){
var instance = this;
instance.addHook('afterDestroy', destroy);
instance.addHook('afterCreateRow', afterTableAlter);
instance.addHook('afterRemoveRow', afterTableAlter);
instance.addHook('afterCreateCol', afterTableAlter);
instance.addHook('afterRemoveCol', afterTableAlter);
instance.addHook('afterChange', function(changes, source){
if(source != 'loadData'){
afterTableAlter.call(this);
}
});
}
function unbindEvents(){
var instance = this;
instance.removeHook('afterDestroy', destroy);
instance.removeHook('afterCreateRow', afterTableAlter);
instance.removeHook('afterRemoveRow', afterTableAlter);
instance.removeHook('afterCreateCol', afterTableAlter);
instance.removeHook('afterRemoveCol', afterTableAlter);
instance.removeHook('afterChange', afterTableAlter);
}
function afterTableAlter(){
var instance = this;
instance.pauseObservingChanges();
instance.addHookOnce('afterChangesObserved', function(){
instance.resumeObservingChanges();
});
}
})();
/*
*
* Plugin enables saving table state
*
* */
function Storage(prefix) {
var savedKeys;
var saveSavedKeys = function () {
window.localStorage[prefix + '__' + 'persistentStateKeys'] = JSON.stringify(savedKeys);
};
var loadSavedKeys = function () {
var keysJSON = window.localStorage[prefix + '__' + 'persistentStateKeys'];
var keys = typeof keysJSON == 'string' ? JSON.parse(keysJSON) : void 0;
savedKeys = keys ? keys : [];
};
var clearSavedKeys = function () {
savedKeys = [];
saveSavedKeys();
};
loadSavedKeys();
this.saveValue = function (key, value) {
window.localStorage[prefix + '_' + key] = JSON.stringify(value);
if (savedKeys.indexOf(key) == -1) {
savedKeys.push(key);
saveSavedKeys();
}
};
this.loadValue = function (key, defaultValue) {
key = typeof key != 'undefined' ? key : defaultValue;
var value = window.localStorage[prefix + '_' + key];
return typeof value == "undefined" ? void 0 : JSON.parse(value);
};
this.reset = function (key) {
window.localStorage.removeItem(prefix + '_' + key);
};
this.resetAll = function () {
for (var index = 0; index < savedKeys.length; index++) {
window.localStorage.removeItem(prefix + '_' + savedKeys[index]);
}
clearSavedKeys();
};
}
(function (StorageClass) {
function HandsontablePersistentState() {
var plugin = this;
this.init = function () {
var instance = this,
pluginSettings = instance.getSettings()['persistentState'];
plugin.enabled = !!(pluginSettings);
if (!plugin.enabled) {
removeHooks.call(instance);
return;
}
if (!instance.storage) {
instance.storage = new StorageClass(instance.rootElement[0].id);
}
instance.resetState = plugin.resetValue;
addHooks.call(instance);
};
this.saveValue = function (key, value) {
var instance = this;
instance.storage.saveValue(key, value);
};
this.loadValue = function (key, saveTo) {
var instance = this;
saveTo.value = instance.storage.loadValue(key);
};
this.resetValue = function (key) {
var instance = this;
if (typeof key != 'undefined') {
instance.storage.reset(key);
} else {
instance.storage.resetAll();
}
};
var hooks = {
'persistentStateSave': plugin.saveValue,
'persistentStateLoad': plugin.loadValue,
'persistentStateReset': plugin.resetValue
};
for (var hookName in hooks) {
if (hooks.hasOwnProperty(hookName)) {
Handsontable.hooks.register(hookName);
}
}
function addHooks() {
var instance = this;
for (var hookName in hooks) {
if (hooks.hasOwnProperty(hookName)) {
instance.addHook(hookName, hooks[hookName]);
}
}
}
function removeHooks() {
var instance = this;
for (var hookName in hooks) {
if (hooks.hasOwnProperty(hookName)) {
instance.removeHook(hookName, hooks[hookName]);
}
}
}
}
var htPersistentState = new HandsontablePersistentState();
Handsontable.hooks.add('beforeInit', htPersistentState.init);
Handsontable.hooks.add('afterUpdateSettings', htPersistentState.init);
})(Storage);
/**
* Handsontable UndoRedo class
*/
(function(Handsontable){
Handsontable.UndoRedo = function (instance) {
var plugin = this;
this.instance = instance;
this.doneActions = [];
this.undoneActions = [];
this.ignoreNewActions = false;
instance.addHook("afterChange", function (changes, origin) {
if(changes){
var action = new Handsontable.UndoRedo.ChangeAction(changes);
plugin.done(action);
}
});
instance.addHook("afterCreateRow", function (index, amount, createdAutomatically) {
if (createdAutomatically) {
return;
}
var action = new Handsontable.UndoRedo.CreateRowAction(index, amount);
plugin.done(action);
});
instance.addHook("beforeRemoveRow", function (index, amount) {
var originalData = plugin.instance.getData();
index = ( originalData.length + index ) % originalData.length;
var removedData = originalData.slice(index, index + amount);
var action = new Handsontable.UndoRedo.RemoveRowAction(index, removedData);
plugin.done(action);
});
instance.addHook("afterCreateCol", function (index, amount, createdAutomatically) {
if (createdAutomatically) {
return;
}
var action = new Handsontable.UndoRedo.CreateColumnAction(index, amount);
plugin.done(action);
});
instance.addHook("beforeRemoveCol", function (index, amount) {
var originalData = plugin.instance.getData();
index = ( plugin.instance.countCols() + index ) % plugin.instance.countCols();
var removedData = [];
for (var i = 0, len = originalData.length; i < len; i++) {
removedData[i] = originalData[i].slice(index, index + amount);
}
var headers;
if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){
headers = instance.getSettings().colHeaders.slice(index, index + removedData.length);
}
var action = new Handsontable.UndoRedo.RemoveColumnAction(index, removedData, headers);
plugin.done(action);
});
};
Handsontable.UndoRedo.prototype.done = function (action) {
if (!this.ignoreNewActions) {
this.doneActions.push(action);
this.undoneActions.length = 0;
}
};
/**
* Undo operation from current revision
*/
Handsontable.UndoRedo.prototype.undo = function () {
if (this.isUndoAvailable()) {
var action = this.doneActions.pop();
this.ignoreNewActions = true;
var that = this;
action.undo(this.instance, function () {
that.ignoreNewActions = false;
that.undoneActions.push(action);
});
}
};
/**
* Redo operation from current revision
*/
Handsontable.UndoRedo.prototype.redo = function () {
if (this.isRedoAvailable()) {
var action = this.undoneActions.pop();
this.ignoreNewActions = true;
var that = this;
action.redo(this.instance, function () {
that.ignoreNewActions = false;
that.doneActions.push(action);
});
}
};
/**
* Returns true if undo point is available
* @return {Boolean}
*/
Handsontable.UndoRedo.prototype.isUndoAvailable = function () {
return this.doneActions.length > 0;
};
/**
* Returns true if redo point is available
* @return {Boolean}
*/
Handsontable.UndoRedo.prototype.isRedoAvailable = function () {
return this.undoneActions.length > 0;
};
/**
* Clears undo history
*/
Handsontable.UndoRedo.prototype.clear = function () {
this.doneActions.length = 0;
this.undoneActions.length = 0;
};
Handsontable.UndoRedo.Action = function () {
};
Handsontable.UndoRedo.Action.prototype.undo = function () {
};
Handsontable.UndoRedo.Action.prototype.redo = function () {
};
Handsontable.UndoRedo.ChangeAction = function (changes) {
this.changes = changes;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.ChangeAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.ChangeAction.prototype.undo = function (instance, undoneCallback) {
var data = $.extend(true, [], this.changes),
emptyRowsAtTheEnd = instance.countEmptyRows(true),
emptyColsAtTheEnd = instance.countEmptyCols(true);
for (var i = 0, len = data.length; i < len; i++) {
data[i].splice(3, 1);
}
instance.addHookOnce('afterChange', undoneCallback);
instance.setDataAtRowProp(data, null, null, 'undo');
for (var i = 0, len = data.length; i < len; i++) {
if(instance.getSettings().minSpareRows &&
data[i][0] + 1 + instance.getSettings().minSpareRows === instance.countRows()
&& emptyRowsAtTheEnd == instance.getSettings().minSpareRows) {
instance.alter('remove_row', parseInt(data[i][0]+1,10), instance.getSettings().minSpareRows);
instance.undoRedo.doneActions.pop();
}
if (instance.getSettings().minSpareCols &&
data[i][1] + 1 + instance.getSettings().minSpareCols === instance.countCols()
&& emptyColsAtTheEnd == instance.getSettings().minSpareCols) {
instance.alter('remove_col', parseInt(data[i][1]+1,10), instance.getSettings().minSpareCols);
instance.undoRedo.doneActions.pop();
}
}
};
Handsontable.UndoRedo.ChangeAction.prototype.redo = function (instance, onFinishCallback) {
var data = $.extend(true, [], this.changes);
for (var i = 0, len = data.length; i < len; i++) {
data[i].splice(2, 1);
}
instance.addHookOnce('afterChange', onFinishCallback);
instance.setDataAtRowProp(data, null, null, 'redo');
};
Handsontable.UndoRedo.CreateRowAction = function (index, amount) {
this.index = index;
this.amount = amount;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.CreateRowAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.CreateRowAction.prototype.undo = function (instance, undoneCallback) {
instance.addHookOnce('afterRemoveRow', undoneCallback);
instance.alter('remove_row', this.index, this.amount);
};
Handsontable.UndoRedo.CreateRowAction.prototype.redo = function (instance, redoneCallback) {
instance.addHookOnce('afterCreateRow', redoneCallback);
instance.alter('insert_row', this.index + 1, this.amount);
};
Handsontable.UndoRedo.RemoveRowAction = function (index, data) {
this.index = index;
this.data = data;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveRowAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.RemoveRowAction.prototype.undo = function (instance, undoneCallback) {
var spliceArgs = [this.index, 0];
Array.prototype.push.apply(spliceArgs, this.data);
Array.prototype.splice.apply(instance.getData(), spliceArgs);
instance.addHookOnce('afterRender', undoneCallback);
instance.render();
};
Handsontable.UndoRedo.RemoveRowAction.prototype.redo = function (instance, redoneCallback) {
instance.addHookOnce('afterRemoveRow', redoneCallback);
instance.alter('remove_row', this.index, this.data.length);
};
Handsontable.UndoRedo.CreateColumnAction = function (index, amount) {
this.index = index;
this.amount = amount;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.CreateColumnAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.CreateColumnAction.prototype.undo = function (instance, undoneCallback) {
instance.addHookOnce('afterRemoveCol', undoneCallback);
instance.alter('remove_col', this.index, this.amount);
};
Handsontable.UndoRedo.CreateColumnAction.prototype.redo = function (instance, redoneCallback) {
instance.addHookOnce('afterCreateCol', redoneCallback);
instance.alter('insert_col', this.index + 1, this.amount);
};
Handsontable.UndoRedo.RemoveColumnAction = function (index, data, headers) {
this.index = index;
this.data = data;
this.amount = this.data[0].length;
this.headers = headers;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveColumnAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.RemoveColumnAction.prototype.undo = function (instance, undoneCallback) {
var row, spliceArgs;
for (var i = 0, len = instance.getData().length; i < len; i++) {
row = instance.getDataAtRow(i);
spliceArgs = [this.index, 0];
Array.prototype.push.apply(spliceArgs, this.data[i]);
Array.prototype.splice.apply(row, spliceArgs);
}
if(typeof this.headers != 'undefined'){
spliceArgs = [this.index, 0];
Array.prototype.push.apply(spliceArgs, this.headers);
Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArgs);
}
instance.addHookOnce('afterRender', undoneCallback);
instance.render();
};
Handsontable.UndoRedo.RemoveColumnAction.prototype.redo = function (instance, redoneCallback) {
instance.addHookOnce('afterRemoveCol', redoneCallback);
instance.alter('remove_col', this.index, this.amount);
};
})(Handsontable);
(function(Handsontable){
function init(){
var instance = this;
var pluginEnabled = typeof instance.getSettings().undo == 'undefined' || instance.getSettings().undo;
if(pluginEnabled){
if(!instance.undoRedo){
instance.undoRedo = new Handsontable.UndoRedo(instance);
exposeUndoRedoMethods(instance);
instance.addHook('beforeKeyDown', onBeforeKeyDown);
instance.addHook('afterChange', onAfterChange);
}
} else {
if(instance.undoRedo){
delete instance.undoRedo;
removeExposedUndoRedoMethods(instance);
instance.removeHook('beforeKeyDown', onBeforeKeyDown);
instance.removeHook('afterChange', onAfterChange);
}
}
}
function onBeforeKeyDown(event){
var instance = this;
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey;
if(ctrlDown){
if (event.keyCode === 89 || (event.shiftKey && event.keyCode === 90)) { //CTRL + Y or CTRL + SHIFT + Z
instance.undoRedo.redo();
event.stopImmediatePropagation();
}
else if (event.keyCode === 90) { //CTRL + Z
instance.undoRedo.undo();
event.stopImmediatePropagation();
}
}
}
function onAfterChange(changes, source){
var instance = this;
if (source == 'loadData'){
return instance.undoRedo.clear();
}
}
function exposeUndoRedoMethods(instance){
instance.undo = function(){
return instance.undoRedo.undo();
};
instance.redo = function(){
return instance.undoRedo.redo();
};
instance.isUndoAvailable = function(){
return instance.undoRedo.isUndoAvailable();
};
instance.isRedoAvailable = function(){
return instance.undoRedo.isRedoAvailable();
};
instance.clearUndo = function(){
return instance.undoRedo.clear();
};
}
function removeExposedUndoRedoMethods(instance){
delete instance.undo;
delete instance.redo;
delete instance.isUndoAvailable;
delete instance.isRedoAvailable;
delete instance.clearUndo;
}
Handsontable.hooks.add('afterInit', init);
Handsontable.hooks.add('afterUpdateSettings', init);
})(Handsontable);
/**
* Plugin used to scroll Handsontable by selecting a cell and dragging outside of visible viewport
* @constructor
*/
function DragToScroll() {
this.boundaries = null;
this.callback = null;
}
/**
* @param boundaries {Object} compatible with getBoundingClientRect
*/
DragToScroll.prototype.setBoundaries = function (boundaries) {
this.boundaries = boundaries;
};
/**
* @param callback {Function}
*/
DragToScroll.prototype.setCallback = function (callback) {
this.callback = callback;
};
/**
* Check if mouse position (x, y) is outside of the viewport
* @param x
* @param y
*/
DragToScroll.prototype.check = function (x, y) {
var diffX = 0;
var diffY = 0;
if (y < this.boundaries.top) {
//y is less than top
diffY = y - this.boundaries.top;
}
else if (y > this.boundaries.bottom) {
//y is more than bottom
diffY = y - this.boundaries.bottom;
}
if (x < this.boundaries.left) {
//x is less than left
diffX = x - this.boundaries.left;
}
else if (x > this.boundaries.right) {
//x is more than right
diffX = x - this.boundaries.right;
}
this.callback(diffX, diffY);
};
var dragToScroll;
var instance;
if (typeof Handsontable !== 'undefined') {
var setupListening = function (instance) {
instance.dragToScrollListening = false;
var scrollHandler = instance.view.wt.wtScrollbars.vertical.scrollHandler; //native scroll
dragToScroll = new DragToScroll();
if (scrollHandler === window) {
//not much we can do currently
return;
}
else if (scrollHandler) {
dragToScroll.setBoundaries(scrollHandler.getBoundingClientRect());
}
else {
dragToScroll.setBoundaries(instance.$table[0].getBoundingClientRect());
}
dragToScroll.setCallback(function (scrollX, scrollY) {
if (scrollX < 0) {
if (scrollHandler) {
scrollHandler.scrollLeft -= 50;
}
else {
instance.view.wt.scrollHorizontal(-1).draw();
}
}
else if (scrollX > 0) {
if (scrollHandler) {
scrollHandler.scrollLeft += 50;
}
else {
instance.view.wt.scrollHorizontal(1).draw();
}
}
if (scrollY < 0) {
if (scrollHandler) {
scrollHandler.scrollTop -= 20;
}
else {
instance.view.wt.scrollVertical(-1).draw();
}
}
else if (scrollY > 0) {
if (scrollHandler) {
scrollHandler.scrollTop += 20;
}
else {
instance.view.wt.scrollVertical(1).draw();
}
}
});
instance.dragToScrollListening = true;
};
Handsontable.hooks.add('afterInit', function () {
var instance = this;
$(document).on('mouseup.' + this.guid, function () {
instance.dragToScrollListening = false;
});
$(document).on('mousemove.' + this.guid, function (event) {
if (instance.dragToScrollListening) {
dragToScroll.check(event.clientX, event.clientY);
}
});
});
Handsontable.hooks.add('afterDestroy', function () {
$(document).off('.' + this.guid);
});
Handsontable.hooks.add('afterOnCellMouseDown', function () {
setupListening(this);
});
Handsontable.hooks.add('afterOnCellCornerMouseDown', function () {
setupListening(this);
});
Handsontable.plugins.DragToScroll = DragToScroll;
}
(function (Handsontable, CopyPaste, SheetClip) {
function CopyPastePlugin(instance) {
this.copyPasteInstance = CopyPaste.getInstance();
this.copyPasteInstance.onCut(onCut);
this.copyPasteInstance.onPaste(onPaste);
var plugin = this;
instance.addHook('beforeKeyDown', onBeforeKeyDown);
function onCut() {
if (!instance.isListening()) {
return;
}
instance.selection.empty();
}
function onPaste(str) {
if (!instance.isListening() || !instance.selection.isSelected()) {
return;
}
var input = str.replace(/^[\r\n]*/g, '').replace(/[\r\n]*$/g, '') //remove newline from the start and the end of the input
, inputArray = SheetClip.parse(input)
, selected = instance.getSelected()
, coordsFrom = new WalkontableCellCoords(selected[0], selected[1])
, coordsTo = new WalkontableCellCoords(selected[2], selected[3])
, cellRange = new WalkontableCellRange(coordsFrom, coordsFrom, coordsTo)
, topLeftCorner = cellRange.getTopLeftCorner()
, bottomRightCorner = cellRange.getBottomRightCorner()
, areaStart = topLeftCorner
, areaEnd = new WalkontableCellCoords(
Math.max(bottomRightCorner.row, inputArray.length - 1 + topLeftCorner.row),
Math.max(bottomRightCorner.col, inputArray[0].length - 1 + topLeftCorner.col)
);
instance.addHookOnce('afterChange', function (changes, source) {
if (changes && changes.length) {
this.selectCell(areaStart.row, areaStart.col, areaEnd.row, areaEnd.col);
}
});
instance.populateFromArray(areaStart.row, areaStart.col, inputArray, areaEnd.row, areaEnd.col, 'paste', instance.getSettings().pasteMode);
};
function onBeforeKeyDown (event) {
if (Handsontable.helper.isCtrlKey(event.keyCode) && instance.getSelected()) {
//when CTRL is pressed, prepare selectable text in textarea
//http://stackoverflow.com/questions/3902635/how-does-one-capture-a-macs-command-key-via-javascript
plugin.setCopyableText();
event.stopImmediatePropagation();
return;
}
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
if (event.keyCode == Handsontable.helper.keyCode.A && ctrlDown) {
setTimeout(Handsontable.helper.proxy(plugin.setCopyableText, plugin));
}
}
this.destroy = function () {
this.copyPasteInstance.removeCallback(onCut);
this.copyPasteInstance.removeCallback(onPaste);
this.copyPasteInstance.destroy();
instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
instance.addHook('afterDestroy', Handsontable.helper.proxy(this.destroy, this));
this.triggerPaste = Handsontable.helper.proxy(this.copyPasteInstance.triggerPaste, this.copyPasteInstance);
this.triggerCut = Handsontable.helper.proxy(this.copyPasteInstance.triggerCut, this.copyPasteInstance);
/**
* Prepares copyable text in the invisible textarea
*/
this.setCopyableText = function () {
var settings = instance.getSettings();
var copyRowsLimit = settings.copyRowsLimit;
var copyColsLimit = settings.copyColsLimit;
var selRange = instance.getSelectedRange();
var topLeft = selRange.getTopLeftCorner();
var bottomRight = selRange.getBottomRightCorner();
var startRow = topLeft.row;
var startCol = topLeft.col;
var endRow = bottomRight.row;
var endCol = bottomRight.col;
var finalEndRow = Math.min(endRow, startRow + copyRowsLimit - 1);
var finalEndCol = Math.min(endCol, startCol + copyColsLimit - 1);
instance.copyPaste.copyPasteInstance.copyable(instance.getCopyableData(startRow, startCol, finalEndRow, finalEndCol));
if (endRow !== finalEndRow || endCol !== finalEndCol) {
Handsontable.hooks.run(instance, "afterCopyLimit", endRow - startRow + 1, endCol - startCol + 1, copyRowsLimit, copyColsLimit);
}
};
}
function init() {
var instance = this;
var pluginEnabled = instance.getSettings().copyPaste !== false;
if(pluginEnabled && !instance.copyPaste){
instance.copyPaste = new CopyPastePlugin(instance);
} else if (!pluginEnabled && instance.copyPaste) {
instance.copyPaste.destroy();
delete instance.copyPaste;
}
}
Handsontable.hooks.add('afterInit', init);
Handsontable.hooks.add('afterUpdateSettings', init);
Handsontable.hooks.register('afterCopyLimit');
})(Handsontable, CopyPaste, SheetClip);
(function (Handsontable) {
'use strict';
Handsontable.Search = function Search(instance) {
this.query = function (queryStr, callback, queryMethod) {
var rowCount = instance.countRows();
var colCount = instance.countCols();
var queryResult = [];
if (!callback) {
callback = Handsontable.Search.global.getDefaultCallback();
}
if (!queryMethod) {
queryMethod = Handsontable.Search.global.getDefaultQueryMethod();
}
for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) {
for (var colIndex = 0; colIndex < colCount; colIndex++) {
var cellData = instance.getDataAtCell(rowIndex, colIndex);
var cellProperties = instance.getCellMeta(rowIndex, colIndex);
var cellCallback = cellProperties.search.callback || callback;
var cellQueryMethod = cellProperties.search.queryMethod || queryMethod;
var testResult = cellQueryMethod(queryStr, cellData);
if (testResult) {
var singleResult = {
row: rowIndex,
col: colIndex,
data: cellData
};
queryResult.push(singleResult);
}
if (cellCallback) {
cellCallback(instance, rowIndex, colIndex, cellData, testResult);
}
}
}
return queryResult;
};
};
Handsontable.Search.DEFAULT_CALLBACK = function (instance, row, col, data, testResult) {
instance.getCellMeta(row, col).isSearchResult = testResult;
};
Handsontable.Search.DEFAULT_QUERY_METHOD = function (query, value) {
if (typeof query == 'undefined' || query == null || !query.toLowerCase || query.length == 0){
return false;
}
return value.toString().toLowerCase().indexOf(query.toLowerCase()) != -1;
};
Handsontable.Search.DEFAULT_SEARCH_RESULT_CLASS = 'htSearchResult';
Handsontable.Search.global = (function () {
var defaultCallback = Handsontable.Search.DEFAULT_CALLBACK;
var defaultQueryMethod = Handsontable.Search.DEFAULT_QUERY_METHOD;
var defaultSearchResultClass = Handsontable.Search.DEFAULT_SEARCH_RESULT_CLASS;
return {
getDefaultCallback: function () {
return defaultCallback;
},
setDefaultCallback: function (newDefaultCallback) {
defaultCallback = newDefaultCallback;
},
getDefaultQueryMethod: function () {
return defaultQueryMethod;
},
setDefaultQueryMethod: function (newDefaultQueryMethod) {
defaultQueryMethod = newDefaultQueryMethod;
},
getDefaultSearchResultClass: function () {
return defaultSearchResultClass;
},
setDefaultSearchResultClass: function (newSearchResultClass) {
defaultSearchResultClass = newSearchResultClass;
}
}
})();
Handsontable.SearchCellDecorator = function (instance, TD, row, col, prop, value, cellProperties) {
var searchResultClass = (typeof cellProperties.search == 'object' && cellProperties.search.searchResultClass) || Handsontable.Search.global.getDefaultSearchResultClass();
if(cellProperties.isSearchResult){
Handsontable.Dom.addClass(TD, searchResultClass);
} else {
Handsontable.Dom.removeClass(TD, searchResultClass);
}
};
var originalDecorator = Handsontable.renderers.cellDecorator;
Handsontable.renderers.cellDecorator = function (instance, TD, row, col, prop, value, cellProperties) {
originalDecorator.apply(this, arguments);
Handsontable.SearchCellDecorator.apply(this, arguments);
};
function init() {
var instance = this;
var pluginEnabled = !!instance.getSettings().search;
if (pluginEnabled) {
instance.search = new Handsontable.Search(instance);
} else {
delete instance.search;
}
}
Handsontable.hooks.add('afterInit', init);
Handsontable.hooks.add('afterUpdateSettings', init);
})(Handsontable);
function CellInfoCollection() {
var collection = [];
collection.getInfo = function (row, col) {
for (var i = 0, ilen = this.length; i < ilen; i++) {
if (this[i].row <= row && this[i].row + this[i].rowspan - 1 >= row && this[i].col <= col && this[i].col + this[i].colspan - 1 >= col) {
return this[i];
}
}
};
collection.setInfo = function (info) {
for (var i = 0, ilen = this.length; i < ilen; i++) {
if (this[i].row === info.row && this[i].col === info.col) {
this[i] = info;
return;
}
}
this.push(info);
};
collection.removeInfo = function (row, col) {
for (var i = 0, ilen = this.length; i < ilen; i++) {
if (this[i].row === row && this[i].col === col) {
this.splice(i, 1);
break;
}
}
};
return collection;
}
/**
* Plugin used to merge cells in Handsontable
* @constructor
*/
function MergeCells(mergeCellsSetting) {
this.mergedCellInfoCollection = new CellInfoCollection();
if (Handsontable.helper.isArray(mergeCellsSetting)) {
for (var i = 0, ilen = mergeCellsSetting.length; i < ilen; i++) {
this.mergedCellInfoCollection.setInfo(mergeCellsSetting[i]);
}
}
}
/**
* @param cellRange (WalkontableCellRange)
*/
MergeCells.prototype.canMergeRange = function (cellRange) {
//is more than one cell selected
return !cellRange.isSingle();
};
MergeCells.prototype.mergeRange = function (cellRange) {
if (!this.canMergeRange(cellRange)) {
return;
}
//normalize top left corner
var topLeft = cellRange.getTopLeftCorner();
var bottomRight = cellRange.getBottomRightCorner();
var mergeParent = {};
mergeParent.row = topLeft.row;
mergeParent.col = topLeft.col;
mergeParent.rowspan = bottomRight.row - topLeft.row + 1; //TD has rowspan == 1 by default. rowspan == 2 means spread over 2 cells
mergeParent.colspan = bottomRight.col - topLeft.col + 1;
this.mergedCellInfoCollection.setInfo(mergeParent);
};
MergeCells.prototype.mergeOrUnmergeSelection = function (cellRange) {
var info = this.mergedCellInfoCollection.getInfo(cellRange.from.row, cellRange.from.col);
if (info) {
//unmerge
this.unmergeSelection(cellRange.from);
}
else {
//merge
this.mergeSelection(cellRange);
}
};
MergeCells.prototype.mergeSelection = function (cellRange) {
this.mergeRange(cellRange);
};
MergeCells.prototype.unmergeSelection = function (cellRange) {
var info = this.mergedCellInfoCollection.getInfo(cellRange.row, cellRange.col);
this.mergedCellInfoCollection.removeInfo(info.row, info.col);
};
MergeCells.prototype.applySpanProperties = function (TD, row, col) {
var info = this.mergedCellInfoCollection.getInfo(row, col);
if (info) {
if (info.row === row && info.col === col) {
TD.setAttribute('rowspan', info.rowspan);
TD.setAttribute('colspan', info.colspan);
}
else {
TD.style.display = "none";
}
}
else {
TD.removeAttribute('rowspan');
TD.removeAttribute('colspan');
}
};
MergeCells.prototype.modifyTransform = function (hook, currentSelectedRange, delta) {
var current;
switch (hook) {
case 'modifyTransformStart':
current = currentSelectedRange.highlight;
break;
case 'modifyTransformEnd':
current = currentSelectedRange.to;
break;
}
if (hook == "modifyTransformStart") {
//in future - can this take the logic from modifyTransformEnd?
var mergeParent = this.mergedCellInfoCollection.getInfo(current.row + delta.row, current.col + delta.col);
if (mergeParent) {
if (current.row > mergeParent.row) { //entering merge by going up or left
this.lastDesiredCoords = new WalkontableCellCoords(current.row + delta.row, current.col + delta.col); //copy
delta.row += (mergeParent.row - current.row) - delta.row;
}
else if (current.row == mergeParent.row && delta.row > 0) { //leaving merge by going down
delta.row += mergeParent.row - current.row + mergeParent.rowspan - 1;
}
else { //leaving merge by going right
if (this.lastDesiredCoords && delta.row === 0) {
delta.row += this.lastDesiredCoords.row - current.row;
this.lastDesiredCoords = null;
}
}
if (current.col > mergeParent.col) { //entering merge by going up or left
if (!this.lastDesiredCoords) {
this.lastDesiredCoords = new WalkontableCellCoords(current.row + delta.row, current.col + delta.col); //copy
}
delta.col += (mergeParent.col - current.col) - delta.col;
}
else if (current.col == mergeParent.col && delta.col > 0) { //leaving merge by going right
delta.col += mergeParent.col - current.col + mergeParent.colspan - 1;
}
else { //leaving merge by going down
if (this.lastDesiredCoords && delta.col === 0) {
delta.col += this.lastDesiredCoords.col - current.col;
this.lastDesiredCoords = null;
}
}
}
else {
if (this.lastDesiredCoords) {
if (delta.col == 0) { //leaving merge by going up
delta.col += this.lastDesiredCoords.col - current.col;
}
else if (delta.row == 0) { //leaving merge by going left
delta.row += this.lastDesiredCoords.row - current.row;
}
this.lastDesiredCoords = null;
}
}
}
else {
//modify transform end
var hightlightMergeParent = this.mergedCellInfoCollection.getInfo(currentSelectedRange.highlight.row, currentSelectedRange.highlight.col);
if (hightlightMergeParent) {
if (currentSelectedRange.isSingle()) {
currentSelectedRange.from = new WalkontableCellCoords(hightlightMergeParent.row, hightlightMergeParent.col);
currentSelectedRange.to = new WalkontableCellCoords(hightlightMergeParent.row + hightlightMergeParent.rowspan - 1, hightlightMergeParent.col + hightlightMergeParent.colspan - 1);
}
}
if (currentSelectedRange.isSingle()) {
//make sure objects are clones but not reference to the same instance
//because we will mutate them
currentSelectedRange.from = new WalkontableCellCoords(currentSelectedRange.highlight.row, currentSelectedRange.highlight.col);
currentSelectedRange.to = new WalkontableCellCoords(currentSelectedRange.highlight.row, currentSelectedRange.highlight.col);
}
var solveDimension = function (dim) {
var altDim = dim == "col" ? "row" : "col";
function changeCoords(obj, altDimValue, dimValue) {
obj[altDim] = altDimValue;
obj[dim] = dimValue;
}
if (delta[dim] != 0) {
var topLeft;
var bottomRight;
var updateCornerInfo = function () {
topLeft = currentSelectedRange.getTopLeftCorner();
bottomRight = currentSelectedRange.getBottomRightCorner();
}
updateCornerInfo();
var expanding = false; //expanding false means shrinking
var examinedCol;
//now check if maybe we are expanding?
if (delta[dim] < 0) {
examinedCol = bottomRight[dim] + delta[dim];
if (bottomRight[dim] == currentSelectedRange.highlight[dim]) {
examinedCol = topLeft[dim] + delta[dim];
expanding = true;
}
else {
for (var i = topLeft[altDim]; i <= bottomRight[altDim]; i++) {
var mergeParent = this.mergedCellInfoCollection.getInfo(i, bottomRight[dim]);
if (mergeParent) {
if (mergeParent[dim] <= currentSelectedRange.highlight[dim]) {
examinedCol = topLeft[dim] + delta[dim];
expanding = true;
break;
}
}
}
}
}
else if (delta[dim] > 0) {
examinedCol = topLeft[dim] + delta[dim];
if (topLeft[dim] == currentSelectedRange.highlight[dim]) {
examinedCol = bottomRight[dim] + delta[dim];
expanding = true;
}
else {
for (var i = topLeft[altDim]; i <= bottomRight[altDim]; i++) {
var mergeParent = this.mergedCellInfoCollection.getInfo(i, topLeft[dim]);
if (mergeParent) {
if (mergeParent[dim] + mergeParent[dim + "span"] > currentSelectedRange.highlight[dim]) {
examinedCol = bottomRight[dim] + delta[dim];
expanding = true;
break;
}
}
}
}
}
if (expanding) {
if (delta[dim] > 0) { //moving East wall further East
changeCoords(currentSelectedRange.from, topLeft[altDim], topLeft[dim]);
changeCoords(currentSelectedRange.to, bottomRight[altDim], Math.max(bottomRight[dim], examinedCol));
updateCornerInfo();
}
else { //moving West wall further West
changeCoords(currentSelectedRange.from, topLeft[altDim], Math.min(topLeft[dim], examinedCol));
changeCoords(currentSelectedRange.to, bottomRight[altDim], bottomRight[dim]);
updateCornerInfo();
}
}
else {
if (delta[dim] > 0) { //shrinking West wall towards East
changeCoords(currentSelectedRange.from, topLeft[altDim], Math.max(topLeft[dim], examinedCol));
changeCoords(currentSelectedRange.to, bottomRight[altDim], bottomRight[dim]);
updateCornerInfo();
}
else { //shrinking East wall towards West
changeCoords(currentSelectedRange.from, topLeft[altDim], topLeft[dim]);
changeCoords(currentSelectedRange.to, bottomRight[altDim], Math.min(bottomRight[dim], examinedCol));
updateCornerInfo();
}
}
for (var i = topLeft[altDim]; i <= bottomRight[altDim]; i++) {
var mergeParent = dim == "col" ? this.mergedCellInfoCollection.getInfo(i, examinedCol) : this.mergedCellInfoCollection.getInfo(examinedCol, i);
if (mergeParent) {
if (expanding) {
if (delta[dim] > 0) { //moving East wall further East
changeCoords(currentSelectedRange.from, Math.min(topLeft[altDim], mergeParent[altDim]), Math.min(topLeft[dim], mergeParent[dim]));
if (examinedCol > mergeParent[dim]) {
changeCoords(currentSelectedRange.to, Math.max(bottomRight[altDim], mergeParent[altDim] + mergeParent[altDim + "span"] - 1), Math.max(bottomRight[dim], mergeParent[dim] + mergeParent[dim + "span"]));
}
else {
changeCoords(currentSelectedRange.to, Math.max(bottomRight[altDim], mergeParent[altDim] + mergeParent[altDim + "span"] - 1), Math.max(bottomRight[dim], mergeParent[dim] + mergeParent[dim + "span"] - 1));
}
updateCornerInfo();
}
else { //moving West wall further West
changeCoords(currentSelectedRange.from, Math.min(topLeft[altDim], mergeParent[altDim]), Math.min(topLeft[dim], mergeParent[dim]));
changeCoords(currentSelectedRange.to, Math.max(bottomRight[altDim], mergeParent[altDim] + mergeParent[altDim + "span"] - 1), Math.max(bottomRight[dim], mergeParent[dim] + mergeParent[dim + "span"] - 1));
updateCornerInfo();
}
}
else {
if (delta[dim] > 0) { //shrinking West wall towards East
if (examinedCol > mergeParent[dim]) {
changeCoords(currentSelectedRange.from, topLeft[altDim], Math.max(topLeft[dim], mergeParent[dim] + mergeParent[dim + "span"]));
changeCoords(currentSelectedRange.to, bottomRight[altDim], Math.max(bottomRight[dim], mergeParent[dim] + mergeParent[dim + "span"]));
}
else {
changeCoords(currentSelectedRange.from, topLeft[altDim], Math.max(topLeft[dim], mergeParent[dim]));
changeCoords(currentSelectedRange.to, bottomRight[altDim], Math.max(bottomRight[dim], mergeParent[dim] + mergeParent[dim + "span"] - 1));
}
updateCornerInfo();
}
else { //shrinking East wall towards West
if (examinedCol < mergeParent[dim] + mergeParent[dim + "span"] - 1) {
changeCoords(currentSelectedRange.from, topLeft[altDim], Math.min(topLeft[dim], mergeParent[dim] - 1));
changeCoords(currentSelectedRange.to, bottomRight[altDim], Math.min(bottomRight[dim], mergeParent[dim] - 1));
}
else {
changeCoords(currentSelectedRange.from, topLeft[altDim], Math.min(topLeft[dim], mergeParent[dim]));
changeCoords(currentSelectedRange.to, bottomRight[altDim], Math.min(bottomRight[dim], mergeParent[dim] + mergeParent[dim + "span"]));
}
updateCornerInfo();
}
}
}
}
/*if (expanding) {
//check if corners are not part of merged cells as well
var oneLastCheck = function (row, col) {
var mergeParent = this.mergedCellInfoCollection.getInfo(row, col);
if (mergeParent) {
currentSelectedRange.expand(new WalkontableCellCoords(mergeParent.row, mergeParent.col));
currentSelectedRange.expand(new WalkontableCellCoords(mergeParent.row + mergeParent.rowspan - 1, mergeParent.col + mergeParent.colspan - 1));
updateCornerInfo();
}
}
oneLastCheck.call(this, topLeft.row, topLeft.col);
oneLastCheck.call(this, topLeft.row, bottomRight.col);
oneLastCheck.call(this, bottomRight.row, bottomRight.col);
oneLastCheck.call(this, bottomRight.row, topLeft.col);
}
else {
//TODO there is still a glitch if you go to merge_cells.html, go to D5 and press up, right, down
}*/
}
};
solveDimension.call(this, "col");
solveDimension.call(this, "row");
delta.row = 0;
delta.col = 0;
}
};
if (typeof Handsontable == 'undefined') {
throw new Error('Handsontable is not defined');
}
var init = function () {
var instance = this;
var mergeCellsSetting = instance.getSettings().mergeCells;
if (mergeCellsSetting) {
if (!instance.mergeCells) {
instance.mergeCells = new MergeCells(mergeCellsSetting);
}
}
};
var onBeforeKeyDown = function (event) {
if (!this.mergeCells) {
return;
}
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey;
if (ctrlDown) {
if (event.keyCode === 77) { //CTRL + M
this.mergeCells.mergeOrUnmergeSelection(this.getSelectedRange());
this.render();
event.stopImmediatePropagation();
}
}
};
var addMergeActionsToContextMenu = function (defaultOptions) {
if (!this.getSettings().mergeCells) {
return;
}
defaultOptions.items.mergeCellsSeparator = Handsontable.ContextMenu.SEPARATOR;
defaultOptions.items.mergeCells = {
name: function () {
var sel = this.getSelected();
var info = this.mergeCells.mergedCellInfoCollection.getInfo(sel[0], sel[1]);
if (info) {
return 'Unmerge cells';
}
else {
return 'Merge cells';
}
},
callback: function () {
this.mergeCells.mergeOrUnmergeSelection(this.getSelectedRange());
this.render();
},
disabled: function () {
return false;
}
};
};
var afterRenderer = function (TD, row, col, prop, value, cellProperties) {
if (this.mergeCells) {
this.mergeCells.applySpanProperties(TD, row, col);
}
};
var modifyTransformFactory = function (hook) {
return function (delta) {
var mergeCellsSetting = this.getSettings().mergeCells;
if (mergeCellsSetting) {
var currentSelectedRange = this.getSelectedRange();
this.mergeCells.modifyTransform(hook, currentSelectedRange, delta);
if (hook === "modifyTransformEnd") {
//sanitize "from" (core.js will sanitize to)
var totalRows = this.countRows();
var totalCols = this.countCols();
if (currentSelectedRange.from.row < 0) {
currentSelectedRange.from.row = 0;
}
else if (currentSelectedRange.from.row > 0 && currentSelectedRange.from.row >= totalRows) {
currentSelectedRange.from.row = currentSelectedRange.from - 1;
}
if (currentSelectedRange.from.col < 0) {
currentSelectedRange.from.col = 0;
}
else if (currentSelectedRange.from.col > 0 && currentSelectedRange.from.col >= totalCols) {
currentSelectedRange.from.col = totalCols - 1;
}
}
}
}
};
/**
* While selecting cells with keyboard or mouse, make sure that rectangular area is expanded to the extent of the merged cell
* @param coords
*/
var beforeSetRangeEnd = function (coords) {
this.lastDesiredCoords = null; //unset lastDesiredCoords when selection is changed with mouse
var mergeCellsSetting = this.getSettings().mergeCells;
if (mergeCellsSetting) {
var selRange = this.getSelectedRange();
selRange.highlight = new WalkontableCellCoords(selRange.highlight.row, selRange.highlight.col); //clone in case we will modify its reference
selRange.to = coords;
for (var i = 0, ilen = this.mergeCells.mergedCellInfoCollection.length; i < ilen; i++) {
var cellInfo = this.mergeCells.mergedCellInfoCollection[i];
var mergedCellTopLeft = new WalkontableCellCoords(cellInfo.row, cellInfo.col);
var mergedCellBottomRight = new WalkontableCellCoords(cellInfo.row + cellInfo.rowspan - 1, cellInfo.col + cellInfo.colspan - 1);
var mergedCellRange = new WalkontableCellRange(mergedCellTopLeft, mergedCellTopLeft, mergedCellBottomRight);
if (selRange.expandByRange(mergedCellRange)) {
var selRangeBottomRight = selRange.getBottomRightCorner();
coords.row = selRangeBottomRight.row;
coords.col = selRangeBottomRight.col;
}
}
}
};
var afterGetCellMeta = function(row, col, cellProperties) {
var mergeCellsSetting = this.getSettings().mergeCells;
if (mergeCellsSetting) {
var mergeParent = this.mergeCells.mergedCellInfoCollection.getInfo(row, col);
if(mergeParent && (mergeParent.row != row || mergeParent.col != col)) {
cellProperties.copyable = false;
}
}
};
Handsontable.hooks.add('beforeInit', init);
Handsontable.hooks.add('beforeKeyDown', onBeforeKeyDown);
Handsontable.hooks.add('modifyTransformStart', modifyTransformFactory('modifyTransformStart'));
Handsontable.hooks.add('modifyTransformEnd', modifyTransformFactory('modifyTransformEnd'));
Handsontable.hooks.add('beforeSetRangeEnd', beforeSetRangeEnd);
Handsontable.hooks.add('afterRenderer', afterRenderer);
Handsontable.hooks.add('afterContextMenuDefaultOptions', addMergeActionsToContextMenu);
Handsontable.hooks.add('afterGetCellMeta', afterGetCellMeta);
Handsontable.MergeCells = MergeCells;
/**
* Creates an overlay over the original Walkontable instance. The overlay renders the clone of the original Walkontable
* and (optionally) implements behavior needed for native horizontal and vertical scrolling
*/
function WalkontableOverlay() {}
/*
Possible optimizations:
[x] don't rerender if scroll delta is smaller than the fragment outside of the viewport
[ ] move .style.top change before .draw()
[ ] put .draw() in requestAnimationFrame
[ ] don't rerender rows that remain visible after the scroll
*/
WalkontableOverlay.prototype.init = function () {
this.TABLE = this.instance.wtTable.TABLE;
this.fixed = this.instance.wtTable.hider;
this.fixedContainer = this.instance.wtTable.holder;
// this.fixed.style.position = 'absolute';
// this.fixed.style.left = '0';
this.scrollHandler = this.getScrollableElement(this.TABLE);
this.$scrollHandler = $(this.scrollHandler); //in future remove jQuery from here
};
WalkontableOverlay.prototype.makeClone = function (direction) {
var clone = document.createElement('DIV');
clone.className = 'ht_clone_' + direction + ' handsontable';
clone.style.position = 'fixed';
clone.style.overflow = 'hidden';
var table2 = document.createElement('TABLE');
table2.className = this.instance.wtTable.TABLE.className;
clone.appendChild(table2);
this.instance.wtTable.holder.parentNode.appendChild(clone);
return new Walkontable({
cloneSource: this.instance,
cloneOverlay: this,
table: table2
});
};
WalkontableOverlay.prototype.getScrollableElement = function (TABLE) {
var el = TABLE.parentNode;
while (el && el.style) {
if (el.style.overflow !== 'visible' && el.style.overflow !== '') {
return el;
}
if (this instanceof WalkontableHorizontalScrollbarNative && el.style.overflowX !== 'visible' && el.style.overflowX !== '') {
return el;
}
el = el.parentNode;
}
return window;
};
WalkontableOverlay.prototype.prepare = function () {
};
WalkontableOverlay.prototype.onScroll = function () {
this.windowScrollPosition = this.getScrollPosition();
this.readSettings(); //read window scroll position
this.resetFixedPosition(); //may be redundant
};
WalkontableOverlay.prototype.availableSize = function () {
var availableSize;
if (this.windowScrollPosition > this.tableParentOffset /*&& last > -1*/) { //last -1 means that viewport is scrolled behind the table
if (this.instance.wtTable.getLastVisibleRow() === this.total - 1) {
availableSize = Handsontable.Dom.outerHeight(this.TABLE);
}
else {
availableSize = this.windowSize;
}
}
else {
availableSize = this.windowSize - (this.tableParentOffset);
}
return availableSize;
};
WalkontableOverlay.prototype.refresh = function (selectionsOnly) {
var last = this.getLastCell();
this.measureBefore = this.sumCellSizes(0, this.offset);
if (last === -1) { //last -1 means that viewport is scrolled behind the table
this.measureAfter = 0;
}
else {
this.measureAfter = this.sumCellSizes(last, this.total - last);
}
this.applyToDOM();
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableOverlay.prototype.destroy = function () {
this.$scrollHandler.off('.' + this.clone.guid);
$(window).off('.' + this.clone.guid);
$(document).off('.' + this.clone.guid);
$(document.body).off('.' + this.clone.guid);
};
/**
* WalkontableAbstractFilter (WalkontableColumnFilter and WalkontableRowFilter inherit from this)
* @constructor
*/
function WalkontableAbstractFilter() {
this.offset = 0;
this.total = 0;
this.fixedCount = 0;
}
WalkontableAbstractFilter.prototype.offsetted = function (n) {
return n + this.offset;
};
WalkontableAbstractFilter.prototype.unOffsetted = function (n) {
return n - this.offset;
};
WalkontableAbstractFilter.prototype.fixed = function (n) {
if (n < this.fixedCount) {
return n - this.offset;
}
else {
return n;
}
};
WalkontableAbstractFilter.prototype.unFixed = function (n) {
if (n < this.fixedCount) {
return n + this.offset;
}
else {
return n;
}
};
WalkontableAbstractFilter.prototype.visibleToSource = function (n) {
return this.offsetted(this.fixed(n));
};
WalkontableAbstractFilter.prototype.sourceToVisible = function (n) {
return this.unOffsetted(this.unFixed(n));
};
/**
* WalkontableAbstractStrategy (WalkontableColumnStrategy and WalkontableRowStrategy inherit from this)
* @constructor
*/
function WalkontableAbstractStrategy(instance) {
this.instance = instance;
}
WalkontableAbstractStrategy.prototype.getSize = function (index) {
return this.cellSizes[index];
};
WalkontableAbstractStrategy.prototype.getContainerSize = function (proposedSize) {
return typeof this.containerSizeFn === 'function' ? this.containerSizeFn(proposedSize) : this.containerSizeFn;
};
WalkontableAbstractStrategy.prototype.countVisible = function () {
return this.cellCount;
};
WalkontableAbstractStrategy.prototype.isLastIncomplete = function () {
return this.remainingSize > 0;
};
function WalkontableBorder(instance, settings) {
var style;
//reference to instance
this.instance = instance;
this.settings = settings;
this.main = document.createElement("div");
style = this.main.style;
style.position = 'absolute';
style.top = 0;
style.left = 0;
for (var i = 0; i < 5; i++) {
var DIV = document.createElement('DIV');
DIV.className = 'wtBorder ' + (settings.className || '');
style = DIV.style;
style.backgroundColor = settings.border.color;
style.height = settings.border.width + 'px';
style.width = settings.border.width + 'px';
this.main.appendChild(DIV);
}
this.top = this.main.childNodes[0];
this.left = this.main.childNodes[1];
this.bottom = this.main.childNodes[2];
this.right = this.main.childNodes[3];
this.topStyle = this.top.style;
this.leftStyle = this.left.style;
this.bottomStyle = this.bottom.style;
this.rightStyle = this.right.style;
this.corner = this.main.childNodes[4];
this.corner.className += ' corner';
this.cornerStyle = this.corner.style;
this.cornerStyle.width = '5px';
this.cornerStyle.height = '5px';
this.cornerStyle.border = '2px solid #FFF';
this.disappear();
if (!instance.wtTable.bordersHolder) {
instance.wtTable.bordersHolder = document.createElement('div');
instance.wtTable.bordersHolder.className = 'htBorders';
instance.wtTable.hider.appendChild(instance.wtTable.bordersHolder);
}
instance.wtTable.bordersHolder.appendChild(this.main);
var down = false;
var $body = $(document.body);
$body.on('mousedown.walkontable.' + instance.guid, function () {
down = true;
});
$body.on('mouseup.walkontable.' + instance.guid, function () {
down = false
});
$(this.main.childNodes).on('mouseenter', function (event) {
if (!down || !instance.getSetting('hideBorderOnMouseDownOver')) {
return;
}
event.preventDefault();
event.stopImmediatePropagation();
var bounds = this.getBoundingClientRect();
var $this = $(this);
$this.hide();
var isOutside = function (event) {
if (event.clientY < Math.floor(bounds.top)) {
return true;
}
if (event.clientY > Math.ceil(bounds.top + bounds.height)) {
return true;
}
if (event.clientX < Math.floor(bounds.left)) {
return true;
}
if (event.clientX > Math.ceil(bounds.left + bounds.width)) {
return true;
}
};
$body.on('mousemove.border.' + instance.guid, function (event) {
if (isOutside(event)) {
$body.off('mousemove.border.' + instance.guid);
$this.show();
}
});
});
}
/**
* Show border around one or many cells
* @param {Array} corners
*/
WalkontableBorder.prototype.appear = function (corners) {
var isMultiple, fromTD, toTD, fromOffset, toOffset, containerOffset, top, minTop, left, minLeft, height, width;
if (this.disabled) {
return;
}
var instance = this.instance;
var fromRow
, fromColumn
, toRow
, toColumn
, hideTop = false
, hideLeft = false
, hideBottom = false
, hideRight = false
, i
, ilen
, s;
if (!instance.wtTable.isRowInViewport(corners[0])) {
hideTop = true;
}
if (!instance.wtTable.isRowInViewport(corners[2])) {
hideBottom = true;
}
if (instance.cloneOverlay instanceof WalkontableVerticalScrollbarNative || instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) {
ilen = instance.getSetting('fixedRowsTop');
}
else {
ilen = instance.wtTable.getRowStrategy().countVisible();
}
for (i = 0; i < ilen; i++) {
s = instance.wtTable.rowFilter.visibleToSource(i);
if (s >= corners[0] && s <= corners[2]) {
fromRow = s;
break;
}
}
for (i = ilen - 1; i >= 0; i--) {
s = instance.wtTable.rowFilter.visibleToSource(i);
if (s >= corners[0] && s <= corners[2]) {
toRow = s;
break;
}
}
if (hideTop && hideBottom) {
hideLeft = true;
hideRight = true;
}
else {
if (!instance.wtTable.isColumnInViewport(corners[1])) {
hideLeft = true;
}
if (!instance.wtTable.isColumnInViewport(corners[3])) {
hideRight = true;
}
if (instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) {
ilen = instance.getSetting('fixedColumnsLeft');
}
else {
ilen = instance.wtTable.getColumnStrategy().cellCount;
}
for (i = 0; i < ilen; i++) {
s = instance.wtTable.columnFilter.visibleToSource(i);
if (s >= corners[1] && s <= corners[3]) {
fromColumn = s;
break;
}
}
for (i = ilen - 1; i >= 0; i--) {
s = instance.wtTable.columnFilter.visibleToSource(i);
if (s >= corners[1] && s <= corners[3]) {
toColumn = s;
break;
}
}
}
if (fromRow !== void 0 && fromColumn !== void 0) {
isMultiple = (fromRow !== toRow || fromColumn !== toColumn);
fromTD = instance.wtTable.getCell(new WalkontableCellCoords(fromRow, fromColumn));
toTD = isMultiple ? instance.wtTable.getCell(new WalkontableCellCoords(toRow, toColumn)) : fromTD;
fromOffset = Handsontable.Dom.offset(fromTD);
toOffset = isMultiple ? Handsontable.Dom.offset(toTD) : fromOffset;
containerOffset = Handsontable.Dom.offset(instance.wtTable.TABLE);
minTop = fromOffset.top;
height = toOffset.top + Handsontable.Dom.outerHeight(toTD) - minTop;
minLeft = fromOffset.left;
width = toOffset.left + Handsontable.Dom.outerWidth(toTD) - minLeft;
top = minTop - containerOffset.top - 1;
left = minLeft - containerOffset.left - 1;
var style = Handsontable.Dom.getComputedStyle(fromTD);
if (parseInt(style['borderTopWidth'], 10) > 0) {
top += 1;
height = height > 0 ? height - 1 : 0;
}
if (parseInt(style['borderLeftWidth'], 10) > 0) {
left += 1;
width = width > 0 ? width - 1 : 0;
}
}
else {
this.disappear();
return;
}
if (hideTop) {
this.topStyle.display = 'none';
}
else {
this.topStyle.top = top + 'px';
this.topStyle.left = left + 'px';
this.topStyle.width = width + 'px';
this.topStyle.display = 'block';
}
if (hideLeft) {
this.leftStyle.display = 'none';
}
else {
this.leftStyle.top = top + 'px';
this.leftStyle.left = left + 'px';
this.leftStyle.height = height + 'px';
this.leftStyle.display = 'block';
}
var delta = Math.floor(this.settings.border.width / 2);
if (hideBottom) {
this.bottomStyle.display = 'none';
}
else {
this.bottomStyle.top = top + height - delta + 'px';
this.bottomStyle.left = left + 'px';
this.bottomStyle.width = width + 'px';
this.bottomStyle.display = 'block';
}
if (hideRight) {
this.rightStyle.display = 'none';
}
else {
this.rightStyle.top = top + 'px';
this.rightStyle.left = left + width - delta + 'px';
this.rightStyle.height = height + 1 + 'px';
this.rightStyle.display = 'block';
}
if (hideBottom || hideRight || !this.hasSetting(this.settings.border.cornerVisible)) {
this.cornerStyle.display = 'none';
}
else {
this.cornerStyle.top = top + height - 4 + 'px';
this.cornerStyle.left = left + width - 4 + 'px';
this.cornerStyle.display = 'block';
}
};
/**
* Hide border
*/
WalkontableBorder.prototype.disappear = function () {
this.topStyle.display = 'none';
this.leftStyle.display = 'none';
this.bottomStyle.display = 'none';
this.rightStyle.display = 'none';
this.cornerStyle.display = 'none';
};
WalkontableBorder.prototype.hasSetting = function (setting) {
if (typeof setting === 'function') {
return setting();
}
return !!setting;
};
/**
* WalkontableCellCoords holds cell coordinates (row, column) and few metiod to validate them and retrieve as an array or an object
* TODO: change interface to WalkontableCellCoords(row, col) everywhere, remove those unnecessary setter and getter functions
*/
function WalkontableCellCoords(row, col) {
if (typeof row !== 'undefined' && typeof col !== 'undefined') {
this.row = row;
this.col = col;
}
else {
this.row = null;
this.col = null;
}
}
/**
* Returns boolean information if given set of coordinates is valid in context of a given Walkontable instance
* @param instance
* @returns {boolean}
*/
WalkontableCellCoords.prototype.isValid = function (instance) {
//is it a valid cell index (0 or higher)
if (this.row < 0 || this.col < 0) {
return false;
}
//is selection within total rows and columns
if (this.row >= instance.getSetting('totalRows') || this.col >= instance.getSetting('totalColumns')) {
return false;
}
return true;
};
/**
* Returns boolean information if this cell coords are the same as cell coords given as a parameter
* @param {WalkontableCellCoords} cellCoords
* @returns {boolean}
*/
WalkontableCellCoords.prototype.isEqual = function (cellCoords) {
if (cellCoords === this) {
return true;
}
return (this.row === cellCoords.row && this.col === cellCoords.col);
};
WalkontableCellCoords.prototype.isSouthEastOf = function (testedCoords) {
return this.row >= testedCoords.row && this.col >= testedCoords.col;
};
WalkontableCellCoords.prototype.isNorthWestOf = function (testedCoords) {
return this.row <= testedCoords.row && this.col <= testedCoords.col;
};
window.WalkontableCellCoords = WalkontableCellCoords; //export
/**
* A cell range is a set of exactly two WalkontableCellCoords (that can be the same or different)
*/
function WalkontableCellRange(highlight, from, to) {
this.highlight = highlight; //this property is used to draw bold border around a cell where selection was started and to edit the cell when you press Enter
this.from = from; //this property is usually the same as highlight, but in Excel there is distinction - one can change highlight within a selection
this.to = to;
}
WalkontableCellRange.prototype.isValid = function (instance) {
return (this.from.isValid(instance) && this.to.isValid(instance));
};
WalkontableCellRange.prototype.isSingle = function () {
return (this.from.row === this.to.row && this.from.col === this.to.col);
};
/**
* Returns boolean information if given cell coords is within `from` and `to` cell coords of this range
* @param {WalkontableCellCoords} cellCoords
* @returns {boolean}
*/
WalkontableCellRange.prototype.includes = function (cellCoords) {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
return (topLeft.row <= cellCoords.row && bottomRight.row >= cellCoords.row && topLeft.col <= cellCoords.col && bottomRight.col >= cellCoords.col);
};
WalkontableCellRange.prototype.includesRange = function (testedRange) {
return this.includes(testedRange.getTopLeftCorner()) && this.includes(testedRange.getBottomRightCorner());
};
/**
* Returns true if tested range overlaps with the range.
* Range A is considered to to be overlapping with range B if intersection of A and B or B and A is not empty.
* @param testedRange
* @returns {boolean}
*/
WalkontableCellRange.prototype.overlaps = function (testedRange) {
return testedRange.isSouthEastOf(this.getTopLeftCorner()) && testedRange.isNorthWestOf(this.getBottomRightCorner());
};
WalkontableCellRange.prototype.isSouthEastOf = function (testedCoords) {
return this.getTopLeftCorner().isSouthEastOf(testedCoords) || this.getBottomRightCorner().isSouthEastOf(testedCoords);
};
WalkontableCellRange.prototype.isNorthWestOf = function (testedCoords) {
return this.getTopLeftCorner().isNorthWestOf(testedCoords) || this.getBottomRightCorner().isNorthWestOf(testedCoords);
};
/**
* Adds a cell to a range (only if exceeds corners of the range). Returns information if range was expanded
* @param {WalkontableCellCoords} cellCoords
* @returns {boolean}
*/
WalkontableCellRange.prototype.expand = function (cellCoords) {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
if (cellCoords.row < topLeft.row || cellCoords.col < topLeft.col || cellCoords.row > bottomRight.row || cellCoords.col > bottomRight.col) {
this.from = new WalkontableCellCoords(Math.min(topLeft.row, cellCoords.row), Math.min(topLeft.col, cellCoords.col));
this.to = new WalkontableCellCoords(Math.max(bottomRight.row, cellCoords.row), Math.max(bottomRight.col, cellCoords.col));
return true;
}
return false;
};
WalkontableCellRange.prototype.expandByRange = function (expandingRange) {
if (this.includesRange(expandingRange) || !this.overlaps(expandingRange)){
return false;
}
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
var expandingTopLeft = expandingRange.getTopLeftCorner();
var expandingBottomRight = expandingRange.getBottomRightCorner();
var resultTopRow = Math.min(topLeft.row, expandingTopLeft.row);
var resultTopCol = Math.min(topLeft.col, expandingTopLeft.col);
var resultBottomRow = Math.max(bottomRight.row, expandingBottomRight.row);
var resultBottomCol = Math.max(bottomRight.col, expandingBottomRight.col);
this.from = new WalkontableCellCoords(resultTopRow, resultTopCol);
this.to = new WalkontableCellCoords(resultBottomRow, resultBottomCol);
return true;
};
WalkontableCellRange.prototype.getTopLeftCorner = function () {
return new WalkontableCellCoords(Math.min(this.from.row, this.to.row), Math.min(this.from.col, this.to.col));
};
WalkontableCellRange.prototype.getBottomRightCorner = function () {
return new WalkontableCellCoords(Math.max(this.from.row, this.to.row), Math.max(this.from.col, this.to.col));
};
WalkontableCellRange.prototype.getInner = function () {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
var out = [];
for (var r = topLeft.row; r <= bottomRight.row; r++) {
for (var c = topLeft.col; c <= bottomRight.col; c++) {
if (!(this.from.row === r && this.from.col === c) && !(this.to.row === r && this.to.col === c)) {
out.push(new WalkontableCellCoords(r, c));
}
}
}
return out;
};
WalkontableCellRange.prototype.getAll = function () {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
var out = [];
for (var r = topLeft.row; r <= bottomRight.row; r++) {
for (var c = topLeft.col; c <= bottomRight.col; c++) {
if (topLeft.row === r && topLeft.col === c) {
out.push(topLeft);
}
else if (bottomRight.row === r && bottomRight.col === c) {
out.push(bottomRight);
}
else {
out.push(new WalkontableCellCoords(r, c));
}
}
}
return out;
};
/**
* Runs a callback function against all cells in the range. You can break the iteration by returning false in the callback function
* @param callback {Function}
*/
WalkontableCellRange.prototype.forAll = function (callback) {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
for (var r = topLeft.row; r <= bottomRight.row; r++) {
for (var c = topLeft.col; c <= bottomRight.col; c++) {
var breakIteration = callback(r, c);
if (breakIteration === false) {
return;
}
}
}
};
window.WalkontableCellRange = WalkontableCellRange; //export
/**
* WalkontableClassNameList
* @constructor
*/
function WalkontableClassNameCache() {
this.cache = [];
}
WalkontableClassNameCache.prototype.add = function (r, c, cls) {
if (!this.cache[r]) {
this.cache[r] = [];
}
if (!this.cache[r][c]) {
this.cache[r][c] = [];
}
this.cache[r][c][cls] = true;
};
WalkontableClassNameCache.prototype.test = function (r, c, cls) {
return (this.cache[r] && this.cache[r][c] && this.cache[r][c][cls]);
};
/**
* WalkontableColumnFilter
* @constructor
*/
function WalkontableColumnFilter(offset, total, fixedCount, countTH) {
this.offset = offset;
this.total = total;
this.fixedCount = fixedCount;
this.countTH = countTH;
}
WalkontableColumnFilter.prototype = new WalkontableAbstractFilter();
WalkontableColumnFilter.prototype.offsettedTH = function (n) {
return n - this.countTH;
};
WalkontableColumnFilter.prototype.unOffsettedTH = function (n) {
return n + this.countTH;
};
WalkontableColumnFilter.prototype.visibleRowHeadedColumnToSourceColumn = function (n) {
return this.visibleToSource(this.offsettedTH(n));
};
WalkontableColumnFilter.prototype.sourceColumnToVisibleRowHeadedColumn = function (n) {
return this.unOffsettedTH(this.sourceToVisible(n));
};
/**
* WalkontableColumnStrategy
* @param containerSizeFn
* @param sizeAtIndex
* @param strategy - all, last, none
* @constructor
*/
function WalkontableColumnStrategy(instance, containerSizeFn, sizeAtIndex, strategy) {
var size
, i = 0;
WalkontableAbstractStrategy.apply(this, arguments);
this.containerSizeFn = containerSizeFn;
this.cellSizesSum = 0;
this.cellSizes = [];
this.cellStretch = [];
this.cellCount = 0;
this.visibleCellCount = 0;
this.remainingSize = 0;
this.strategy = strategy;
//step 1 - determine cells that fit containerSize and cache their widths
while (true) {
size = sizeAtIndex(i);
if (size === void 0) {
break; //total columns exceeded
}
if (this.cellSizesSum < this.getContainerSize(this.cellSizesSum + size)) {
this.visibleCellCount++;
}
this.cellSizes.push(size);
this.cellSizesSum += size;
this.cellCount++;
i++;
}
var containerSize = this.getContainerSize(this.cellSizesSum);
this.remainingSize = this.cellSizesSum - containerSize;
//negative value means the last cell is fully visible and there is some space left for stretching
//positive value means the last cell is not fully visible
}
WalkontableColumnStrategy.prototype = new WalkontableAbstractStrategy();
WalkontableColumnStrategy.prototype.getSize = function (index) {
return this.cellSizes[index] + (this.cellStretch[index] || 0);
};
WalkontableColumnStrategy.prototype.stretch = function () {
//step 2 - apply stretching strategy
var containerSize
, i = 0;
containerSize = this.instance.wtTable.allRowsInViewport() ? this.getContainerSize() : this.getContainerSize(Infinity);
this.remainingSize = this.cellSizesSum - containerSize;
this.cellStretch.length = 0; //clear previous stretch
if (this.strategy === 'all') {
if (this.remainingSize < 0) {
var ratio = containerSize / this.cellSizesSum;
var newSize;
while (i < this.cellCount - 1) { //"i < this.cellCount - 1" is needed because last cellSize is adjusted after the loop
newSize = Math.floor(ratio * this.cellSizes[i]);
this.remainingSize += newSize - this.cellSizes[i];
this.cellStretch[i] = newSize - this.cellSizes[i];
i++;
}
this.cellStretch[this.cellCount - 1] = -this.remainingSize;
this.remainingSize = 0;
}
}
else if (this.strategy === 'last') {
if (this.remainingSize < 0 && containerSize !== Infinity) { //Infinity is with native scroll when the table is wider than the viewport (TODO: test)
this.cellStretch[this.cellCount - 1] = -this.remainingSize;
this.remainingSize = 0;
}
}
};
WalkontableColumnStrategy.prototype.countVisible = function () {
return this.visibleCellCount;
};
WalkontableColumnStrategy.prototype.isLastIncomplete = function () {
var firstRow = this.instance.wtTable.getFirstVisibleRow();
var lastCol = this.instance.wtTable.getLastVisibleColumn();
var cell = this.instance.wtTable.getCell(new WalkontableCellCoords(firstRow, lastCol));
var cellOffset = Handsontable.Dom.offset(cell);
var cellWidth = Handsontable.Dom.outerWidth(cell);
var cellEnd = cellOffset.left + cellWidth;
var viewportOffsetLeft = this.instance.wtScrollbars.vertical.getScrollPosition();
var viewportWitdh = this.instance.wtViewport.getViewportWidth();
var viewportEnd = viewportOffsetLeft + viewportWitdh;
return viewportEnd >= cellEnd;
};
function Walkontable(settings) {
var originalHeaders = [];
this.guid = 'wt_' + walkontableRandomString(); //this is the namespace for global events
//bootstrap from settings
if (settings.cloneSource) {
this.cloneSource = settings.cloneSource;
this.cloneOverlay = settings.cloneOverlay;
this.wtSettings = settings.cloneSource.wtSettings;
this.wtTable = new WalkontableTable(this, settings.table);
this.wtScroll = new WalkontableScroll(this);
this.wtViewport = settings.cloneSource.wtViewport;
this.wtEvent = new WalkontableEvent(this);
this.selections = this.cloneSource.selections.makeClone(this);
}
else {
this.wtSettings = new WalkontableSettings(this, settings);
this.wtTable = new WalkontableTable(this, settings.table);
this.wtScroll = new WalkontableScroll(this);
this.wtViewport = new WalkontableViewport(this);
this.wtEvent = new WalkontableEvent(this);
this.selections = new WalkontableSelections(this, this.getSetting('selections'));
this.wtScrollbars = new WalkontableScrollbars(this);
}
//find original headers
if (this.wtTable.THEAD.childNodes.length && this.wtTable.THEAD.childNodes[0].childNodes.length) {
for (var c = 0, clen = this.wtTable.THEAD.childNodes[0].childNodes.length; c < clen; c++) {
originalHeaders.push(this.wtTable.THEAD.childNodes[0].childNodes[c].innerHTML);
}
if (!this.getSetting('columnHeaders').length) {
this.update('columnHeaders', [function (column, TH) {
Handsontable.Dom.fastInnerText(TH, originalHeaders[column]);
}]);
}
}
this.drawn = false;
this.drawInterrupted = false;
}
Walkontable.prototype.draw = function (selectionsOnly) {
this.drawInterrupted = false;
if (!selectionsOnly && !Handsontable.Dom.isVisible(this.wtTable.TABLE)) {
this.drawInterrupted = true; //draw interrupted because TABLE is not visible
return;
}
selectionsOnly = selectionsOnly && this.getSetting('offsetRow') === this.lastOffsetRow && this.getSetting('offsetColumn') === this.lastOffsetColumn;
this.lastOffsetRow = this.getSetting('offsetRow');
this.lastOffsetColumn = this.getSetting('offsetColumn');
var totalRows = this.getSetting('totalRows');
if (this.lastOffsetRow > totalRows && totalRows > 0) {
this.scrollVertical(-Infinity); //TODO: probably very inefficient!
this.scrollViewport(new WalkontableCellCoords(totalRows - 1, 0));
}
this.wtTable.draw(selectionsOnly);
return this;
};
Walkontable.prototype.update = function (settings, value) {
return this.wtSettings.update(settings, value);
};
Walkontable.prototype.scrollVertical = function (delta) {
var result = this.wtScroll.scrollVertical(delta);
this.getSetting('onScrollVertically');
return result;
};
Walkontable.prototype.scrollHorizontal = function (delta) {
var result = this.wtScroll.scrollHorizontal(delta);
this.getSetting('onScrollHorizontally');
return result;
};
/**
* Scrolls the viewport to a cell (rerenders if needed)
* @param {WalkontableCellCoords} coords
* @returns {Walkontable}
*/
Walkontable.prototype.scrollViewport = function (coords) {
this.wtScroll.scrollViewport(coords);
return this;
};
Walkontable.prototype.getViewport = function () {
return [
this.wtTable.getFirstVisibleRow(),
this.wtTable.getFirstVisibleColumn(),
this.wtTable.getLastVisibleRow(),
this.wtTable.getLastVisibleColumn()
];
};
Walkontable.prototype.getSetting = function (key, param1, param2, param3, param4) {
return this.wtSettings.getSetting(key, param1, param2, param3, param4); //this is faster than .apply - https://github.com/handsontable/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
};
Walkontable.prototype.hasSetting = function (key) {
return this.wtSettings.has(key);
};
Walkontable.prototype.destroy = function () {
$(window).off('.' + this.guid);
$(document.body).off('.' + this.guid);
this.wtScrollbars.destroy();
this.wtEvent && this.wtEvent.destroy();
};
/**
* A overlay that renders ALL available rows & columns positioned on top of the original Walkontable instance and all other overlays.
* Used for debugging purposes to see if the other overlays (that render only part of the rows & columns) are positioned correctly
* @param instance
* @constructor
*/
function WalkontableDebugOverlay(instance) {
this.instance = instance;
this.init();
this.clone = this.makeClone('debug');
this.clone.wtTable.holder.style.opacity = 0.4;
this.clone.wtTable.holder.style.textShadow = '0 0 2px #ff0000';
var that = this;
var lastTimeout;
var lastX = 0;
var lastY = 0;
var overlayContainer = that.clone.wtTable.holder.parentNode;
$(document.body).on('mousemove.' + this.instance.guid, function (event) {
if (!that.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
if ((event.clientX - lastX > -5 && event.clientX - lastX < 5) && (event.clientY - lastY > -5 && event.clientY - lastY < 5)) {
return; //ignore minor mouse movement
}
lastX = event.clientX;
lastY = event.clientY;
Handsontable.Dom.addClass(overlayContainer, 'wtDebugHidden');
Handsontable.Dom.removeClass(overlayContainer, 'wtDebugVisible');
clearTimeout(lastTimeout);
lastTimeout = setTimeout(function () {
Handsontable.Dom.removeClass(overlayContainer, 'wtDebugHidden');
Handsontable.Dom.addClass(overlayContainer, 'wtDebugVisible');
}, 1000);
});
}
WalkontableDebugOverlay.prototype = new WalkontableOverlay();
WalkontableDebugOverlay.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box = this.instance.wtTable.holder.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
};
WalkontableDebugOverlay.prototype.prepare = function () {
};
WalkontableDebugOverlay.prototype.refresh = function (selectionsOnly) {
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableDebugOverlay.prototype.getScrollPosition = function () {
};
WalkontableDebugOverlay.prototype.getLastCell = function () {
};
WalkontableDebugOverlay.prototype.applyToDOM = function () {
};
WalkontableDebugOverlay.prototype.scrollTo = function () {
};
WalkontableDebugOverlay.prototype.readWindowSize = function () {
};
WalkontableDebugOverlay.prototype.readSettings = function () {
};
function WalkontableEvent(instance) {
var that = this;
//reference to instance
this.instance = instance;
var dblClickOrigin = [null, null];
var dblClickTimeout = [null, null];
var onMouseDown = function (event) {
var cell = that.parentCell(event.target);
if (Handsontable.Dom.hasClass(event.target, 'corner')) {
that.instance.getSetting('onCellCornerMouseDown', event, event.target);
}
else if (cell.TD){
// if(cell.TD.nodeName == 'TD' || cell.TD.nodeName == 'TH'){
if (that.instance.hasSetting('onCellMouseDown')) {
that.instance.getSetting('onCellMouseDown', event, cell.coords, cell.TD, that.instance);
}
// }
}
if (event.button !== 2) { //if not right mouse button
// if (cell.TD && cell.TD.nodeName === 'TD') {
if (cell.TD) {
dblClickOrigin[0] = cell.TD;
clearTimeout(dblClickTimeout[0]);
dblClickTimeout[0] = setTimeout(function () {
dblClickOrigin[0] = null;
}, 1000);
}
}
};
var lastMouseOver;
var onMouseOver = function (event) {
if (that.instance.hasSetting('onCellMouseOver')) {
var TABLE = that.instance.wtTable.TABLE;
var TD = Handsontable.Dom.closest(event.target, ['TD', 'TH'], TABLE);
if (TD && TD !== lastMouseOver && Handsontable.Dom.isChildOf(TD, TABLE)) {
lastMouseOver = TD;
if (TD.nodeName === 'TD') {
that.instance.getSetting('onCellMouseOver', event, that.instance.wtTable.getCoords(TD), TD, that.instance);
}
}
}
};
/* var lastMouseOut;
var onMouseOut = function (event) {
if (that.instance.hasSetting('onCellMouseOut')) {
var TABLE = that.instance.wtTable.TABLE;
var TD = Handsontable.Dom.closest(event.target, ['TD', 'TH'], TABLE);
if (TD && TD !== lastMouseOut && Handsontable.Dom.isChildOf(TD, TABLE)) {
lastMouseOut = TD;
if (TD.nodeName === 'TD') {
that.instance.getSetting('onCellMouseOut', event, that.instance.wtTable.getCoords(TD), TD);
}
}
}
};*/
var onMouseUp = function (event) {
if (event.button !== 2) { //if not right mouse button
var cell = that.parentCell(event.target);
if (cell.TD === dblClickOrigin[0] && cell.TD === dblClickOrigin[1]) {
if (Handsontable.Dom.hasClass(event.target, 'corner')) {
that.instance.getSetting('onCellCornerDblClick', event, cell.coords, cell.TD, that.instance);
}
// else if (cell.TD) {
else {
that.instance.getSetting('onCellDblClick', event, cell.coords, cell.TD, that.instance);
}
dblClickOrigin[0] = null;
dblClickOrigin[1] = null;
}
else if (cell.TD === dblClickOrigin[0]) {
dblClickOrigin[1] = cell.TD;
clearTimeout(dblClickTimeout[1]);
dblClickTimeout[1] = setTimeout(function () {
dblClickOrigin[1] = null;
}, 500);
}
}
};
$(this.instance.wtTable.holder).on('mousedown', onMouseDown);
$(this.instance.wtTable.TABLE).on('mouseover', onMouseOver);
$(this.instance.wtTable.holder).on('mouseup', onMouseUp);
}
WalkontableEvent.prototype.parentCell = function (elem) {
var cell = {};
var TABLE = this.instance.wtTable.TABLE;
var TD = Handsontable.Dom.closest(elem, ['TD', 'TH'], TABLE);
if (TD && Handsontable.Dom.isChildOf(TD, TABLE)) {
cell.coords = this.instance.wtTable.getCoords(TD);
cell.TD = TD;
}
else if (Handsontable.Dom.hasClass(elem, 'wtBorder') && Handsontable.Dom.hasClass(elem, 'current')) {
cell.coords = this.instance.selections.current.cellRange.highlight;
cell.TD = this.instance.wtTable.getCell(cell.coords);
}
return cell;
};
WalkontableEvent.prototype.destroy = function () {
clearTimeout(this.dblClickTimeout0);
clearTimeout(this.dblClickTimeout1);
};
function walkontableRangesIntersect() {
var from = arguments[0];
var to = arguments[1];
for (var i = 1, ilen = arguments.length / 2; i < ilen; i++) {
if (from <= arguments[2 * i + 1] && to >= arguments[2 * i]) {
return true;
}
}
return false;
}
/**
* Generates a random hex string. Used as namespace for Walkontable instance events.
* @return {String} - 16 character random string: "92b1bfc74ec4"
*/
function walkontableRandomString() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + s4() + s4();
}
/**
* http://notes.jetienne.com/2011/05/18/cancelRequestAnimFrame-for-paul-irish-requestAnimFrame.html
*/
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (/* function */ callback, /* DOMElement */ element) {
return window.setTimeout(callback, 1000 / 60);
};
})();
window.cancelRequestAnimFrame = (function () {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout
})();
//http://snipplr.com/view/13523/
//modified for speed
//http://jsperf.com/getcomputedstyle-vs-style-vs-css/8
if (!window.getComputedStyle) {
(function () {
var elem;
var styleObj = {
getPropertyValue: function getPropertyValue(prop) {
if (prop == 'float') prop = 'styleFloat';
return elem.currentStyle[prop.toUpperCase()] || null;
}
};
window.getComputedStyle = function (el) {
elem = el;
return styleObj;
}
})();
}
/**
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
*/
if (!String.prototype.trim) {
var trimRegex = /^\s+|\s+$/g;
String.prototype.trim = function () {
return this.replace(trimRegex, '');
};
}
/**
* WalkontableRowFilter
* @constructor
*/
function WalkontableRowFilter(offset, total, fixedCount, countTH) {
this.offset = offset;
this.total = total;
this.fixedCount = fixedCount;
this.countTH = countTH;
}
WalkontableRowFilter.prototype = new WalkontableAbstractFilter();
WalkontableRowFilter.prototype.offsettedTH = function (n) {
return n - this.countTH;
};
WalkontableRowFilter.prototype.visibleColHeadedColumnToSourceColumn = function (n) {
return this.visibleToSource(this.offsettedTH(n));
};
WalkontableRowFilter.prototype.sourceColumnToVisibleColHeadedColumn = function (n) {
return this.unOffsettedTH(this.sourceToVisible(n));
};
/**
* WalkontableRowStrategy
* @param containerSizeFn
* @param sizeAtIndex
* @constructor
*/
function WalkontableRowStrategy(instance, containerSizeFn, sizeAtIndex) {
WalkontableAbstractStrategy.apply(this, arguments);
this.containerSizeFn = containerSizeFn;
this.sizeAtIndex = sizeAtIndex;
this.cellSizesSum = 0;
this.cellSizes = [];
this.cellCount = 0;
this.visiblCellCount = 0;
this.remainingSize = -Infinity;
this.maxOuts = 10; //max outs in one direction (before and after table)
this.curOuts = this.maxOuts;
}
WalkontableRowStrategy.prototype = new WalkontableAbstractStrategy();
WalkontableRowStrategy.prototype.add = function (i, TD) {
if(!this.canRenderMoreRows()){
return false;
}
var size = this.sizeAtIndex(i, TD);
if (size === void 0) {
return false; //total rows exceeded
}
var containerSize = this.getContainerSize(this.cellSizesSum + size);
this.cellSizes.push(size);
this.cellSizesSum += size;
this.cellCount++;
this.remainingSize = this.cellSizesSum - containerSize;
if (this.remainingSize <= size ){
this.visiblCellCount++;
}
return true;
};
/**
* Checks whether the number of already rendered rows does not exceeds the number of rows visible in viewport + maximal
* number of rows rendered above and below viewport
* @returns {boolean}
*/
WalkontableRowStrategy.prototype.canRenderMoreRows = function () {
return this.remainingSize <= 0 || this.cellCount - this.visiblCellCount < this.curOuts;
};
WalkontableRowStrategy.prototype.remove = function () {
var size = this.cellSizes.pop();
this.cellSizesSum -= size;
this.cellCount--;
this.remainingSize -= size;
};
WalkontableRowStrategy.prototype.removeOutstanding = function () {
while (this.cellCount - this.visiblCellCount > this.curOuts) { //this row is completely off screen!
this.remove();
}
};
WalkontableRowStrategy.prototype.countRendered = function () {
return this.cellCount;
}
WalkontableRowStrategy.prototype.countVisible = function () {
return this.visiblCellCount;
};
WalkontableRowStrategy.prototype.isLastIncomplete = function () {
var lastRow = this.instance.wtTable.getLastVisibleRow();
var firstCol = this.instance.wtTable.getFirstVisibleColumn();
var cell = this.instance.wtTable.getCell(new WalkontableCellCoords(lastRow, firstCol));
var cellOffsetTop = Handsontable.Dom.offset(cell).top;
var cellHeight = Handsontable.Dom.outerHeight(cell);
var cellEnd = cellOffsetTop + cellHeight;
var viewportOffsetTop = this.instance.wtScrollbars.horizontal.scrollHandler.offsetTop + this.instance.wtScrollbars.vertical.getScrollPosition();
var viewportHeight = this.instance.wtViewport.getViewportHeight();
var viewportEnd = viewportOffsetTop + viewportHeight;
return viewportEnd < cellEnd;
};
function WalkontableScroll(instance) {
this.instance = instance;
}
WalkontableScroll.prototype.scrollVertical = function (delta) {
if (!this.instance.drawn) {
throw new Error('scrollVertical can only be called after table was drawn to DOM');
}
var instance = this.instance
, newOffset
, offset = instance.getSetting('offsetRow')
, fixedCount = instance.getSetting('fixedRowsTop')
, total = instance.getSetting('totalRows')
, maxSize = instance.wtViewport.getViewportHeight();
if (total > 0 && !this.instance.wtTable.isLastRowFullyVisible()) {
newOffset = this.scrollLogicVertical(delta, offset, total, fixedCount, maxSize, function (row) {
if (row - offset < fixedCount && row - offset >= 0) {
return instance.getSetting('rowHeight', row - offset);
}
else {
return instance.getSetting('rowHeight', row);
}
});
} else {
newOffset = 0;
}
if (newOffset !== offset) {
this.instance.wtScrollbars.vertical.scrollTo(newOffset);
}
return instance;
};
WalkontableScroll.prototype.scrollHorizontal = function (delta) {
if (!this.instance.drawn) {
throw new Error('scrollHorizontal can only be called after table was drawn to DOM');
}
var instance = this.instance
, newOffset
, offset = instance.getSetting('offsetColumn')
, fixedCount = instance.getSetting('fixedColumnsLeft')
, total = instance.getSetting('totalColumns')
, maxSize = instance.wtViewport.getViewportWidth();
if (total > 0) {
newOffset = this.scrollLogicHorizontal(delta, offset, total, fixedCount, maxSize, function (col) {
if (col - offset < fixedCount && col - offset >= 0) {
return instance.getSetting('columnWidth', col - offset);
}
else {
return instance.getSetting('columnWidth', col);
}
});
}
else {
newOffset = 0;
}
if (newOffset !== offset) {
this.instance.wtScrollbars.horizontal.scrollTo(newOffset);
}
return instance;
};
WalkontableScroll.prototype.scrollLogicVertical = function (delta, offset, total, fixedCount, maxSize, cellSizeFn) {
var newOffset = offset + delta;
if (newOffset >= total - fixedCount) {
newOffset = total - fixedCount - 1;
}
if (newOffset < 0) {
newOffset = 0;
}
return newOffset;
};
WalkontableScroll.prototype.scrollLogicHorizontal = function (delta, offset, total, fixedCount, maxSize, cellSizeFn) {
var newOffset = offset + delta
, sum = 0
, col;
if (newOffset > fixedCount) {
if (newOffset >= total - fixedCount) {
newOffset = total - fixedCount - 1;
}
col = newOffset;
while (sum < maxSize && col < total) {
sum += cellSizeFn(col);
col++;
}
if (sum < maxSize) {
while (newOffset > 0) {
//if sum still less than available width, we cannot scroll that far (must move offset to the left)
sum += cellSizeFn(newOffset - 1);
if (sum < maxSize) {
newOffset--;
}
else {
break;
}
}
}
}
else if (newOffset < 0) {
newOffset = 0;
}
return newOffset;
};
/**
* Scrolls viewport to a cell by minimum number of cells
* @param {WalkontableCellCoords} coords
*/
WalkontableScroll.prototype.scrollViewport = function (coords) {
if (!this.instance.drawn) {
return;
}
var offsetRow = this.instance.getSetting('offsetRow')
, offsetColumn = this.instance.getSetting('offsetColumn')
, totalRows = this.instance.getSetting('totalRows')
, totalColumns = this.instance.getSetting('totalColumns')
, fixedRowsTop = this.instance.getSetting('fixedRowsTop')
, fixedColumnsLeft = this.instance.getSetting('fixedColumnsLeft');
if (coords.row < 0 || coords.row > totalRows - 1) {
throw new Error('row ' + coords.row + ' does not exist');
}
if (coords.col < 0 || coords.col > totalColumns - 1) {
throw new Error('column ' + coords.col + ' does not exist');
}
var TD = this.instance.wtTable.getCell(coords);
if (typeof TD === 'object') {
this.scrollToRenderedCell(TD);
} else if (coords.row >= this.instance.wtTable.getLastVisibleRow()) {
this.scrollVertical(coords.row - this.instance.wtTable.getLastVisibleRow());
if (coords.row == this.instance.wtTable.getLastVisibleRow() && this.instance.wtTable.getRowStrategy().isLastIncomplete()){
this.scrollViewport(coords)
}
} else if (coords.row >= this.instance.getSetting('fixedColumnsLeft')){
this.scrollVertical(coords.row - this.instance.wtTable.getFirstVisibleRow());
}
};
WalkontableScroll.prototype.scrollToRenderedCell = function (TD) {
var cellOffset = Handsontable.Dom.offset(TD);
var cellWidth = Handsontable.Dom.outerWidth(TD);
var cellHeight = Handsontable.Dom.outerHeight(TD);
var workspaceOffset = Handsontable.Dom.offset(this.instance.wtTable.TABLE);
var viewportScrollPosition = {
left: this.instance.wtScrollbars.horizontal.getScrollPosition(),
top: this.instance.wtScrollbars.vertical.getScrollPosition()
};
var workspaceWidth = this.instance.wtViewport.getWorkspaceWidth();
var workspaceHeight = this.instance.wtViewport.getWorkspaceHeight();
var leftCloneWidth = Handsontable.Dom.outerWidth(this.instance.wtScrollbars.horizontal.clone.wtTable.TABLE);
var topCloneHeight = Handsontable.Dom.outerHeight(this.instance.wtScrollbars.vertical.clone.wtTable.TABLE);
if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) {
workspaceOffset.left = 0;
cellOffset.left -= Handsontable.Dom.offset(this.instance.wtScrollbars.horizontal.scrollHandler).left;
}
if (this.instance.wtScrollbars.vertical.scrollHandler !== window) {
workspaceOffset.top = 0;
cellOffset.top = cellOffset.top - Handsontable.Dom.offset(this.instance.wtScrollbars.vertical.scrollHandler).top;
}
if (cellWidth < workspaceWidth) {
if (cellOffset.left < viewportScrollPosition.left + leftCloneWidth) {
this.instance.wtScrollbars.horizontal.setScrollPosition(cellOffset.left - leftCloneWidth);
}
else if (cellOffset.left + cellWidth > workspaceOffset.left + viewportScrollPosition.left + workspaceWidth) {
var delta = (cellOffset.left + cellWidth) - (workspaceOffset.left + viewportScrollPosition.left + workspaceWidth);
this.instance.wtScrollbars.horizontal.setScrollPosition(viewportScrollPosition.left + delta);
}
}
if (cellHeight < workspaceHeight) {
if (cellOffset.top < viewportScrollPosition.top + topCloneHeight) {
this.instance.wtScrollbars.vertical.setScrollPosition(cellOffset.top - topCloneHeight);
this.instance.wtScrollbars.vertical.onScroll();
}
else if (cellOffset.top + cellHeight > viewportScrollPosition.top + workspaceHeight) {
this.instance.wtScrollbars.vertical.setScrollPosition(cellOffset.top - workspaceHeight + cellHeight);
this.instance.wtScrollbars.vertical.onScroll();
}
}
};
function WalkontableCornerScrollbarNative(instance) {
this.instance = instance;
this.init();
this.clone = this.makeClone('corner');
}
WalkontableCornerScrollbarNative.prototype = new WalkontableOverlay();
WalkontableCornerScrollbarNative.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box;
if (this.scrollHandler === window) {
box = this.instance.wtTable.hider.getBoundingClientRect();
var top = Math.ceil(box.top, 10);
var bottom = Math.ceil(box.bottom, 10);
if (top < 0 && bottom > 0) {
elem.style.top = '0';
}
else {
elem.style.top = top + 'px';
}
var left = Math.ceil(box.left, 10);
var right = Math.ceil(box.right, 10);
if (left < 0 && right > 0) {
elem.style.left = '0';
}
else {
elem.style.left = left + 'px';
}
}
else {
box = this.scrollHandler.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
}
elem.style.width = Handsontable.Dom.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px';
elem.style.height = Handsontable.Dom.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px';
};
WalkontableCornerScrollbarNative.prototype.prepare = function () {
};
WalkontableCornerScrollbarNative.prototype.refresh = function (selectionsOnly) {
this.measureBefore = 0;
this.measureAfter = 0;
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableCornerScrollbarNative.prototype.getScrollPosition = function () {
};
WalkontableCornerScrollbarNative.prototype.getLastCell = function () {
};
WalkontableCornerScrollbarNative.prototype.applyToDOM = function () {
};
WalkontableCornerScrollbarNative.prototype.scrollTo = function () {
};
WalkontableCornerScrollbarNative.prototype.readWindowSize = function () {
};
WalkontableCornerScrollbarNative.prototype.readSettings = function () {
};
function WalkontableHorizontalScrollbarNative(instance) {
this.instance = instance;
this.type = 'horizontal';
this.cellSize = 50;
this.init();
this.clone = this.makeClone('left');
}
WalkontableHorizontalScrollbarNative.prototype = new WalkontableOverlay();
//resetFixedPosition (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box;
if (this.scrollHandler === window) {
box = this.instance.wtTable.hider.getBoundingClientRect();
var left = Math.ceil(box.left, 10);
var right = Math.ceil(box.right, 10);
if (left < 0 && right > 0) {
elem.style.left = '0';
}
else {
elem.style.left = left + 'px';
}
}
else {
box = this.scrollHandler.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
}
this.react();
};
//react on movement of the other dimension scrollbar (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.react = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var overlayContainer = this.clone.wtTable.holder.parentNode;
if (this.instance.wtScrollbars.vertical.scrollHandler === window) {
var box = this.instance.wtTable.hider.getBoundingClientRect();
overlayContainer.style.top = Math.ceil(box.top, 10) + 'px';
overlayContainer.style.height = Handsontable.Dom.outerHeight(this.clone.wtTable.TABLE) + 'px';
}
else {
this.clone.wtTable.holder.style.top = -(this.instance.wtScrollbars.vertical.windowScrollPosition - this.instance.wtScrollbars.vertical.measureBefore) + 'px';
overlayContainer.style.height = this.instance.wtViewport.getWorkspaceHeight() + 'px'
}
overlayContainer.style.width = Handsontable.Dom.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px'; //4 is for the box shadow
};
WalkontableHorizontalScrollbarNative.prototype.prepare = function () {
};
WalkontableHorizontalScrollbarNative.prototype.refresh = function (selectionsOnly) {
this.measureBefore = 0;
this.measureAfter = 0;
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableHorizontalScrollbarNative.prototype.getScrollPosition = function () {
return Handsontable.Dom.getScrollLeft(this.scrollHandler);
};
WalkontableHorizontalScrollbarNative.prototype.setScrollPosition = function (pos) {
if (this.scrollHandler === window){
window.scrollTo(pos, Handsontable.Dom.getWindowScrollTop());
} else {
this.scrollHandler.scrollLeft = pos;
}
};
WalkontableHorizontalScrollbarNative.prototype.onScroll = function () {
WalkontableOverlay.prototype.onScroll.call(this);
this.instance.getSetting('onScrollHorizontally');
};
WalkontableHorizontalScrollbarNative.prototype.getLastCell = function () {
return this.instance.wtTable.getLastVisibleColumn();
};
//applyToDOM (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.applyToDOM = function () {
this.fixedContainer.style.paddingLeft = this.measureBefore + 'px';
this.fixedContainer.style.paddingRight = this.measureAfter + 'px';
};
WalkontableHorizontalScrollbarNative.prototype.scrollTo = function (cell) {
this.setScrollPosition(this.tableParentOffset + cell * this.cellSize);
};
//readWindowSize (in future merge it with this.prepare?)
WalkontableHorizontalScrollbarNative.prototype.readWindowSize = function () {
if (this.scrollHandler === window) {
this.windowSize = document.documentElement.clientWidth;
this.tableParentOffset = this.instance.wtTable.holderOffset.left;
}
else {
this.windowSize = this.scrollHandler.clientWidth;
this.tableParentOffset = 0;
}
this.windowScrollPosition = this.getScrollPosition();
};
//readSettings (in future merge it with this.prepare?)
WalkontableHorizontalScrollbarNative.prototype.readSettings = function () {
this.readWindowSize();
this.offset = this.instance.getSetting('offsetColumn');
this.total = this.instance.getSetting('totalColumns');
};
function WalkontableVerticalScrollbarNative(instance) {
this.instance = instance;
this.type = 'vertical';
this.cellSize = this.instance.wtSettings.settings.defaultRowHeight;
this.offset;
this.total;
this.init();
this.clone = this.makeClone('top');
}
WalkontableVerticalScrollbarNative.prototype = new WalkontableOverlay();
//resetFixedPosition (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box;
if (this.scrollHandler === window) {
box = this.instance.wtTable.hider.getBoundingClientRect();
var top = Math.ceil(box.top, 10);
var bottom = Math.ceil(box.bottom, 10);
if (top < 0 && bottom > 0) {
elem.style.top = '0';
}
else {
elem.style.top = top + 'px';
}
}
else {
box = this.instance.wtScrollbars.horizontal.scrollHandler.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
}
if (this.instance.wtScrollbars.horizontal.scrollHandler === window) {
elem.style.width = this.instance.wtViewport.getWorkspaceActualWidth() + 'px';
}
else {
elem.style.width = Handsontable.Dom.outerWidth(this.instance.wtTable.holder.parentNode) + 'px';
}
elem.style.height = Handsontable.Dom.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px';
};
//react on movement of the other dimension scrollbar (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.react = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var overlayContainer = this.clone.wtTable.holder.parentNode;
if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) {
overlayContainer.firstChild.style.left = -this.instance.wtScrollbars.horizontal.windowScrollPosition + 'px';
} else {
var box = this.instance.wtTable.hider.getBoundingClientRect();
overlayContainer.style.left = Math.ceil(box.left, 10) + 'px';
overlayContainer.style.width = Handsontable.Dom.outerWidth(this.clone.wtTable.TABLE) + 'px';
}
};
WalkontableVerticalScrollbarNative.prototype.getScrollPosition = function () {
return Handsontable.Dom.getScrollTop(this.scrollHandler);
};
WalkontableVerticalScrollbarNative.prototype.setScrollPosition = function (pos) {
if (this.scrollHandler === window){
window.scrollTo(Handsontable.Dom.getWindowScrollLeft(), pos);
} else {
this.scrollHandler.scrollTop = pos;
}
};
WalkontableVerticalScrollbarNative.prototype.onScroll = function () {
WalkontableOverlay.prototype.onScroll.call(this);
this.instance.draw(true);//
this.instance.getSetting('onScrollVertically');
};
WalkontableVerticalScrollbarNative.prototype.getLastCell = function () {
return this.instance.getSetting('offsetRow') + this.instance.wtTable.tbodyChildrenLength - 1;
};
WalkontableVerticalScrollbarNative.prototype.sumCellSizes = function (from, length) {
var sum = 0;
while (from < length) {
sum += this.instance.wtSettings.settings.rowHeight(from) || this.instance.wtSettings.settings.defaultRowHeight; //TODO optimize getSetting, because this is MUCH faster then getSetting
from++;
}
return sum;
};
//applyToDOM (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.applyToDOM = function () {
var headerSize = this.instance.wtViewport.getColumnHeaderHeight();
this.fixedContainer.style.height = headerSize + this.sumCellSizes(0, this.total) + 4 + 'px'; //+4 is needed, otherwise vertical scroll appears in Chrome (window scroll mode) - maybe because of fill handle in last row or because of box shadow
this.fixed.style.top = this.measureBefore + 'px';
this.fixed.style.bottom = '';
};
WalkontableVerticalScrollbarNative.prototype.scrollTo = function (cell) {
var newY = this.tableParentOffset + cell * this.cellSize;
this.setScrollPosition(newY);
this.onScroll();
};
//readWindowSize (in future merge it with this.prepare?)
WalkontableVerticalScrollbarNative.prototype.readWindowSize = function () {
if (this.scrollHandler === window) {
this.windowSize = document.documentElement.clientHeight;
this.tableParentOffset = this.instance.wtTable.holderOffset.top;
}
else {
var elemHeight = Handsontable.Dom.outerHeight(this.scrollHandler);
this.windowSize = elemHeight > 0 && this.scrollHandler.clientHeight > 0 ? this.scrollHandler.clientHeight : Infinity; //returns height without DIV scrollbar
this.tableParentOffset = 0;
}
this.windowScrollPosition = this.getScrollPosition();
};
//readSettings (in future merge it with this.prepare?)
WalkontableVerticalScrollbarNative.prototype.readSettings = function () {
this.readWindowSize();
this.offset = this.instance.getSetting('offsetRow');
this.total = this.instance.getSetting('totalRows');
var scrollDelta = this.windowScrollPosition - this.tableParentOffset;
var sum = 0;
var last;
for (var i = 0; i < this.total; i++) {
last = this.instance.getSetting('rowHeight', i) || this.instance.wtSettings.settings.defaultRowHeight;
sum += last;
if (sum - 1 > scrollDelta) {
break;
}
}
this.offset = Math.min(i, this.total);
this.instance.update('offsetRow', this.offset);
};
function WalkontableScrollbars(instance) {
this.instance = instance;
instance.update('scrollbarWidth', Handsontable.Dom.getScrollbarWidth());
instance.update('scrollbarHeight', Handsontable.Dom.getScrollbarWidth());
this.vertical = new WalkontableVerticalScrollbarNative(instance);
this.horizontal = new WalkontableHorizontalScrollbarNative(instance);
this.corner = new WalkontableCornerScrollbarNative(instance);
if (instance.getSetting('debug')) {
this.debug = new WalkontableDebugOverlay(instance);
}
this.registerListeners();
}
WalkontableScrollbars.prototype.registerListeners = function () {
var that = this;
var oldVerticalScrollPosition
, oldHorizontalScrollPosition
, oldBoxTop
, oldBoxLeft
, oldBoxWidth
, oldBoxHeight;
function refreshAll() {
if(!that.instance.drawn) {
return;
}
if (!that.instance.wtTable.holder.parentNode) {
//Walkontable was detached from DOM, but this handler was not removed
that.destroy();
return;
}
that.vertical.windowScrollPosition = that.vertical.getScrollPosition();
that.horizontal.windowScrollPosition = that.horizontal.getScrollPosition();
that.box = that.instance.wtTable.hider.getBoundingClientRect();
/*if((that.box.width !== oldBoxWidth || that.box.height !== oldBoxHeight) && that.instance.rowHeightCache) {
//that.instance.rowHeightCache.length = 0; //at this point the cached row heights may be invalid, but it is better not to reset the cache, which could cause scrollbar jumping when there are multiline cells outside of the rendered part of the table
oldBoxWidth = that.box.width;
oldBoxHeight = that.box.height;
that.instance.draw(true);
}*/
if (that.vertical.windowScrollPosition !== oldVerticalScrollPosition || that.horizontal.windowScrollPosition !== oldHorizontalScrollPosition || that.box.top !== oldBoxTop || that.box.left !== oldBoxLeft) {
that.vertical.onScroll();
that.horizontal.onScroll(); //it's done here to make sure that all onScroll's are executed before changing styles
that.corner.onScroll();
that.vertical.react();
that.horizontal.react(); //it's done here to make sure that all onScroll's are executed before changing styles
oldVerticalScrollPosition = that.vertical.windowScrollPosition;
oldHorizontalScrollPosition = that.horizontal.windowScrollPosition;
oldBoxTop = that.box.top;
oldBoxLeft = that.box.left;
}
}
var $window = $(window);
this.vertical.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll);
if (this.vertical.scrollHandler !== this.horizontal.scrollHandler) {
this.horizontal.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll);
}
if (this.vertical.scrollHandler !== window && this.horizontal.scrollHandler !== window) {
$window.on('scroll.' + this.instance.guid, refreshAll);
}
};
WalkontableScrollbars.prototype.destroy = function () {
this.vertical && this.vertical.destroy();
this.horizontal && this.horizontal.destroy();
this.corner && this.corner.destroy();
};
WalkontableScrollbars.prototype.refresh = function (selectionsOnly) {
this.horizontal && this.horizontal.readSettings();
this.vertical && this.vertical.readSettings();
this.horizontal && this.horizontal.prepare();
this.vertical && this.vertical.prepare();
this.horizontal && this.horizontal.refresh(selectionsOnly);
this.vertical && this.vertical.refresh(selectionsOnly);
this.corner && this.corner.refresh(selectionsOnly);
this.debug && this.debug.refresh(selectionsOnly);
};
function WalkontableSelection(instance, settings) {
this.instance = instance;
this.settings = settings;
this.cellRange = null;
if (settings.border) {
this.border = new WalkontableBorder(instance, settings);
}
}
/**
* Returns boolean information if selection is empty
* @returns {boolean}
*/
WalkontableSelection.prototype.isEmpty = function () {
return (this.cellRange === null);
};
/**
* Adds a cell coords to the selection
* @param {WalkontableCellCoords} coords
*/
WalkontableSelection.prototype.add = function (coords) {
if (this.isEmpty()) {
this.cellRange = new WalkontableCellRange(coords, coords, coords);
}
else {
this.cellRange.expand(coords);
}
};
/**
* If selection range from or to property equals oldCoords, replace it with newCoords. Return boolean information about success
* @param {WalkontableCellCoords} oldCoords
* @param {WalkontableCellCoords} newCoords
* @return {boolean}
*/
WalkontableSelection.prototype.replace = function (oldCoords, newCoords) {
if (!this.isEmpty()) {
if(this.cellRange.from.isEqual(oldCoords)) {
this.cellRange.from = newCoords;
return true;
}
if(this.cellRange.to.isEqual(oldCoords)) {
this.cellRange.to = newCoords;
return true;
}
}
return false;
};
WalkontableSelection.prototype.clear = function () {
this.cellRange = null;
};
/**
* Returns the top left (TL) and bottom right (BR) selection coordinates
* @returns {Object}
*/
WalkontableSelection.prototype.getCorners = function () {
var topLeft = this.cellRange.getTopLeftCorner();
var bottomRight = this.cellRange.getBottomRightCorner();
return [topLeft.row, topLeft.col, bottomRight.row, bottomRight.col];
};
WalkontableSelection.prototype.draw = function () {
var corners, r, c, source_r, source_c,
instance = this.instance,
visibleRows = instance.wtTable.getRowStrategy().countVisible(),
renderedColumns = instance.wtTable.getColumnStrategy().cellCount;
if (!this.isEmpty()) {
corners = this.getCorners();
for (r = 0; r < visibleRows; r++) {
for (c = 0; c < renderedColumns; c++) {
source_r = instance.wtTable.rowFilter.visibleToSource(r);
source_c = instance.wtTable.columnFilter.visibleToSource(c);
if (source_r >= corners[0] && source_r <= corners[2] && source_c >= corners[1] && source_c <= corners[3]) {
//selected cell
if (this.settings.className) {
instance.wtTable.currentCellCache.add(r, c, this.settings.className);
}
}
else if (source_r >= corners[0] && source_r <= corners[2]) {
//selection is in this row
if (this.settings.highlightRowClassName) {
instance.wtTable.currentCellCache.add(r, c, this.settings.highlightRowClassName);
}
}
else if (source_c >= corners[1] && source_c <= corners[3]) {
//selection is in this column
if (this.settings.highlightColumnClassName) {
instance.wtTable.currentCellCache.add(r, c, this.settings.highlightColumnClassName);
}
}
}
}
this.border && this.border.appear(corners); //warning! border.appear modifies corners!
}
else {
this.border && this.border.disappear();
}
};
/*
Make a clone of a selection by overriding the WOT instance and creating new WalkontableBorder for the new instance
Method is used for creating selections in overlays
*/
WalkontableSelection.prototype.makeClone = function (instance) {
function WalkontableSelectionClone(){}
WalkontableSelectionClone.prototype = this;
var clone = new WalkontableSelectionClone();
clone.instance = instance;
if (clone.border){
clone.border = new WalkontableBorder(instance, clone.settings);
}
return clone;
};
function WalkontableSelections(instance, config){
if (config) {
for (var i in config) {
if (config.hasOwnProperty(i)) {
this[i] = new WalkontableSelection(instance, config[i]);
}
}
}
}
WalkontableSelections.prototype.makeClone = function (instance) {
function WalkontableSelectionsClone(){}
var clone = new WalkontableSelectionsClone();
for (var selectionName in this){
if (this.hasOwnProperty(selectionName)){
clone[selectionName] = this[selectionName].makeClone(instance);
}
}
return clone;
};
function WalkontableSettings(instance, settings) {
var that = this;
this.instance = instance;
//default settings. void 0 means it is required, null means it can be empty
this.defaults = {
table: void 0,
debug: false, //shows WalkontableDebugOverlay
//presentation mode
scrollH: 'auto', //values: scroll (always show scrollbar), auto (show scrollbar if table does not fit in the container), none (never show scrollbar)
scrollV: 'auto', //values: see above
stretchH: 'none', //values: all, last, none
currentRowClassName: null,
currentColumnClassName: null,
//data source
data: void 0,
offsetRow: 0,
offsetColumn: 0,
fixedColumnsLeft: 0,
fixedRowsTop: 0,
rowHeaders: function () {
return []
}, //this must be array of functions: [function (row, TH) {}]
columnHeaders: function () {
return []
}, //this must be array of functions: [function (column, TH) {}]
totalRows: void 0,
totalColumns: void 0,
width: null,
height: null,
cellRenderer: function (row, column, TD) {
var cellData = that.getSetting('data', row, column);
Handsontable.Dom.fastInnerText(TD, cellData === void 0 || cellData === null ? '' : cellData);
},
columnWidth: 50,
rowHeight: function (row) {
return 23;
},
defaultRowHeight: 23,
selections: null,
hideBorderOnMouseDownOver: false,
//callbacks
onCellMouseDown: null,
onCellMouseOver: null,
// onCellMouseOut: null,
onCellDblClick: null,
onCellCornerMouseDown: null,
onCellCornerDblClick: null,
beforeDraw: null,
onDraw: null,
onScrollVertically: null,
onScrollHorizontally: null,
//constants
scrollbarWidth: 10,
scrollbarHeight: 10,
renderAllRows: false
};
//reference to settings
this.settings = {};
for (var i in this.defaults) {
if (this.defaults.hasOwnProperty(i)) {
if (settings[i] !== void 0) {
this.settings[i] = settings[i];
}
else if (this.defaults[i] === void 0) {
throw new Error('A required setting "' + i + '" was not provided');
}
else {
this.settings[i] = this.defaults[i];
}
}
}
}
/**
* generic methods
*/
WalkontableSettings.prototype.update = function (settings, value) {
if (value === void 0) { //settings is object
for (var i in settings) {
if (settings.hasOwnProperty(i)) {
this.settings[i] = settings[i];
}
}
}
else { //if value is defined then settings is the key
this.settings[settings] = value;
}
return this.instance;
};
WalkontableSettings.prototype.getSetting = function (key, param1, param2, param3, param4) {
if (typeof this.settings[key] === 'function') {
return this.settings[key](param1, param2, param3, param4); //this is faster than .apply - https://github.com/handsontable/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
else if (param1 !== void 0 && Object.prototype.toString.call(this.settings[key]) === '[object Array]') { //perhaps this can be removed, it is only used in tests
return this.settings[key][param1];
}
else {
return this.settings[key];
}
};
WalkontableSettings.prototype.has = function (key) {
return !!this.settings[key]
};
function WalkontableTable(instance, table) {
//reference to instance
this.instance = instance;
this.TABLE = table;
Handsontable.Dom.removeTextNodes(this.TABLE);
//wtSpreader
var parent = this.TABLE.parentNode;
if (!parent || parent.nodeType !== 1 || !Handsontable.Dom.hasClass(parent, 'wtHolder')) {
var spreader = document.createElement('DIV');
spreader.className = 'wtSpreader';
if (parent) {
parent.insertBefore(spreader, this.TABLE); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
}
spreader.appendChild(this.TABLE);
}
this.spreader = this.TABLE.parentNode;
//wtHider
parent = this.spreader.parentNode;
if (!parent || parent.nodeType !== 1 || !Handsontable.Dom.hasClass(parent, 'wtHolder')) {
var hider = document.createElement('DIV');
hider.className = 'wtHider';
if (parent) {
parent.insertBefore(hider, this.spreader); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
}
hider.appendChild(this.spreader);
}
this.hider = this.spreader.parentNode;
this.hiderStyle = this.hider.style;
this.hiderStyle.position = 'relative';
//wtHolder
parent = this.hider.parentNode;
if (!parent || parent.nodeType !== 1 || !Handsontable.Dom.hasClass(parent, 'wtHolder')) {
var holder = document.createElement('DIV');
holder.style.position = 'relative';
holder.className = 'wtHolder';
if(!instance.cloneSource) {
holder.className += ' ht_master';
}
if (parent) {
parent.insertBefore(holder, this.hider); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
}
holder.appendChild(this.hider);
}
this.holder = this.hider.parentNode;
//bootstrap from settings
this.TBODY = this.TABLE.getElementsByTagName('TBODY')[0];
if (!this.TBODY) {
this.TBODY = document.createElement('TBODY');
this.TABLE.appendChild(this.TBODY);
}
this.THEAD = this.TABLE.getElementsByTagName('THEAD')[0];
if (!this.THEAD) {
this.THEAD = document.createElement('THEAD');
this.TABLE.insertBefore(this.THEAD, this.TBODY);
}
this.COLGROUP = this.TABLE.getElementsByTagName('COLGROUP')[0];
if (!this.COLGROUP) {
this.COLGROUP = document.createElement('COLGROUP');
this.TABLE.insertBefore(this.COLGROUP, this.THEAD);
}
if (this.instance.getSetting('columnHeaders').length) {
if (!this.THEAD.childNodes.length) {
var TR = document.createElement('TR');
this.THEAD.appendChild(TR);
}
}
this.colgroupChildrenLength = this.COLGROUP.childNodes.length;
this.theadChildrenLength = this.THEAD.firstChild ? this.THEAD.firstChild.childNodes.length : 0;
this.tbodyChildrenLength = this.TBODY.childNodes.length;
this.oldCellCache = new WalkontableClassNameCache();
this.currentCellCache = new WalkontableClassNameCache();
this.rowFilter = null;
this.columnFilter = null;
this.columnWidthCache = [];
}
WalkontableTable.prototype.getRowStrategy = function () {
return this.isWorkingOnClone() ? this.instance.cloneSource.wtTable.rowStrategy : this.rowStrategy;
};
WalkontableTable.prototype.getColumnStrategy = function () {
return this.isWorkingOnClone() ? this.instance.cloneSource.wtTable.columnStrategy : this.columnStrategy;
};
WalkontableTable.prototype.isWorkingOnClone = function () {
return !!this.instance.cloneSource;
};
WalkontableTable.prototype.refreshHiderDimensions = function () {
var spreaderStyle = this.spreader.style;
spreaderStyle.position = 'relative';
spreaderStyle.width = 'auto';
spreaderStyle.height = 'auto';
};
WalkontableTable.prototype.draw = function (selectionsOnly) {
if (!selectionsOnly) {
if (this.isWorkingOnClone()) {
this.tableOffset = this.instance.cloneSource.wtTable.tableOffset;
}
else {
this.holderOffset = Handsontable.Dom.offset(this.holder);
this.tableOffset = Handsontable.Dom.offset(this.TABLE);
this.instance.wtScrollbars.vertical.readSettings();
this.instance.wtScrollbars.horizontal.readSettings();
this.instance.wtViewport.resetSettings();
}
var offsetRow;
if (this.instance.cloneOverlay instanceof WalkontableDebugOverlay) {
offsetRow = 0;
}
else {
offsetRow = this.instance.wtSettings.settings.offsetRow;
}
this.rowFilter = new WalkontableRowFilter(
offsetRow,
this.instance.getSetting('totalRows'),
this.instance.getSetting('fixedRowsTop'),
this.instance.getSetting('columnHeaders').length
);
this.columnFilter = new WalkontableColumnFilter(
this.instance.wtSettings.settings.offsetColumn,
this.instance.getSetting('totalColumns'),
this.instance.getSetting('fixedColumnsLeft'),
this.instance.getSetting('rowHeaders').length
);
this._doDraw();
}
else {
this.instance.wtScrollbars && this.instance.wtScrollbars.refresh(true);
}
this.refreshPositions(selectionsOnly);
if (!selectionsOnly) {
if (!this.isWorkingOnClone()) {
this.instance.wtScrollbars.vertical.resetFixedPosition();
this.instance.wtScrollbars.horizontal.resetFixedPosition();
this.instance.wtScrollbars.corner.resetFixedPosition();
this.instance.wtScrollbars.debug && this.instance.wtScrollbars.debug.resetFixedPosition();
}
}
this.instance.drawn = true;
return this;
};
WalkontableTable.prototype._doDraw = function () {
var wtRenderer = new WalkontableTableRenderer(this);
wtRenderer.render();
};
WalkontableTable.prototype.refreshPositions = function (selectionsOnly) {
this.refreshHiderDimensions();
this.refreshSelections(selectionsOnly);
};
WalkontableTable.prototype.refreshSelections = function (selectionsOnly) {
var vr
, r
, vc
, c
, s
, slen
, classNames = []
, visibleRows = this.getRowStrategy().countVisible()
, renderedCells = this.getColumnStrategy().cellCount;
this.oldCellCache = this.currentCellCache;
this.currentCellCache = new WalkontableClassNameCache();
if (this.instance.selections) {
for (r in this.instance.selections) {
if (this.instance.selections.hasOwnProperty(r)) {
this.instance.selections[r].draw();
if (this.instance.selections[r].settings.className) {
classNames.push(this.instance.selections[r].settings.className);
}
if (this.instance.selections[r].settings.highlightRowClassName) {
classNames.push(this.instance.selections[r].settings.highlightRowClassName);
}
if (this.instance.selections[r].settings.highlightColumnClassName) {
classNames.push(this.instance.selections[r].settings.highlightColumnClassName);
}
}
}
}
slen = classNames.length;
for (vr = 0; vr < visibleRows; vr++) {
for (vc = 0; vc < renderedCells; vc++) {
r = this.rowFilter.visibleToSource(vr);
c = this.columnFilter.visibleToSource(vc);
for (s = 0; s < slen; s++) {
var cell;
if (this.currentCellCache.test(vr, vc, classNames[s])) {
cell = this.getCell(new WalkontableCellCoords(r, c));
if (typeof cell == 'object' ) Handsontable.Dom.addClass(cell, classNames[s]);
}
else if (selectionsOnly && this.oldCellCache.test(vr, vc, classNames[s])) {
cell = this.getCell(new WalkontableCellCoords(r, c));
if (typeof cell == 'object' ) Handsontable.Dom.removeClass(cell, classNames[s]);
}
}
}
}
};
/**
* getCell
* @param {WalkontableCellCoords} coords
* @return {Object} HTMLElement on success or {Number} one of the exit codes on error:
* -1 row before viewport
* -2 row after viewport
*
*/
WalkontableTable.prototype.getCell = function (coords) {
if (this.isRowBeforeViewport(coords.row)) {
return -1; //row before viewport
}
else if (this.isRowAfterViewport(coords.row)) {
return -2; //row after viewport
}
var TR = this.TBODY.childNodes[this.rowFilter.sourceToVisible(coords.row)];
if (TR) {
return TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(coords.col)];
}
};
/**
* Returns cell coords object for a given TD
* @param TD
* @returns {WalkontableCellCoords}
*/
WalkontableTable.prototype.getCoords = function (TD) {
var TR = TD.parentNode;
var row = Handsontable.Dom.index(TR);
if (TR.parentNode === this.THEAD) {
row = this.rowFilter.visibleColHeadedColumnToSourceColumn(row);
}
else {
row = this.rowFilter.visibleToSource(row);
}
return new WalkontableCellCoords(
row,
this.columnFilter.visibleRowHeadedColumnToSourceColumn(TD.cellIndex)
);
};
//returns -1 if no row is visible
WalkontableTable.prototype.getFirstVisibleRow = function () {
return this.rowFilter.visibleToSource(0 + this.rowFilter.fixedCount);
};
//returns -1 if no column is visible
WalkontableTable.prototype.getFirstVisibleColumn = function () {
if (this.isWorkingOnClone()){
if (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative){
return 0;
} else {
return this.instance.cloneSource.wtTable.getFirstVisibleColumn();
}
}
var leftOffset = this.instance.wtScrollbars.horizontal.getScrollPosition();
var columnCount = this.getColumnStrategy().cellCount;
var firstTR = this.TBODY.firstChild;
if (!firstTR){
return 0;
}
for (var colIndex = 0; colIndex < columnCount; colIndex++){
leftOffset -= firstTR.childNodes[colIndex].offsetWidth;
if (leftOffset < 0){
return colIndex;
}
}
return -1;
};
//returns -1 if no row is visible
WalkontableTable.prototype.getLastVisibleRow = function () {
var lastVisibleRow = this.rowFilter.visibleToSource(this.getRowStrategy().countVisible() - 1);
var instance = this.instance;
if (instance.cloneOverlay instanceof WalkontableVerticalScrollbarNative || instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) {
var fixedRowsTop = this.instance.getSetting('fixedRowsTop');
return Math.min(fixedRowsTop - 1, lastVisibleRow);
} else {
return lastVisibleRow;
}
};
//returns -1 if no column is visible
WalkontableTable.prototype.getLastVisibleColumn = function () {
var instance = this.instance;
if (this.isWorkingOnClone()){
if (instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || instance.cloneOverlay instanceof WalkontableCornerScrollbarNative){
var lastVisibleColumn = this.getColumnStrategy().countVisible() - 1;
var fixedColumnsLeft = instance.getSetting('fixedColumnsLeft');
return Math.min(fixedColumnsLeft - 1, lastVisibleColumn);
} else {
return this.instance.cloneSource.wtTable.getLastVisibleColumn();
}
}
var leftOffset = this.instance.wtScrollbars.horizontal.getScrollPosition();
var leftPartOfTable = leftOffset + this.instance.wtViewport.getWorkspaceWidth(Infinity);
var columnCount = this.getColumnStrategy().cellCount;
var rowHeaderCount = this.instance.getSetting('rowHeaders').length || 0;
var firstTR = this.TBODY.firstChild;
if (!columnCount) {
return -1;
}
for (var colIndex = 0; colIndex < columnCount + rowHeaderCount; colIndex++){
leftPartOfTable -= firstTR.childNodes[colIndex].offsetWidth;
if (leftPartOfTable <= 0){
return colIndex - rowHeaderCount;
}
}
return colIndex - rowHeaderCount - 1;
};
WalkontableTable.prototype.isRowBeforeViewport = function (r) {
return (this.rowFilter.sourceToVisible(r) < this.rowFilter.fixedCount && r >= this.rowFilter.fixedCount);
};
WalkontableTable.prototype.isRowAfterViewport = function (r) {
return (r > this.getLastVisibleRow());
};
WalkontableTable.prototype.isColumnBeforeViewport = function (c) {
return (this.columnFilter.sourceToVisible(c) < this.columnFilter.fixedCount && c >= this.columnFilter.fixedCount);
};
WalkontableTable.prototype.isColumnAfterViewport = function (c) {
return (c > this.getLastVisibleColumn());
};
WalkontableTable.prototype.isRowInViewport = function (r) {
return (!this.isRowBeforeViewport(r) && !this.isRowAfterViewport(r));
};
WalkontableTable.prototype.isColumnInViewport = function (c) {
return (!this.isColumnBeforeViewport(c) && !this.isColumnAfterViewport(c));
};
WalkontableTable.prototype.isLastRowFullyVisible = function () {
return (this.getLastVisibleRow() === this.instance.getSetting('totalRows') - 1 && !this.getRowStrategy().isLastIncomplete());
};
WalkontableTable.prototype.isLastColumnFullyVisible = function () {
return (this.getLastVisibleColumn() === this.instance.getSetting('totalColumns') - 1 && !this.getColumnStrategy().isLastIncomplete());
};
WalkontableTable.prototype.getVisibleRowsCount = function () {
return this.getRowStrategy().countVisible();
};
WalkontableTable.prototype.allRowsInViewport = function () {
return this.getRowStrategy().cellCount == this.getVisibleRowsCount();
};
function WalkontableTableRenderer(wtTable){
this.wtTable = wtTable;
this.instance = wtTable.instance;
this.rowFilter = wtTable.rowFilter;
this.columnFilter = wtTable.columnFilter;
this.TABLE = wtTable.TABLE;
this.THEAD = wtTable.THEAD;
this.TBODY = wtTable.TBODY;
this.COLGROUP = wtTable.COLGROUP;
this.utils = WalkontableTableRenderer.utils;
}
WalkontableTableRenderer.prototype.render = function () {
if (!this.wtTable.isWorkingOnClone()) {
this.instance.getSetting('beforeDraw', true);
}
this.rowHeaders = this.instance.getSetting('rowHeaders');
this.rowHeaderCount = this.rowHeaders.length;
this.fixedRowsTop = this.instance.getSetting('fixedRowsTop');
this.columnHeaders = this.instance.getSetting('columnHeaders');
var visibleColIndex
, totalRows = this.instance.getSetting('totalRows')
, totalColumns = this.instance.getSetting('totalColumns')
, displayTds
, TR
, TD
, TH
, adjusted = false
, workspaceWidth
, res;
if (totalColumns > 0) {
var cloneLimit;
if (this.wtTable.isWorkingOnClone()) { //must be run after adjustAvailableNodes because otherwise this.rowStrategy is not yet defined
if (this.instance.cloneOverlay instanceof WalkontableVerticalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) {
cloneLimit = this.fixedRowsTop;
}
else if (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative) {
cloneLimit = this.wtTable.getRowStrategy().cellCount;
}
//else if WalkontableDebugOverlay do nothing. No cloneLimit means render ALL rows
}
this.adjustAvailableNodes();
adjusted = true;
this.renderColGroups();
this.renderColumnHeaders();
displayTds = this.getColumnCount();
//Render table rows
this.renderRows(totalRows, cloneLimit, displayTds);
if (!this.wtTable.isWorkingOnClone()) {
workspaceWidth = this.instance.wtViewport.getWorkspaceWidth();
this.wtTable.getColumnStrategy().stretch();
}
this.adjustColumnWidths(displayTds);
}
if (!adjusted) {
this.adjustAvailableNodes();
}
if (!(this.instance.cloneOverlay instanceof WalkontableDebugOverlay)) {
this.removeRedundantRows();
}
if (!this.wtTable.isWorkingOnClone()) {
this.instance.wtScrollbars.refresh(false);
if (workspaceWidth !== this.instance.wtViewport.getWorkspaceWidth()) {
//workspace width changed though to shown/hidden vertical scrollbar. Let's reapply stretching
this.wtTable.getColumnStrategy().stretch();
for (visibleColIndex = 0; visibleColIndex < this.wtTable.getColumnStrategy().cellCount; visibleColIndex++) {
this.COLGROUP.childNodes[visibleColIndex + this.rowHeaderCount].style.width = this.wtTable.getColumnStrategy().getSize(visibleColIndex) + 'px';
}
}
this.instance.getSetting('onDraw', true);
}
};
WalkontableTableRenderer.prototype.removeRedundantRows = function () {
var renderedRowIndex = this.wtTable.getRowStrategy().countRendered();
while (this.wtTable.tbodyChildrenLength > renderedRowIndex) {
this.TBODY.removeChild(this.TBODY.lastChild);
this.wtTable.tbodyChildrenLength--;
}
};
WalkontableTableRenderer.prototype.renderRows = function (totalRows, cloneLimit, displayTds) {
var lastTD, TR, res;
var offsetRow = this.instance.getSetting('offsetRow');
var visibleRowIndex = 0;
var sourceRowIndex = this.rowFilter.visibleToSource(visibleRowIndex);
var isWorkingOnClone = this.wtTable.isWorkingOnClone();
while (sourceRowIndex < totalRows && sourceRowIndex >= 0) {
if (visibleRowIndex > 1000) {
throw new Error('Security brake: Too much TRs. Please define height for your table, which will enforce scrollbars.');
}
if (cloneLimit !== void 0 && visibleRowIndex === cloneLimit) {
break; //we have as much rows as needed for this clone
}
TR = this.getTrForRow(visibleRowIndex, TR);
//Render row headers
this.renderRowHeaders(sourceRowIndex, TR);
this.adjustColumns(TR, displayTds + this.rowHeaderCount);
lastTD = this.renderCells(sourceRowIndex, TR, displayTds);
offsetRow = this.instance.getSetting('offsetRow'); //refresh the value
//after last column is rendered, check if last cell is fully displayed
if (!isWorkingOnClone) {
res = this.wtTable.getRowStrategy().add(visibleRowIndex, lastTD);
if (res === false) {
break;
}
if (visibleRowIndex == 0) { //rendering the first row may caused bottom scrollbar to appear, so we need to refresh the window size
this.instance.wtScrollbars.vertical.readWindowSize();
}
}
if (TR.firstChild) {
var height = this.instance.getSetting('rowHeight', sourceRowIndex); //if I have 2 fixed columns with one-line content and the 3rd column has a multiline content, this is the way to make sure that the overlay will has same row height
if(height) {
TR.firstChild.style.height = height + 'px';
}
else {
TR.firstChild.style.height = '';
}
}
visibleRowIndex++;
sourceRowIndex = this.rowFilter.visibleToSource(visibleRowIndex);
}
};
WalkontableTableRenderer.prototype.renderCells = function (sourceRowIndex, TR, displayTds) {
var TD, sourceColIndex;
for (var visibleColIndex = 0; visibleColIndex < displayTds; visibleColIndex++) {
sourceColIndex = this.columnFilter.visibleToSource(visibleColIndex);
if (visibleColIndex === 0) {
TD = TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(sourceColIndex)];
}
else {
TD = TD.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
}
//If the number of headers has been reduced, we need to replace excess TH with TD
if (TD.nodeName == 'TH') {
TD = this.utils.replaceThWithTd(TD, TR);
}
TD.className = '';
TD.removeAttribute('style');
this.instance.getSetting('cellRenderer', sourceRowIndex, sourceColIndex, TD);
}
return TD;
};
WalkontableTableRenderer.prototype.adjustColumnWidths = function (displayTds) {
var cache = this.instance.wtTable.columnWidthCache;
var cacheChanged = false;
var width;
for (var visibleColIndex = 0; visibleColIndex < displayTds; visibleColIndex++) {
if(this.wtTable.isWorkingOnClone()) {
width = this.instance.cloneSource.wtTable.columnWidthCache[visibleColIndex];
}
else {
width = this.wtTable.getColumnStrategy().getSize(visibleColIndex);
}
if (width !== cache[visibleColIndex]) {
this.COLGROUP.childNodes[visibleColIndex + this.rowHeaderCount].style.width = width + 'px';
cache[visibleColIndex] = width;
cacheChanged = true;
}
}
};
WalkontableTableRenderer.prototype.appendToTbody = function (TR) {
this.TBODY.appendChild(TR);
this.wtTable.tbodyChildrenLength++;
};
WalkontableTableRenderer.prototype.getTrForRow = function (rowIndex, currentTr) {
var TR;
if (rowIndex >= this.wtTable.tbodyChildrenLength) {
TR = this.createRow();
this.appendToTbody(TR);
} else if (rowIndex === 0) {
TR = this.TBODY.firstChild;
} else {
TR = currentTr.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
}
return TR;
};
WalkontableTableRenderer.prototype.createRow = function() {
var TR = document.createElement('TR');
for (var visibleColIndex = 0; visibleColIndex < this.rowHeaderCount; visibleColIndex++) {
TR.appendChild(document.createElement('TH'));
}
return TR;
};
WalkontableTableRenderer.prototype.renderRowHeader = function(row, col, TH){
this.rowHeaders[col](row, TH);
};
WalkontableTableRenderer.prototype.renderRowHeaders = function(row, TR){
for (var TH = TR.firstChild, visibleColIndex = 0; visibleColIndex < this.rowHeaderCount; visibleColIndex++) {
//If the number of row headers increased we need to create TH or replace an existing TD node with TH
if (!TH){
TH = document.createElement('TH');
TR.appendChild(TH);
} else if (TH.nodeName == 'TD') {
TH = this.utils.replaceTdWithTh(TH, TR);
}
this.renderRowHeader(row, visibleColIndex, TH);
TH = TH.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
}
};
WalkontableTableRenderer.prototype.adjustAvailableNodes = function () {
this.refreshStretching(); //actually it is wrong position because it assumes rowHeader would be always 50px wide (because we measure before it is filled with text). TODO: debug
//adjust COLGROUP
this.adjustColGroups();
//adjust THEAD
this.adjustThead();
};
WalkontableTableRenderer.prototype.renderColumnHeaders = function () {
if (!this.columnHeaders.length) {
return;
}
var columnCount = this.getColumnCount();
var TR = this.getTrForColumnHeaders();
for (var columnIndex = 0; columnIndex < columnCount; columnIndex++) {
if (this.columnHeaders.length) {
this.renderColumnHeader( this.columnFilter.visibleToSource(columnIndex), TR.childNodes[this.rowHeaderCount + columnIndex]);
}
}
};
WalkontableTableRenderer.prototype.adjustColGroups = function () {
var columnCount = this.getColumnCount();
//adjust COLGROUP
while (this.wtTable.colgroupChildrenLength < columnCount + this.rowHeaderCount) {
this.COLGROUP.appendChild(document.createElement('COL'));
this.wtTable.colgroupChildrenLength++;
}
while (this.wtTable.colgroupChildrenLength > columnCount + this.rowHeaderCount) {
this.COLGROUP.removeChild(this.COLGROUP.lastChild);
this.wtTable.colgroupChildrenLength--;
}
};
WalkontableTableRenderer.prototype.adjustThead = function () {
var columnCount = this.getColumnCount();
var TR = this.THEAD.firstChild;
if (this.columnHeaders.length) {
if (!TR) {
TR = document.createElement('TR');
this.THEAD.appendChild(TR);
}
this.theadChildrenLength = TR.childNodes.length;
while (this.theadChildrenLength < columnCount + this.rowHeaderCount) {
TR.appendChild(document.createElement('TH'));
this.theadChildrenLength++;
}
while (this.theadChildrenLength > columnCount + this.rowHeaderCount) {
TR.removeChild(TR.lastChild);
this.theadChildrenLength--;
}
}
else if (TR) {
Handsontable.Dom.empty(TR);
}
};
WalkontableTableRenderer.prototype.getTrForColumnHeaders = function () {
var TR = this.THEAD.firstChild;
if (this.rowHeaderCount) {
this.renderRowHeaders(-1, TR);
}
return TR;
};
WalkontableTableRenderer.prototype.renderColumnHeader = function (col, TR) {
return this.columnHeaders[0](col, TR);
};
WalkontableTableRenderer.prototype.getColumnCount = function () {
if (this.wtTable.isWorkingOnClone() && (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative)) {
return this.instance.getSetting('fixedColumnsLeft');
}
else {
return this.wtTable.getColumnStrategy().cellCount;
}
};
WalkontableTableRenderer.prototype.renderColGroups = function () {
for (var colIndex = 0; colIndex < this.wtTable.colgroupChildrenLength; colIndex++) {
if (colIndex < this.rowHeaderCount) {
Handsontable.Dom.addClass(this.COLGROUP.childNodes[colIndex], 'rowHeader');
}
else {
Handsontable.Dom.removeClass(this.COLGROUP.childNodes[colIndex], 'rowHeader');
}
}
};
WalkontableTableRenderer.prototype.adjustColumns = function (TR, desiredCount) {
var count = TR.childNodes.length;
while (count < desiredCount) {
var TD = document.createElement('TD');
TR.appendChild(TD);
count++;
}
while (count > desiredCount) {
TR.removeChild(TR.lastChild);
count--;
}
};
WalkontableTableRenderer.prototype.refreshStretching = function () {
if (this.wtTable.isWorkingOnClone()) {
return;
}
var instance = this.instance
, stretchH = instance.getSetting('stretchH')
, totalRows = instance.getSetting('totalRows')
, totalColumns = instance.getSetting('totalColumns')
, offsetColumn = instance.getSetting('offsetColumn');
var containerWidthFn = function (cacheWidth) {
var viewportWidth = that.instance.wtViewport.getViewportWidth(cacheWidth);
return viewportWidth;
};
var that = this;
var columnWidthFn = function (i) {
var source_c = that.columnFilter.visibleToSource(i);
if (source_c < totalColumns) {
return instance.getSetting('columnWidth', source_c);
}
};
var containerHeightFn = function (cacheHeight) {
if (that.instance.cloneOverlay instanceof WalkontableDebugOverlay || instance.wtSettings.settings.renderAllRows) {
return Infinity;
}
else {
return that.instance.wtViewport.getViewportHeight(cacheHeight);
}
};
var rowHeightFn = function (i, TD) {
return instance.wtSettings.settings.defaultRowHeight;
};
this.wtTable.columnStrategy = new WalkontableColumnStrategy(instance, containerWidthFn, columnWidthFn, stretchH);
this.wtTable.rowStrategy = new WalkontableRowStrategy(instance, containerHeightFn, rowHeightFn);
};
/*
Helper functions, which does not have any side effects
*/
WalkontableTableRenderer.utils = {};
WalkontableTableRenderer.utils.replaceTdWithTh = function(TD, TR) {
var TH;
TH = document.createElement('TH');
TR.insertBefore(TH, TD);
TR.removeChild(TD);
return TH;
};
WalkontableTableRenderer.utils.replaceThWithTd = function(TH, TR) {
var TD = document.createElement('TD');
TR.insertBefore(TD, TH);
TR.removeChild(TH);
return TD;
};
function WalkontableViewport(instance) {
this.instance = instance;
this.resetSettings();
var that = this;
$(window).on('resize.walkontable.' + this.instance.guid, function () {
that.clientHeight = that.getWorkspaceHeight();
});
}
//used by scrollbar
WalkontableViewport.prototype.getWorkspaceHeight = function (proposedHeight) {
return this.instance.wtScrollbars.vertical.windowSize;
};
WalkontableViewport.prototype.getWorkspaceWidth = function (proposedWidth) {
if (this.instance.wtScrollbars.horizontal.scrollHandler === window){
return Math.min(document.documentElement.offsetWidth - this.getWorkspaceOffset().left, document.documentElement.offsetWidth);
}
return this.instance.wtScrollbars.horizontal.windowSize;
};
WalkontableViewport.prototype.getWorkspaceOffset = function () {
return Handsontable.Dom.offset(this.instance.wtTable.TABLE);
};
WalkontableViewport.prototype.getWorkspaceActualHeight = function () {
return Handsontable.Dom.outerHeight(this.instance.wtTable.TABLE);
};
WalkontableViewport.prototype.getWorkspaceActualWidth = function () {
return Handsontable.Dom.outerWidth(this.instance.wtTable.TABLE) || Handsontable.Dom.outerWidth(this.instance.wtTable.TBODY) || Handsontable.Dom.outerWidth(this.instance.wtTable.THEAD); //IE8 reports 0 as <table> offsetWidth;
};
WalkontableViewport.prototype.getColumnHeaderHeight = function () {
if (isNaN(this.columnHeaderHeight)) {
var cellOffset = Handsontable.Dom.offset(this.instance.wtTable.TBODY)
, tableOffset = this.instance.wtTable.tableOffset;
this.columnHeaderHeight = cellOffset.top - tableOffset.top;
}
return this.columnHeaderHeight;
};
WalkontableViewport.prototype.getViewportHeight = function (proposedHeight) {
var containerHeight = this.getWorkspaceHeight(proposedHeight);
if (containerHeight === Infinity) {
return containerHeight;
}
var columnHeaderHeight = this.getColumnHeaderHeight();
if (columnHeaderHeight > 0) {
containerHeight -= columnHeaderHeight;
}
return containerHeight;
};
WalkontableViewport.prototype.getRowHeaderWidth = function () {
if (this.instance.cloneSource) {
return this.instance.cloneSource.wtViewport.getRowHeaderWidth();
}
if (isNaN(this.rowHeaderWidth)) {
var rowHeaders = this.instance.getSetting('rowHeaders');
if (rowHeaders.length) {
var TH = this.instance.wtTable.TABLE.querySelector('TH');
this.rowHeaderWidth = 0;
for (var i = 0, ilen = rowHeaders.length; i < ilen; i++) {
if (TH) {
this.rowHeaderWidth += Handsontable.Dom.outerWidth(TH);
TH = TH.nextSibling;
}
else {
this.rowHeaderWidth += 50; //yes this is a cheat but it worked like that before, just taking assumption from CSS instead of measuring. TODO: proper fix
}
}
}
else {
this.rowHeaderWidth = 0;
}
}
return this.rowHeaderWidth;
};
WalkontableViewport.prototype.getViewportWidth = function (proposedWidth) {
var containerWidth = this.getWorkspaceWidth(proposedWidth);
if (containerWidth === Infinity) {
return containerWidth;
}
var rowHeaderWidth = this.getRowHeaderWidth();
if (rowHeaderWidth > 0) {
return containerWidth - rowHeaderWidth;
}
else {
return containerWidth;
}
};
WalkontableViewport.prototype.resetSettings = function () {
this.rowHeaderWidth = NaN;
this.columnHeaderHeight = NaN;
};
})(jQuery, window, Handsontable);
/*!
* numeral.js
* version : 1.5.3
* author : Adam Draper
* license : MIT
* http://adamwdraper.github.com/Numeral-js/
*/
(function () {
/************************************
Constants
************************************/
var numeral,
VERSION = '1.5.3',
// internal storage for language config files
languages = {},
currentLanguage = 'en',
zeroFormat = null,
defaultFormat = '0,0',
// check for nodeJS
hasModule = (typeof module !== 'undefined' && module.exports);
/************************************
Constructors
************************************/
// Numeral prototype object
function Numeral (number) {
this._value = number;
}
/**
* Implementation of toFixed() that treats floats more like decimals
*
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
* problems for accounting- and finance-related software.
*/
function toFixed (value, precision, roundingFunction, optionals) {
var power = Math.pow(10, precision),
optionalsRegExp,
output;
//roundingFunction = (roundingFunction !== undefined ? roundingFunction : Math.round);
// Multiply up by precision, round accurately, then divide and use native toFixed():
output = (roundingFunction(value * power) / power).toFixed(precision);
if (optionals) {
optionalsRegExp = new RegExp('0{1,' + optionals + '}$');
output = output.replace(optionalsRegExp, '');
}
return output;
}
/************************************
Formatting
************************************/
// determine what type of formatting we need to do
function formatNumeral (n, format, roundingFunction) {
var output;
// figure out what kind of format we are dealing with
if (format.indexOf('$') > -1) { // currency!!!!!
output = formatCurrency(n, format, roundingFunction);
} else if (format.indexOf('%') > -1) { // percentage
output = formatPercentage(n, format, roundingFunction);
} else if (format.indexOf(':') > -1) { // time
output = formatTime(n, format);
} else { // plain ol' numbers or bytes
output = formatNumber(n._value, format, roundingFunction);
}
// return string
return output;
}
// revert to number
function unformatNumeral (n, string) {
var stringOriginal = string,
thousandRegExp,
millionRegExp,
billionRegExp,
trillionRegExp,
suffixes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
bytesMultiplier = false,
power;
if (string.indexOf(':') > -1) {
n._value = unformatTime(string);
} else {
if (string === zeroFormat) {
n._value = 0;
} else {
if (languages[currentLanguage].delimiters.decimal !== '.') {
string = string.replace(/\./g,'').replace(languages[currentLanguage].delimiters.decimal, '.');
}
// see if abbreviations are there so that we can multiply to the correct number
thousandRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.thousand + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
millionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.million + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
billionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.billion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
trillionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.trillion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
// see if bytes are there so that we can multiply to the correct number
for (power = 0; power <= suffixes.length; power++) {
bytesMultiplier = (string.indexOf(suffixes[power]) > -1) ? Math.pow(1024, power + 1) : false;
if (bytesMultiplier) {
break;
}
}
// do some math to create our number
n._value = ((bytesMultiplier) ? bytesMultiplier : 1) * ((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) * ((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) * ((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) * ((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) * ((string.indexOf('%') > -1) ? 0.01 : 1) * (((string.split('-').length + Math.min(string.split('(').length-1, string.split(')').length-1)) % 2)? 1: -1) * Number(string.replace(/[^0-9\.]+/g, ''));
// round if we are talking about bytes
n._value = (bytesMultiplier) ? Math.ceil(n._value) : n._value;
}
}
return n._value;
}
function formatCurrency (n, format, roundingFunction) {
var symbolIndex = format.indexOf('$'),
openParenIndex = format.indexOf('('),
minusSignIndex = format.indexOf('-'),
space = '',
spliceIndex,
output;
// check for space before or after currency
if (format.indexOf(' $') > -1) {
space = ' ';
format = format.replace(' $', '');
} else if (format.indexOf('$ ') > -1) {
space = ' ';
format = format.replace('$ ', '');
} else {
format = format.replace('$', '');
}
// format the number
output = formatNumber(n._value, format, roundingFunction);
// position the symbol
if (symbolIndex <= 1) {
if (output.indexOf('(') > -1 || output.indexOf('-') > -1) {
output = output.split('');
spliceIndex = 1;
if (symbolIndex < openParenIndex || symbolIndex < minusSignIndex){
// the symbol appears before the "(" or "-"
spliceIndex = 0;
}
output.splice(spliceIndex, 0, languages[currentLanguage].currency.symbol + space);
output = output.join('');
} else {
output = languages[currentLanguage].currency.symbol + space + output;
}
} else {
if (output.indexOf(')') > -1) {
output = output.split('');
output.splice(-1, 0, space + languages[currentLanguage].currency.symbol);
output = output.join('');
} else {
output = output + space + languages[currentLanguage].currency.symbol;
}
}
return output;
}
function formatPercentage (n, format, roundingFunction) {
var space = '',
output,
value = n._value * 100;
// check for space before %
if (format.indexOf(' %') > -1) {
space = ' ';
format = format.replace(' %', '');
} else {
format = format.replace('%', '');
}
output = formatNumber(value, format, roundingFunction);
if (output.indexOf(')') > -1 ) {
output = output.split('');
output.splice(-1, 0, space + '%');
output = output.join('');
} else {
output = output + space + '%';
}
return output;
}
function formatTime (n) {
var hours = Math.floor(n._value/60/60),
minutes = Math.floor((n._value - (hours * 60 * 60))/60),
seconds = Math.round(n._value - (hours * 60 * 60) - (minutes * 60));
return hours + ':' + ((minutes < 10) ? '0' + minutes : minutes) + ':' + ((seconds < 10) ? '0' + seconds : seconds);
}
function unformatTime (string) {
var timeArray = string.split(':'),
seconds = 0;
// turn hours and minutes into seconds and add them all up
if (timeArray.length === 3) {
// hours
seconds = seconds + (Number(timeArray[0]) * 60 * 60);
// minutes
seconds = seconds + (Number(timeArray[1]) * 60);
// seconds
seconds = seconds + Number(timeArray[2]);
} else if (timeArray.length === 2) {
// minutes
seconds = seconds + (Number(timeArray[0]) * 60);
// seconds
seconds = seconds + Number(timeArray[1]);
}
return Number(seconds);
}
function formatNumber (value, format, roundingFunction) {
var negP = false,
signed = false,
optDec = false,
abbr = '',
abbrK = false, // force abbreviation to thousands
abbrM = false, // force abbreviation to millions
abbrB = false, // force abbreviation to billions
abbrT = false, // force abbreviation to trillions
abbrForce = false, // force abbreviation
bytes = '',
ord = '',
abs = Math.abs(value),
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
min,
max,
power,
w,
precision,
thousands,
d = '',
neg = false;
// check if number is zero and a custom zero format has been set
if (value === 0 && zeroFormat !== null) {
return zeroFormat;
} else {
// see if we should use parentheses for negative number or if we should prefix with a sign
// if both are present we default to parentheses
if (format.indexOf('(') > -1) {
negP = true;
format = format.slice(1, -1);
} else if (format.indexOf('+') > -1) {
signed = true;
format = format.replace(/\+/g, '');
}
// see if abbreviation is wanted
if (format.indexOf('a') > -1) {
// check if abbreviation is specified
abbrK = format.indexOf('aK') >= 0;
abbrM = format.indexOf('aM') >= 0;
abbrB = format.indexOf('aB') >= 0;
abbrT = format.indexOf('aT') >= 0;
abbrForce = abbrK || abbrM || abbrB || abbrT;
// check for space before abbreviation
if (format.indexOf(' a') > -1) {
abbr = ' ';
format = format.replace(' a', '');
} else {
format = format.replace('a', '');
}
if (abs >= Math.pow(10, 12) && !abbrForce || abbrT) {
// trillion
abbr = abbr + languages[currentLanguage].abbreviations.trillion;
value = value / Math.pow(10, 12);
} else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9) && !abbrForce || abbrB) {
// billion
abbr = abbr + languages[currentLanguage].abbreviations.billion;
value = value / Math.pow(10, 9);
} else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6) && !abbrForce || abbrM) {
// million
abbr = abbr + languages[currentLanguage].abbreviations.million;
value = value / Math.pow(10, 6);
} else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3) && !abbrForce || abbrK) {
// thousand
abbr = abbr + languages[currentLanguage].abbreviations.thousand;
value = value / Math.pow(10, 3);
}
}
// see if we are formatting bytes
if (format.indexOf('b') > -1) {
// check for space before
if (format.indexOf(' b') > -1) {
bytes = ' ';
format = format.replace(' b', '');
} else {
format = format.replace('b', '');
}
for (power = 0; power <= suffixes.length; power++) {
min = Math.pow(1024, power);
max = Math.pow(1024, power+1);
if (value >= min && value < max) {
bytes = bytes + suffixes[power];
if (min > 0) {
value = value / min;
}
break;
}
}
}
// see if ordinal is wanted
if (format.indexOf('o') > -1) {
// check for space before
if (format.indexOf(' o') > -1) {
ord = ' ';
format = format.replace(' o', '');
} else {
format = format.replace('o', '');
}
ord = ord + languages[currentLanguage].ordinal(value);
}
if (format.indexOf('[.]') > -1) {
optDec = true;
format = format.replace('[.]', '.');
}
w = value.toString().split('.')[0];
precision = format.split('.')[1];
thousands = format.indexOf(',');
if (precision) {
if (precision.indexOf('[') > -1) {
precision = precision.replace(']', '');
precision = precision.split('[');
d = toFixed(value, (precision[0].length + precision[1].length), roundingFunction, precision[1].length);
} else {
d = toFixed(value, precision.length, roundingFunction);
}
w = d.split('.')[0];
if (d.split('.')[1].length) {
d = languages[currentLanguage].delimiters.decimal + d.split('.')[1];
} else {
d = '';
}
if (optDec && Number(d.slice(1)) === 0) {
d = '';
}
} else {
w = toFixed(value, null, roundingFunction);
}
// format number
if (w.indexOf('-') > -1) {
w = w.slice(1);
neg = true;
}
if (thousands > -1) {
w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + languages[currentLanguage].delimiters.thousands);
}
if (format.indexOf('.') === 0) {
w = '';
}
return ((negP && neg) ? '(' : '') + ((!negP && neg) ? '-' : '') + ((!neg && signed) ? '+' : '') + w + d + ((ord) ? ord : '') + ((abbr) ? abbr : '') + ((bytes) ? bytes : '') + ((negP && neg) ? ')' : '');
}
}
/************************************
Top Level Functions
************************************/
numeral = function (input) {
if (numeral.isNumeral(input)) {
input = input.value();
} else if (input === 0 || typeof input === 'undefined') {
input = 0;
} else if (!Number(input)) {
input = numeral.fn.unformat(input);
}
return new Numeral(Number(input));
};
// version number
numeral.version = VERSION;
// compare numeral object
numeral.isNumeral = function (obj) {
return obj instanceof Numeral;
};
// This function will load languages and then set the global language. If
// no arguments are passed in, it will simply return the current global
// language key.
numeral.language = function (key, values) {
if (!key) {
return currentLanguage;
}
if (key && !values) {
if(!languages[key]) {
throw new Error('Unknown language : ' + key);
}
currentLanguage = key;
}
if (values || !languages[key]) {
loadLanguage(key, values);
}
return numeral;
};
// This function provides access to the loaded language data. If
// no arguments are passed in, it will simply return the current
// global language object.
numeral.languageData = function (key) {
if (!key) {
return languages[currentLanguage];
}
if (!languages[key]) {
throw new Error('Unknown language : ' + key);
}
return languages[key];
};
numeral.language('en', {
delimiters: {
thousands: ',',
decimal: '.'
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal: function (number) {
var b = number % 10;
return (~~ (number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
},
currency: {
symbol: '$'
}
});
numeral.zeroFormat = function (format) {
zeroFormat = typeof(format) === 'string' ? format : null;
};
numeral.defaultFormat = function (format) {
defaultFormat = typeof(format) === 'string' ? format : '0.0';
};
/************************************
Helpers
************************************/
function loadLanguage(key, values) {
languages[key] = values;
}
/************************************
Floating-point helpers
************************************/
// The floating-point helper functions and implementation
// borrows heavily from sinful.js: http://guipn.github.io/sinful.js/
/**
* Array.prototype.reduce for browsers that don't support it
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Compatibility
*/
if ('function' !== typeof Array.prototype.reduce) {
Array.prototype.reduce = function (callback, opt_initialValue) {
'use strict';
if (null === this || 'undefined' === typeof this) {
// At the moment all modern browsers, that support strict mode, have
// native implementation of Array.prototype.reduce. For instance, IE8
// does not support strict mode, so this check is actually useless.
throw new TypeError('Array.prototype.reduce called on null or undefined');
}
if ('function' !== typeof callback) {
throw new TypeError(callback + ' is not a function');
}
var index,
value,
length = this.length >>> 0,
isValueSet = false;
if (1 < arguments.length) {
value = opt_initialValue;
isValueSet = true;
}
for (index = 0; length > index; ++index) {
if (this.hasOwnProperty(index)) {
if (isValueSet) {
value = callback(value, this[index], index, this);
} else {
value = this[index];
isValueSet = true;
}
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
};
}
/**
* Computes the multiplier necessary to make x >= 1,
* effectively eliminating miscalculations caused by
* finite precision.
*/
function multiplier(x) {
var parts = x.toString().split('.');
if (parts.length < 2) {
return 1;
}
return Math.pow(10, parts[1].length);
}
/**
* Given a variable number of arguments, returns the maximum
* multiplier that must be used to normalize an operation involving
* all of them.
*/
function correctionFactor() {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function (prev, next) {
var mp = multiplier(prev),
mn = multiplier(next);
return mp > mn ? mp : mn;
}, -Infinity);
}
/************************************
Numeral Prototype
************************************/
numeral.fn = Numeral.prototype = {
clone : function () {
return numeral(this);
},
format : function (inputString, roundingFunction) {
return formatNumeral(this,
inputString ? inputString : defaultFormat,
(roundingFunction !== undefined) ? roundingFunction : Math.round
);
},
unformat : function (inputString) {
if (Object.prototype.toString.call(inputString) === '[object Number]') {
return inputString;
}
return unformatNumeral(this, inputString ? inputString : defaultFormat);
},
value : function () {
return this._value;
},
valueOf : function () {
return this._value;
},
set : function (value) {
this._value = Number(value);
return this;
},
add : function (value) {
var corrFactor = correctionFactor.call(null, this._value, value);
function cback(accum, curr, currI, O) {
return accum + corrFactor * curr;
}
this._value = [this._value, value].reduce(cback, 0) / corrFactor;
return this;
},
subtract : function (value) {
var corrFactor = correctionFactor.call(null, this._value, value);
function cback(accum, curr, currI, O) {
return accum - corrFactor * curr;
}
this._value = [value].reduce(cback, this._value * corrFactor) / corrFactor;
return this;
},
multiply : function (value) {
function cback(accum, curr, currI, O) {
var corrFactor = correctionFactor(accum, curr);
return (accum * corrFactor) * (curr * corrFactor) /
(corrFactor * corrFactor);
}
this._value = [this._value, value].reduce(cback, 1);
return this;
},
divide : function (value) {
function cback(accum, curr, currI, O) {
var corrFactor = correctionFactor(accum, curr);
return (accum * corrFactor) / (curr * corrFactor);
}
this._value = [this._value, value].reduce(cback);
return this;
},
difference : function (value) {
return Math.abs(numeral(this._value).subtract(value).value());
}
};
/************************************
Exposing Numeral
************************************/
// CommonJS module is defined
if (hasModule) {
module.exports = numeral;
}
/*global ender:false */
if (typeof ender === 'undefined') {
// here, `this` means `window` in the browser, or `global` on the server
// add `numeral` as a global object via a string identifier,
// for Closure Compiler 'advanced' mode
this['numeral'] = numeral;
}
/*global define:false */
if (typeof define === 'function' && define.amd) {
define([], function () {
return numeral;
});
}
}).call(this);
|
src/routes.js | esbb48/react-demo | import React from 'react';
import { Route } from 'react-router';
import App from './containers/App';
import * as containers from './containers';
const {
Todo,
} = containers;
export default (
<Route component={App}>
<Route path="/" component={Todo} />
</Route>
);
|
src/svg-icons/hardware/videogame-asset.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareVideogameAsset = (props) => (
<SvgIcon {...props}>
<path d="M21 6H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-10 7H8v3H6v-3H3v-2h3V8h2v3h3v2zm4.5 2c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4-3c-.83 0-1.5-.67-1.5-1.5S18.67 9 19.5 9s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/>
</SvgIcon>
);
HardwareVideogameAsset = pure(HardwareVideogameAsset);
HardwareVideogameAsset.displayName = 'HardwareVideogameAsset';
HardwareVideogameAsset.muiName = 'SvgIcon';
export default HardwareVideogameAsset;
|
packages/react-devtools-shell/src/app/InspectableElements/UnserializableProps.js | mjackson/react | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import React from 'react';
import Immutable from 'immutable';
const set = new Set(['abc', 123]);
const map = new Map([['name', 'Brian'], ['food', 'sushi']]);
const setOfSets = new Set([new Set(['a', 'b', 'c']), new Set([1, 2, 3])]);
const mapOfMaps = new Map([['first', map], ['second', map]]);
const typedArray = Int8Array.from([100, -100, 0]);
const immutable = Immutable.fromJS({
a: [{hello: 'there'}, 'fixed', true],
b: 123,
c: {
'1': 'xyz',
xyz: 1,
},
});
export default function UnserializableProps() {
return (
<ChildComponent
map={map}
set={set}
mapOfMaps={mapOfMaps}
setOfSets={setOfSets}
typedArray={typedArray}
immutable={immutable}
/>
);
}
function ChildComponent(props: any) {
return null;
}
|
app/components/TagLabels.js | y-takey/shokushu | import _ from 'lodash';
import React, { Component } from 'react';
import Color from 'material-ui/lib/styles/colors'
const tagStyle = {
color: Color.white,
backgroundColor: Color.lightBlue600
}
export default class TagLabels extends Component {
render() {
const { tags, activeTag, handler } = this.props
return (
<span>
{_.map(tags, (t) => {
let active = activeTag === t ? " active" : ""
return <span className={`tag-label${active}`} style={tagStyle} key={t} onClick={ () => handler(t) }>
<i className={`fa fa-tag`} />{t}
</span>
})}
</span>
);
}
}
|
ajax/libs/yui/3.7.1/event-focus/event-focus-min.js | rlugojr/cdnjs | YUI.add("event-focus",function(e,t){function u(t,r,u){var a="_"+t+"Notifiers";e.Event.define(t,{_attach:function(i,s,o){return e.DOM.isWindow(i)?n._attach([t,function(e){s.fire(e)},i]):n._attach([r,this._proxy,i,this,s,o],{capture:!0})},_proxy:function(t,r,i){var s=t.target,f=t.currentTarget,l=s.getData(a),c=e.stamp(f._node),h=o||s!==f,p;r.currentTarget=i?s:f,r.container=i?f:null,l?h=!0:(l={},s.setData(a,l),h&&(p=n._attach([u,this._notify,s._node]).sub,p.once=!0)),l[c]||(l[c]=[]),l[c].push(r),h||this._notify(t)},_notify:function(t,n){var r=t.currentTarget,i=r.getData(a),o=r.ancestors(),u=r.get("ownerDocument"),f=[],l=i?e.Object.keys(i).length:0,c,h,p,d,v,m,g,y,b,w;r.clearData(a),o.push(r),u&&o.unshift(u),o._nodes.reverse(),l&&(m=l,o.some(function(t){var n=e.stamp(t),r=i[n],s,o;if(r){l--;for(s=0,o=r.length;s<o;++s)r[s].handle.sub.filter&&f.push(r[s])}return!l}),l=m);while(l&&(c=o.shift())){d=e.stamp(c),h=i[d];if(h){for(g=0,y=h.length;g<y;++g){p=h[g],b=p.handle.sub,v=!0,t.currentTarget=c,b.filter&&(v=b.filter.apply(c,[c,t].concat(b.args||[])),f.splice(s(f,p),1)),v&&(t.container=p.container,w=p.fire(t));if(w===!1||t.stopped===2)break}delete h[d],l--}if(t.stopped!==2)for(g=0,y=f.length;g<y;++g){p=f[g],b=p.handle.sub,b.filter.apply(c,[c,t].concat(b.args||[]))&&(t.container=p.container,t.currentTarget=c,w=p.fire(t));if(w===!1||t.stopped===2)break}if(t.stopped)break}},on:function(e,t,n){t.handle=this._attach(e._node,n)},detach:function(e,t){t.handle.detach()},delegate:function(t,n,r,s){i(s)&&(n.filter=function(n){return e.Selector.test(n._node,s,t===n?null:t._node)}),n.handle=this._attach(t._node,r,!0)},detachDelegate:function(e,t){t.handle.detach()}},!0)}var n=e.Event,r=e.Lang,i=r.isString,s=e.Array.indexOf,o=r.isFunction(e.DOM.create('<p onbeforeactivate=";"/>').onbeforeactivate);o?(u("focus","beforeactivate","focusin"),u("blur","beforedeactivate","focusout")):(u("focus","focus","focus"),u("blur","blur","blur"))},"@VERSION@",{requires:["event-synthetic"]});
|
ajax/libs/angular-google-maps/2.1.4/angular-google-maps.js | Showfom/cdnjs | /*! angular-google-maps 2.1.4 2015-06-14
* AngularJS directives for Google Maps
* git: https://github.com/angular-ui/angular-google-maps.git
*/
;
(function( window, angular, undefined ){
'use strict';
/*
!
The MIT License
Copyright (c) 2010-2013 Google, Inc. http://angularjs.org
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.
angular-google-maps
https://github.com/angular-ui/angular-google-maps
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module('uiGmapgoogle-maps.providers', []);
angular.module('uiGmapgoogle-maps.wrapped', []);
angular.module('uiGmapgoogle-maps.extensions', ['uiGmapgoogle-maps.wrapped', 'uiGmapgoogle-maps.providers']);
angular.module('uiGmapgoogle-maps.directives.api.utils', ['uiGmapgoogle-maps.extensions']);
angular.module('uiGmapgoogle-maps.directives.api.managers', []);
angular.module('uiGmapgoogle-maps.directives.api.options', ['uiGmapgoogle-maps.directives.api.utils']);
angular.module('uiGmapgoogle-maps.directives.api.options.builders', []);
angular.module('uiGmapgoogle-maps.directives.api.models.child', ['uiGmapgoogle-maps.directives.api.utils', 'uiGmapgoogle-maps.directives.api.options', 'uiGmapgoogle-maps.directives.api.options.builders']);
angular.module('uiGmapgoogle-maps.directives.api.models.parent', ['uiGmapgoogle-maps.directives.api.managers', 'uiGmapgoogle-maps.directives.api.models.child', 'uiGmapgoogle-maps.providers']);
angular.module('uiGmapgoogle-maps.directives.api', ['uiGmapgoogle-maps.directives.api.models.parent']);
angular.module('uiGmapgoogle-maps', ['uiGmapgoogle-maps.directives.api', 'uiGmapgoogle-maps.providers']);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.providers').factory('uiGmapMapScriptLoader', [
'$q', 'uiGmapuuid', function($q, uuid) {
var getScriptUrl, includeScript, isGoogleMapsLoaded, scriptId;
scriptId = void 0;
getScriptUrl = function(options) {
if (options.china) {
return 'http://maps.google.cn/maps/api/js?';
} else {
if (options.transport === 'auto') {
return '//maps.googleapis.com/maps/api/js?';
} else {
return options.transport + '://maps.googleapis.com/maps/api/js?';
}
}
};
includeScript = function(options) {
var omitOptions, query, script;
omitOptions = ['transport', 'isGoogleMapsForWork', 'china'];
if (options.isGoogleMapsForWork) {
omitOptions.push('key');
}
query = _.map(_.omit(options, omitOptions), function(v, k) {
return k + '=' + v;
});
if (scriptId) {
document.getElementById(scriptId).remove();
}
query = query.join('&');
script = document.createElement('script');
script.id = scriptId = "ui_gmap_map_load_" + (uuid.generate());
script.type = 'text/javascript';
script.src = getScriptUrl(options) + query;
return document.body.appendChild(script);
};
isGoogleMapsLoaded = function() {
return angular.isDefined(window.google) && angular.isDefined(window.google.maps);
};
return {
load: function(options) {
var deferred, randomizedFunctionName;
deferred = $q.defer();
if (isGoogleMapsLoaded()) {
deferred.resolve(window.google.maps);
return deferred.promise;
}
randomizedFunctionName = options.callback = 'onGoogleMapsReady' + Math.round(Math.random() * 1000);
window[randomizedFunctionName] = function() {
window[randomizedFunctionName] = null;
deferred.resolve(window.google.maps);
};
if (window.navigator.connection && window.Connection && window.navigator.connection.type === window.Connection.NONE) {
document.addEventListener('online', function() {
if (!isGoogleMapsLoaded()) {
return includeScript(options);
}
});
} else {
includeScript(options);
}
return deferred.promise;
}
};
}
]).provider('uiGmapGoogleMapApi', function() {
this.options = {
transport: 'https',
isGoogleMapsForWork: false,
china: false,
v: '3',
libraries: '',
language: 'en',
sensor: 'false'
};
this.configure = function(options) {
angular.extend(this.options, options);
};
this.$get = [
'uiGmapMapScriptLoader', (function(_this) {
return function(loader) {
return loader.load(_this.options);
};
})(this)
];
return this;
});
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.extensions').service('uiGmapExtendGWin', function() {
return {
init: _.once(function() {
var uiGmapInfoBox;
if (!(google || (typeof google !== "undefined" && google !== null ? google.maps : void 0) || (google.maps.InfoWindow != null))) {
return;
}
google.maps.InfoWindow.prototype._open = google.maps.InfoWindow.prototype.open;
google.maps.InfoWindow.prototype._close = google.maps.InfoWindow.prototype.close;
google.maps.InfoWindow.prototype._isOpen = false;
google.maps.InfoWindow.prototype.open = function(map, anchor, recurse) {
if (recurse != null) {
return;
}
this._isOpen = true;
this._open(map, anchor, true);
};
google.maps.InfoWindow.prototype.close = function(recurse) {
if (recurse != null) {
return;
}
this._isOpen = false;
this._close(true);
};
google.maps.InfoWindow.prototype.isOpen = function(val) {
if (val == null) {
val = void 0;
}
if (val == null) {
return this._isOpen;
} else {
return this._isOpen = val;
}
};
/*
Do the same for InfoBox
TODO: Clean this up so the logic is defined once, wait until develop becomes master as this will be easier
*/
if (window.InfoBox) {
window.InfoBox.prototype._open = window.InfoBox.prototype.open;
window.InfoBox.prototype._close = window.InfoBox.prototype.close;
window.InfoBox.prototype._isOpen = false;
window.InfoBox.prototype.open = function(map, anchor) {
this._isOpen = true;
this._open(map, anchor);
};
window.InfoBox.prototype.close = function() {
this._isOpen = false;
this._close();
};
window.InfoBox.prototype.isOpen = function(val) {
if (val == null) {
val = void 0;
}
if (val == null) {
return this._isOpen;
} else {
return this._isOpen = val;
}
};
uiGmapInfoBox = (function(superClass) {
extend(uiGmapInfoBox, superClass);
function uiGmapInfoBox(opts) {
this.getOrigCloseBoxImg_ = bind(this.getOrigCloseBoxImg_, this);
this.getCloseBoxDiv_ = bind(this.getCloseBoxDiv_, this);
var box;
box = new window.InfoBox(opts);
_.extend(this, box);
if (opts.closeBoxDiv != null) {
this.closeBoxDiv_ = opts.closeBoxDiv;
}
}
uiGmapInfoBox.prototype.getCloseBoxDiv_ = function() {
return this.closeBoxDiv_;
};
uiGmapInfoBox.prototype.getCloseBoxImg_ = function() {
var div, img;
div = this.getCloseBoxDiv_();
img = this.getOrigCloseBoxImg_();
return div || img;
};
uiGmapInfoBox.prototype.getOrigCloseBoxImg_ = function() {
var img;
img = "";
if (this.closeBoxURL_ !== "") {
img = "<img";
img += " src='" + this.closeBoxURL_ + "'";
img += " align=right";
img += " style='";
img += " position: relative;";
img += " cursor: pointer;";
img += " margin: " + this.closeBoxMargin_ + ";";
img += "'>";
}
return img;
};
return uiGmapInfoBox;
})(window.InfoBox);
window.uiGmapInfoBox = uiGmapInfoBox;
}
if (window.MarkerLabel_) {
return window.MarkerLabel_.prototype.setContent = function() {
var content;
content = this.marker_.get('labelContent');
if (!content || _.isEqual(this.oldContent, content)) {
return;
}
if (typeof (content != null ? content.nodeType : void 0) === 'undefined') {
this.labelDiv_.innerHTML = content;
this.eventDiv_.innerHTML = this.labelDiv_.innerHTML;
this.oldContent = content;
} else {
this.labelDiv_.innerHTML = '';
this.labelDiv_.appendChild(content);
content = content.cloneNode(true);
this.labelDiv_.innerHTML = '';
this.eventDiv_.appendChild(content);
this.oldContent = content;
}
};
}
})
};
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.extensions').service('uiGmapLodash', function() {
/*
Author Nick McCready
Intersection of Objects if the arrays have something in common each intersecting object will be returned
in an new array.
*/
this.intersectionObjects = function(array1, array2, comparison) {
var res;
if (comparison == null) {
comparison = void 0;
}
res = _.map(array1, (function(_this) {
return function(obj1) {
return _.find(array2, function(obj2) {
if (comparison != null) {
return comparison(obj1, obj2);
} else {
return _.isEqual(obj1, obj2);
}
});
};
})(this));
return _.filter(res, function(o) {
return o != null;
});
};
this.containsObject = _.includeObject = function(obj, target, comparison) {
if (comparison == null) {
comparison = void 0;
}
if (obj === null) {
return false;
}
return _.any(obj, (function(_this) {
return function(value) {
if (comparison != null) {
return comparison(value, target);
} else {
return _.isEqual(value, target);
}
};
})(this));
};
this.differenceObjects = function(array1, array2, comparison) {
if (comparison == null) {
comparison = void 0;
}
return _.filter(array1, (function(_this) {
return function(value) {
return !_this.containsObject(array2, value, comparison);
};
})(this));
};
this.withoutObjects = this.differenceObjects;
this.indexOfObject = function(array, item, comparison, isSorted) {
var i, length;
if (array == null) {
return -1;
}
i = 0;
length = array.length;
if (isSorted) {
if (typeof isSorted === "number") {
i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return (array[i] === item ? i : -1);
}
}
while (i < length) {
if (comparison != null) {
if (comparison(array[i], item)) {
return i;
}
} else {
if (_.isEqual(array[i], item)) {
return i;
}
}
i++;
}
return -1;
};
this.isNullOrUndefined = function(thing) {
return _.isNull(thing || _.isUndefined(thing));
};
return this;
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.extensions').factory('uiGmapString', function() {
return function(str) {
this.contains = function(value, fromIndex) {
return str.indexOf(value, fromIndex) !== -1;
};
return this;
};
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmap_sync', [
function() {
return {
fakePromise: function() {
var _cb;
_cb = void 0;
return {
then: function(cb) {
return _cb = cb;
},
resolve: function() {
return _cb.apply(void 0, arguments);
}
};
}
};
}
]).service('uiGmap_async', [
'$timeout', 'uiGmapPromise', 'uiGmapLogger', '$q', 'uiGmapDataStructures', 'uiGmapGmapUtil', function($timeout, uiGmapPromise, $log, $q, uiGmapDataStructures, uiGmapGmapUtil) {
var ExposedPromise, PromiseQueueManager, SniffedPromise, _getArrayAndKeys, _getIterateeValue, defaultChunkSize, doChunk, doSkippPromise, each, errorObject, isInProgress, kickPromise, logTryCatch, managePromiseQueue, map, maybeCancelPromises, promiseStatus, promiseTypes, tryCatch;
promiseTypes = uiGmapPromise.promiseTypes;
isInProgress = uiGmapPromise.isInProgress;
promiseStatus = uiGmapPromise.promiseStatus;
ExposedPromise = uiGmapPromise.ExposedPromise;
SniffedPromise = uiGmapPromise.SniffedPromise;
kickPromise = function(sniffedPromise, cancelCb) {
var promise;
promise = sniffedPromise.promise();
promise.promiseType = sniffedPromise.promiseType;
if (promise.$$state) {
$log.debug("promiseType: " + promise.promiseType + ", state: " + (promiseStatus(promise.$$state.status)));
}
promise.cancelCb = cancelCb;
return promise;
};
doSkippPromise = function(sniffedPromise, lastPromise) {
if (sniffedPromise.promiseType === promiseTypes.create && lastPromise.promiseType !== promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes.init) {
$log.debug("lastPromise.promiseType " + lastPromise.promiseType + ", newPromiseType: " + sniffedPromise.promiseType + ", SKIPPED MUST COME AFTER DELETE ONLY");
return true;
}
return false;
};
maybeCancelPromises = function(queue, sniffedPromise, lastPromise) {
var first;
if (sniffedPromise.promiseType === promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes["delete"]) {
if ((lastPromise.cancelCb != null) && _.isFunction(lastPromise.cancelCb) && isInProgress(lastPromise)) {
$log.debug("promiseType: " + sniffedPromise.promiseType + ", CANCELING LAST PROMISE type: " + lastPromise.promiseType);
lastPromise.cancelCb('cancel safe');
first = queue.peek();
if ((first != null) && isInProgress(first)) {
if (first.hasOwnProperty("cancelCb") && _.isFunction(first.cancelCb)) {
$log.debug("promiseType: " + first.promiseType + ", CANCELING FIRST PROMISE type: " + first.promiseType);
return first.cancelCb('cancel safe');
} else {
return $log.warn('first promise was not cancelable');
}
}
}
}
};
/*
From a High Level:
This is a SniffedPromiseQueueManager (looking to rename) where the queue is existingPiecesObj.existingPieces.
This is a function and should not be considered a class.
So it is run to manage the state (cancel, skip, link) as needed.
Purpose:
The whole point is to check if there is existing async work going on. If so we wait on it.
arguments:
- existingPiecesObj = Queue<Promises>
- sniffedPromise = object wrapper holding a function to a pending (function) promise (promise: fnPromise)
with its intended type.
- cancelCb = callback which accepts a string, this string is intended to be returned at the end of _async.each iterator
Where the cancelCb passed msg is 'cancel safe' _async.each will drop out and fall through. Thus canceling the promise
gracefully without messing up state.
Synopsis:
- Promises have been broken down to 4 states create, update,delete (3 main) and init. (Helps boil down problems in ordering)
where (init) is special to indicate that it is one of the first or to allow a create promise to work beyond being after a delete
- Every Promise that comes is is enqueue and linked to the last promise in the queue.
- A promise can be skipped or canceled to save cycles.
Saved Cycles:
- Skipped - This will only happen if async work comes in out of order. Where a pending create promise (un-executed) comes in
after a delete promise.
- Canceled - Where an incoming promise (un-executed promise) is of type delete and the any lastPromise is not a delete type.
NOTE:
- You should not muck with existingPieces as its state is dependent on this functional loop.
- PromiseQueueManager should not be thought of as a class that has a life expectancy (it has none). It's sole
purpose is to link, skip, and kill promises. It also manages the promise queue existingPieces.
*/
PromiseQueueManager = function(existingPiecesObj, sniffedPromise, cancelCb) {
var lastPromise, newPromise;
if (!existingPiecesObj.existingPieces) {
existingPiecesObj.existingPieces = new uiGmapDataStructures.Queue();
return existingPiecesObj.existingPieces.enqueue(kickPromise(sniffedPromise, cancelCb));
} else {
lastPromise = _.last(existingPiecesObj.existingPieces._content);
if (doSkippPromise(sniffedPromise, lastPromise)) {
return;
}
maybeCancelPromises(existingPiecesObj.existingPieces, sniffedPromise, lastPromise);
newPromise = ExposedPromise(lastPromise["finally"](function() {
return kickPromise(sniffedPromise, cancelCb);
}));
newPromise.cancelCb = cancelCb;
newPromise.promiseType = sniffedPromise.promiseType;
existingPiecesObj.existingPieces.enqueue(newPromise);
return lastPromise["finally"](function() {
return existingPiecesObj.existingPieces.dequeue();
});
}
};
managePromiseQueue = function(objectToLock, promiseType, msg, cancelCb, fnPromise) {
var cancelLogger;
if (msg == null) {
msg = '';
}
cancelLogger = function(msg) {
$log.debug(msg + ": " + msg);
if ((cancelCb != null) && _.isFunction(cancelCb)) {
return cancelCb(msg);
}
};
return PromiseQueueManager(objectToLock, SniffedPromise(fnPromise, promiseType), cancelLogger);
};
defaultChunkSize = 80;
errorObject = {
value: null
};
tryCatch = function(fn, ctx, args) {
var e;
try {
return fn.apply(ctx, args);
} catch (_error) {
e = _error;
errorObject.value = e;
return errorObject;
}
};
logTryCatch = function(fn, ctx, deferred, args) {
var msg, result;
result = tryCatch(fn, ctx, args);
if (result === errorObject) {
msg = "error within chunking iterator: " + errorObject.value;
$log.error(msg);
deferred.reject(msg);
}
if (result === 'cancel safe') {
return false;
}
return true;
};
_getIterateeValue = function(collection, array, index) {
var _isArray, valOrKey;
_isArray = collection === array;
valOrKey = array[index];
if (_isArray) {
return valOrKey;
}
return collection[valOrKey];
};
_getArrayAndKeys = function(collection, keys, bailOutCb, cb) {
var array;
if (angular.isArray(collection)) {
array = collection;
} else {
array = keys ? keys : Object.keys(_.omit(collection, ['length', 'forEach', 'map']));
keys = array;
}
if (cb == null) {
cb = bailOutCb;
}
if (angular.isArray(array) && (array === void 0 || (array != null ? array.length : void 0) <= 0)) {
if (cb !== bailOutCb) {
return bailOutCb();
}
}
return cb(array, keys);
};
/*
Author: Nicholas McCready & jfriend00
_async handles things asynchronous-like :), to allow the UI to be free'd to do other things
Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui
The design of any functionality of _async is to be like lodash/underscore and replicate it but call things
asynchronously underneath. Each should be sufficient for most things to be derived from.
Optional Asynchronous Chunking via promises.
*/
doChunk = function(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, _keys) {
return _getArrayAndKeys(collection, _keys, function(array, keys) {
var cnt, i, keepGoing, val;
if (chunkSizeOrDontChunk && chunkSizeOrDontChunk < array.length) {
cnt = chunkSizeOrDontChunk;
} else {
cnt = array.length;
}
i = index;
keepGoing = true;
while (keepGoing && cnt-- && i < (array ? array.length : i + 1)) {
val = _getIterateeValue(collection, array, i);
keepGoing = angular.isFunction(val) ? true : logTryCatch(chunkCb, void 0, overallD, [val, i]);
++i;
}
if (array) {
if (keepGoing && i < array.length) {
index = i;
if (chunkSizeOrDontChunk) {
if ((pauseCb != null) && _.isFunction(pauseCb)) {
logTryCatch(pauseCb, void 0, overallD, []);
}
return $timeout(function() {
return doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, keys);
}, pauseMilli, false);
}
} else {
return overallD.resolve();
}
}
});
};
each = function(collection, chunk, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) {
var error, overallD, ret;
if (chunkSizeOrDontChunk == null) {
chunkSizeOrDontChunk = defaultChunkSize;
}
if (index == null) {
index = 0;
}
if (pauseMilli == null) {
pauseMilli = 1;
}
ret = void 0;
overallD = uiGmapPromise.defer();
ret = overallD.promise;
if (!pauseMilli) {
error = 'pause (delay) must be set from _async!';
$log.error(error);
overallD.reject(error);
return ret;
}
return _getArrayAndKeys(collection, _keys, function() {
overallD.resolve();
return ret;
}, function(array, keys) {
doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index, keys);
return ret;
});
};
map = function(collection, iterator, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) {
var results;
results = [];
return _getArrayAndKeys(collection, _keys, function() {
return uiGmapPromise.resolve(results);
}, function(array, keys) {
return each(collection, function(o) {
return results.push(iterator(o));
}, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, keys).then(function() {
return results;
});
});
};
return {
each: each,
map: map,
managePromiseQueue: managePromiseQueue,
promiseLock: managePromiseQueue,
defaultChunkSize: defaultChunkSize,
chunkSizeFrom: function(fromSize, ret) {
if (ret == null) {
ret = void 0;
}
if (_.isNumber(fromSize)) {
ret = fromSize;
}
if (uiGmapGmapUtil.isFalse(fromSize) || fromSize === false) {
ret = false;
}
return ret;
}
};
}
]);
}).call(this);
;(function() {
var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapBaseObject', function() {
var BaseObject, baseObjectKeywords;
baseObjectKeywords = ['extended', 'included'];
BaseObject = (function() {
function BaseObject() {}
BaseObject.extend = function(obj) {
var key, ref, value;
for (key in obj) {
value = obj[key];
if (indexOf.call(baseObjectKeywords, key) < 0) {
this[key] = value;
}
}
if ((ref = obj.extended) != null) {
ref.apply(this);
}
return this;
};
BaseObject.include = function(obj) {
var key, ref, value;
for (key in obj) {
value = obj[key];
if (indexOf.call(baseObjectKeywords, key) < 0) {
this.prototype[key] = value;
}
}
if ((ref = obj.included) != null) {
ref.apply(this);
}
return this;
};
return BaseObject;
})();
return BaseObject;
});
}).call(this);
;
/*
Useful function callbacks that should be defined at later time.
Mainly to be used for specs to verify creation / linking.
This is to lead a common design in notifying child stuff.
*/
(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapChildEvents', function() {
return {
onChildCreation: function(child) {}
};
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapCtrlHandle', [
'$q', function($q) {
var CtrlHandle;
return CtrlHandle = {
handle: function($scope, $element) {
$scope.$on('$destroy', function() {
return CtrlHandle.handle($scope);
});
$scope.deferred = $q.defer();
return {
getScope: function() {
return $scope;
}
};
},
mapPromise: function(scope, ctrl) {
var mapScope;
mapScope = ctrl.getScope();
mapScope.deferred.promise.then(function(map) {
return scope.map = map;
});
return mapScope.deferred.promise;
}
};
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api.utils").service("uiGmapEventsHelper", [
"uiGmapLogger", function($log) {
var _getEventsObj, _hasEvents;
_hasEvents = function(obj) {
return angular.isDefined(obj.events) && (obj.events != null) && angular.isObject(obj.events);
};
_getEventsObj = function(scope, model) {
if (_hasEvents(scope)) {
return scope;
}
if (_hasEvents(model)) {
return model;
}
};
return {
setEvents: function(gObject, scope, model, ignores) {
var eventObj;
eventObj = _getEventsObj(scope, model);
if (eventObj != null) {
return _.compact(_.map(eventObj.events, function(eventHandler, eventName) {
var doIgnore;
if (ignores) {
doIgnore = _(ignores).contains(eventName);
}
if (eventObj.events.hasOwnProperty(eventName) && angular.isFunction(eventObj.events[eventName]) && !doIgnore) {
return google.maps.event.addListener(gObject, eventName, function() {
if (!scope.$evalAsync) {
scope.$evalAsync = function() {};
}
return scope.$evalAsync(eventHandler.apply(scope, [gObject, eventName, model, arguments]));
});
}
}));
}
},
removeEvents: function(listeners) {
if (!listeners) {
return;
}
return listeners.forEach(function(l) {
if (l) {
return google.maps.event.removeListener(l);
}
});
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapFitHelper', [
'uiGmapLogger', 'uiGmap_async', function($log, _async) {
return {
fit: function(gMarkers, gMap) {
var bounds, everSet;
if (gMap && gMarkers && gMarkers.length > 0) {
bounds = new google.maps.LatLngBounds();
everSet = false;
gMarkers.forEach((function(_this) {
return function(gMarker) {
if (gMarker) {
if (!everSet) {
everSet = true;
}
return bounds.extend(gMarker.getPosition());
}
};
})(this));
if (everSet) {
return gMap.fitBounds(bounds);
}
}
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapGmapUtil', [
'uiGmapLogger', '$compile', function(Logger, $compile) {
var _isFalse, _isTruthy, getCoords, getLatitude, getLongitude, validateCoords;
_isTruthy = function(value, bool, optionsArray) {
return value === bool || optionsArray.indexOf(value) !== -1;
};
_isFalse = function(value) {
return _isTruthy(value, false, ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO']);
};
getLatitude = function(value) {
if (Array.isArray(value) && value.length === 2) {
return value[1];
} else if (angular.isDefined(value.type) && value.type === 'Point') {
return value.coordinates[1];
} else {
return value.latitude;
}
};
getLongitude = function(value) {
if (Array.isArray(value) && value.length === 2) {
return value[0];
} else if (angular.isDefined(value.type) && value.type === 'Point') {
return value.coordinates[0];
} else {
return value.longitude;
}
};
getCoords = function(value) {
if (!value) {
return;
}
if (Array.isArray(value) && value.length === 2) {
return new google.maps.LatLng(value[1], value[0]);
} else if (angular.isDefined(value.type) && value.type === 'Point') {
return new google.maps.LatLng(value.coordinates[1], value.coordinates[0]);
} else {
return new google.maps.LatLng(value.latitude, value.longitude);
}
};
validateCoords = function(coords) {
if (angular.isUndefined(coords)) {
return false;
}
if (_.isArray(coords)) {
if (coords.length === 2) {
return true;
}
} else if ((coords != null) && (coords != null ? coords.type : void 0)) {
if (coords.type === 'Point' && _.isArray(coords.coordinates) && coords.coordinates.length === 2) {
return true;
}
}
if (coords && angular.isDefined((coords != null ? coords.latitude : void 0) && angular.isDefined(coords != null ? coords.longitude : void 0))) {
return true;
}
return false;
};
return {
setCoordsFromEvent: function(prevValue, newLatLon) {
if (!prevValue) {
return;
}
if (Array.isArray(prevValue) && prevValue.length === 2) {
prevValue[1] = newLatLon.lat();
prevValue[0] = newLatLon.lng();
} else if (angular.isDefined(prevValue.type) && prevValue.type === 'Point') {
prevValue.coordinates[1] = newLatLon.lat();
prevValue.coordinates[0] = newLatLon.lng();
} else {
prevValue.latitude = newLatLon.lat();
prevValue.longitude = newLatLon.lng();
}
return prevValue;
},
getLabelPositionPoint: function(anchor) {
var xPos, yPos;
if (anchor === void 0) {
return void 0;
}
anchor = /^([-\d\.]+)\s([-\d\.]+)$/.exec(anchor);
xPos = parseFloat(anchor[1]);
yPos = parseFloat(anchor[2]);
if ((xPos != null) && (yPos != null)) {
return new google.maps.Point(xPos, yPos);
}
},
createWindowOptions: function(gMarker, scope, content, defaults) {
var options;
if ((content != null) && (defaults != null) && ($compile != null)) {
options = angular.extend({}, defaults, {
content: this.buildContent(scope, defaults, content),
position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : getCoords(scope.coords)
});
if ((gMarker != null) && ((options != null ? options.pixelOffset : void 0) == null)) {
if (options.boxClass == null) {
} else {
options.pixelOffset = {
height: 0,
width: -2
};
}
}
return options;
} else {
if (!defaults) {
Logger.error('infoWindow defaults not defined');
if (!content) {
return Logger.error('infoWindow content not defined');
}
} else {
return defaults;
}
}
},
buildContent: function(scope, defaults, content) {
var parsed, ret;
if (defaults.content != null) {
ret = defaults.content;
} else {
if ($compile != null) {
content = content.replace(/^\s+|\s+$/g, '');
parsed = content === '' ? '' : $compile(content)(scope);
if (parsed.length > 0) {
ret = parsed[0];
}
} else {
ret = content;
}
}
return ret;
},
defaultDelay: 50,
isTrue: function(value) {
return _isTruthy(value, true, ['true', 'TRUE', 1, 'y', 'Y', 'yes', 'YES']);
},
isFalse: _isFalse,
isFalsy: function(value) {
return _isTruthy(value, false, [void 0, null]) || _isFalse(value);
},
getCoords: getCoords,
validateCoords: validateCoords,
equalCoords: function(coord1, coord2) {
return getLatitude(coord1) === getLatitude(coord2) && getLongitude(coord1) === getLongitude(coord2);
},
validatePath: function(path) {
var array, i, polygon, trackMaxVertices;
i = 0;
if (angular.isUndefined(path.type)) {
if (!Array.isArray(path) || path.length < 2) {
return false;
}
while (i < path.length) {
if (!((angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) || (typeof path[i].lat === 'function' && typeof path[i].lng === 'function'))) {
return false;
}
i++;
}
return true;
} else {
if (angular.isUndefined(path.coordinates)) {
return false;
}
if (path.type === 'Polygon') {
if (path.coordinates[0].length < 4) {
return false;
}
array = path.coordinates[0];
} else if (path.type === 'MultiPolygon') {
trackMaxVertices = {
max: 0,
index: 0
};
_.forEach(path.coordinates, function(polygon, index) {
if (polygon[0].length > this.max) {
this.max = polygon[0].length;
return this.index = index;
}
}, trackMaxVertices);
polygon = path.coordinates[trackMaxVertices.index];
array = polygon[0];
if (array.length < 4) {
return false;
}
} else if (path.type === 'LineString') {
if (path.coordinates.length < 2) {
return false;
}
array = path.coordinates;
} else {
return false;
}
while (i < array.length) {
if (array[i].length !== 2) {
return false;
}
i++;
}
return true;
}
},
convertPathPoints: function(path) {
var array, i, latlng, result, trackMaxVertices;
i = 0;
result = new google.maps.MVCArray();
if (angular.isUndefined(path.type)) {
while (i < path.length) {
latlng;
if (angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) {
latlng = new google.maps.LatLng(path[i].latitude, path[i].longitude);
} else if (typeof path[i].lat === 'function' && typeof path[i].lng === 'function') {
latlng = path[i];
}
result.push(latlng);
i++;
}
} else {
array;
if (path.type === 'Polygon') {
array = path.coordinates[0];
} else if (path.type === 'MultiPolygon') {
trackMaxVertices = {
max: 0,
index: 0
};
_.forEach(path.coordinates, function(polygon, index) {
if (polygon[0].length > this.max) {
this.max = polygon[0].length;
return this.index = index;
}
}, trackMaxVertices);
array = path.coordinates[trackMaxVertices.index][0];
} else if (path.type === 'LineString') {
array = path.coordinates;
}
while (i < array.length) {
result.push(new google.maps.LatLng(array[i][1], array[i][0]));
i++;
}
}
return result;
},
extendMapBounds: function(map, points) {
var bounds, i;
bounds = new google.maps.LatLngBounds();
i = 0;
while (i < points.length) {
bounds.extend(points.getAt(i));
i++;
}
return map.fitBounds(bounds);
},
getPath: function(object, key) {
var obj;
if ((key == null) || !_.isString(key)) {
return key;
}
obj = object;
_.each(key.split('.'), function(value) {
if (obj) {
return obj = obj[value];
}
});
return obj;
},
validateBoundPoints: function(bounds) {
if (angular.isUndefined(bounds.sw.latitude) || angular.isUndefined(bounds.sw.longitude) || angular.isUndefined(bounds.ne.latitude) || angular.isUndefined(bounds.ne.longitude)) {
return false;
}
return true;
},
convertBoundPoints: function(bounds) {
var result;
result = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.sw.latitude, bounds.sw.longitude), new google.maps.LatLng(bounds.ne.latitude, bounds.ne.longitude));
return result;
},
fitMapBounds: function(map, bounds) {
return map.fitBounds(bounds);
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapIsReady', [
'$q', '$timeout', function($q, $timeout) {
var _checkIfReady, _ctr, _currentCheckNum, _maxCtrChecks, _promises, _proms;
_ctr = 0;
_proms = [];
_currentCheckNum = 1;
_maxCtrChecks = 50;
_promises = function() {
return $q.all(_proms);
};
_checkIfReady = function(deferred, expectedInstances) {
return $timeout(function() {
if (_currentCheckNum >= _maxCtrChecks) {
deferred.reject('Your maps are not found we have checked the maximum amount of times. :)');
}
_currentCheckNum += 1;
if (_ctr !== expectedInstances) {
return _checkIfReady(deferred, expectedInstances);
} else {
return deferred.resolve(_promises());
}
}, 100);
};
return {
spawn: function() {
var d;
d = $q.defer();
_proms.push(d.promise);
_ctr += 1;
return {
instance: _ctr,
deferred: d
};
},
promises: _promises,
instances: function() {
return _ctr;
},
promise: function(expectedInstances) {
var d;
if (expectedInstances == null) {
expectedInstances = 1;
}
d = $q.defer();
_checkIfReady(d, expectedInstances);
return d.promise;
},
reset: function() {
_ctr = 0;
_proms.length = 0;
},
decrement: function() {
if (_ctr > 0) {
_ctr -= 1;
}
if (_proms.length) {
_proms.length -= 1;
}
}
};
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapLinked", [
"uiGmapBaseObject", function(BaseObject) {
var Linked;
Linked = (function(superClass) {
extend(Linked, superClass);
function Linked(scope, element, attrs, ctrls) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.ctrls = ctrls;
}
return Linked;
})(BaseObject);
return Linked;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapLogger', [
'$log', function($log) {
var LEVELS, Logger, log, maybeExecLevel;
LEVELS = {
log: 1,
info: 2,
debug: 3,
warn: 4,
error: 5,
none: 6
};
maybeExecLevel = function(level, current, fn) {
if (level >= current) {
return fn();
}
};
log = function(logLevelFnName, msg) {
if ($log != null) {
return $log[logLevelFnName](msg);
} else {
return console[logLevelFnName](msg);
}
};
Logger = (function() {
function Logger() {
var logFns;
this.doLog = true;
logFns = {};
['log', 'info', 'debug', 'warn', 'error'].forEach((function(_this) {
return function(level) {
return logFns[level] = function(msg) {
if (_this.doLog) {
return maybeExecLevel(LEVELS[level], _this.currentLevel, function() {
return log(level, msg);
});
}
};
};
})(this));
this.LEVELS = LEVELS;
this.currentLevel = LEVELS.error;
this.log = logFns['log'];
this.info = logFns['info'];
this.debug = logFns['debug'];
this.warn = logFns['warn'];
this.error = logFns['error'];
}
Logger.prototype.spawn = function() {
return new Logger();
};
Logger.prototype.setLog = function(someLogger) {
return $log = someLogger;
};
return Logger;
})();
return new Logger();
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelKey', [
'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapPromise', '$q', '$timeout', function(BaseObject, GmapUtil, uiGmapPromise, $q, $timeout) {
var ModelKey;
return ModelKey = (function(superClass) {
extend(ModelKey, superClass);
function ModelKey(scope1) {
this.scope = scope1;
this.modelsLength = bind(this.modelsLength, this);
this.updateChild = bind(this.updateChild, this);
this.destroy = bind(this.destroy, this);
this.onDestroy = bind(this.onDestroy, this);
this.setChildScope = bind(this.setChildScope, this);
this.getChanges = bind(this.getChanges, this);
this.getProp = bind(this.getProp, this);
this.setIdKey = bind(this.setIdKey, this);
this.modelKeyComparison = bind(this.modelKeyComparison, this);
ModelKey.__super__.constructor.call(this);
this["interface"] = {};
this["interface"].scopeKeys = [];
this.defaultIdKey = 'id';
this.idKey = void 0;
}
ModelKey.prototype.evalModelHandle = function(model, modelKey) {
if ((model == null) || (modelKey == null)) {
return;
}
if (modelKey === 'self') {
return model;
} else {
if (_.isFunction(modelKey)) {
modelKey = modelKey();
}
return GmapUtil.getPath(model, modelKey);
}
};
ModelKey.prototype.modelKeyComparison = function(model1, model2) {
var hasCoords, isEqual, scope;
hasCoords = _.contains(this["interface"].scopeKeys, 'coords');
if (hasCoords && (this.scope.coords != null) || !hasCoords) {
scope = this.scope;
}
if (scope == null) {
throw 'No scope set!';
}
if (hasCoords) {
isEqual = GmapUtil.equalCoords(this.scopeOrModelVal('coords', scope, model1), this.scopeOrModelVal('coords', scope, model2));
if (!isEqual) {
return isEqual;
}
}
isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) {
return function(k) {
return _this.scopeOrModelVal(scope[k], scope, model1) === _this.scopeOrModelVal(scope[k], scope, model2);
};
})(this));
return isEqual;
};
ModelKey.prototype.setIdKey = function(scope) {
return this.idKey = scope.idKey != null ? scope.idKey : this.defaultIdKey;
};
ModelKey.prototype.setVal = function(model, key, newValue) {
var thingToSet;
thingToSet = this.modelOrKey(model, key);
thingToSet = newValue;
return model;
};
ModelKey.prototype.modelOrKey = function(model, key) {
if (key == null) {
return;
}
if (key !== 'self') {
return GmapUtil.getPath(model, key);
}
return model;
};
ModelKey.prototype.getProp = function(propName, scope, model) {
return this.scopeOrModelVal(propName, scope, model);
};
/*
For the cases were watching a large object we only want to know the list of props
that actually changed.
Also we want to limit the amount of props we analyze to whitelisted props that are
actually tracked by scope. (should make things faster with whitelisted)
*/
ModelKey.prototype.getChanges = function(now, prev, whitelistedProps) {
var c, changes, prop;
if (whitelistedProps) {
prev = _.pick(prev, whitelistedProps);
now = _.pick(now, whitelistedProps);
}
changes = {};
prop = {};
c = {};
for (prop in now) {
if (!prev || prev[prop] !== now[prop]) {
if (_.isArray(now[prop])) {
changes[prop] = now[prop];
} else if (_.isObject(now[prop])) {
c = this.getChanges(now[prop], (prev ? prev[prop] : null));
if (!_.isEmpty(c)) {
changes[prop] = c;
}
} else {
changes[prop] = now[prop];
}
}
}
return changes;
};
ModelKey.prototype.scopeOrModelVal = function(key, scope, model, doWrap) {
var maybeWrap, modelKey, modelProp, scopeProp;
if (doWrap == null) {
doWrap = false;
}
maybeWrap = function(isScope, ret, doWrap) {
if (doWrap == null) {
doWrap = false;
}
if (doWrap) {
return {
isScope: isScope,
value: ret
};
}
return ret;
};
scopeProp = scope[key];
if (_.isFunction(scopeProp)) {
return maybeWrap(true, scopeProp(model), doWrap);
}
if (_.isObject(scopeProp)) {
return maybeWrap(true, scopeProp, doWrap);
}
if (!_.isString(scopeProp)) {
return maybeWrap(true, scopeProp, doWrap);
}
modelKey = scopeProp;
if (!modelKey) {
modelProp = model[key];
} else {
modelProp = modelKey === 'self' ? model : model[modelKey];
}
if (_.isFunction(modelProp)) {
return maybeWrap(false, modelProp(), doWrap);
}
return maybeWrap(false, modelProp, doWrap);
};
ModelKey.prototype.setChildScope = function(keys, childScope, model) {
_.each(keys, (function(_this) {
return function(name) {
var isScopeObj, newValue;
isScopeObj = _this.scopeOrModelVal(name, childScope, model, true);
if ((isScopeObj != null ? isScopeObj.value : void 0) != null) {
newValue = isScopeObj.value;
if (newValue !== childScope[name]) {
return childScope[name] = newValue;
}
}
};
})(this));
return childScope.model = model;
};
ModelKey.prototype.onDestroy = function(scope) {};
ModelKey.prototype.destroy = function(manualOverride) {
var ref;
if (manualOverride == null) {
manualOverride = false;
}
if ((this.scope != null) && !((ref = this.scope) != null ? ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) {
return this.scope.$destroy();
} else {
return this.clean();
}
};
ModelKey.prototype.updateChild = function(child, model) {
if (model[this.idKey] == null) {
this.$log.error("Model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.");
return;
}
return child.updateModel(model);
};
ModelKey.prototype.modelsLength = function(arrayOrObjModels) {
var len, toCheck;
if (arrayOrObjModels == null) {
arrayOrObjModels = void 0;
}
len = 0;
toCheck = arrayOrObjModels ? arrayOrObjModels : this.scope.models;
if (toCheck == null) {
return len;
}
if (angular.isArray(toCheck) || (toCheck.length != null)) {
len = toCheck.length;
} else {
len = Object.keys(toCheck).length;
}
return len;
};
return ModelKey;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelsWatcher', [
'uiGmapLogger', 'uiGmap_async', '$q', 'uiGmapPromise', function(Logger, _async, $q, uiGmapPromise) {
return {
didQueueInitPromise: function(existingPiecesObj, scope) {
if (scope.models.length === 0) {
_async.promiseLock(existingPiecesObj, uiGmapPromise.promiseTypes.init, null, null, ((function(_this) {
return function() {
return uiGmapPromise.resolve();
};
})(this)));
return true;
}
return false;
},
figureOutState: function(idKey, scope, childObjects, comparison, callBack) {
var adds, children, mappedScopeModelIds, removals, updates;
adds = [];
mappedScopeModelIds = {};
removals = [];
updates = [];
scope.models.forEach(function(m) {
var child;
if (m[idKey] != null) {
mappedScopeModelIds[m[idKey]] = {};
if (childObjects.get(m[idKey]) == null) {
return adds.push(m);
} else {
child = childObjects.get(m[idKey]);
if (!comparison(m, child.clonedModel, scope)) {
return updates.push({
model: m,
child: child
});
}
}
} else {
return Logger.error(' id missing for model #{m.toString()},\ncan not use do comparison/insertion');
}
});
children = childObjects.values();
children.forEach(function(c) {
var id;
if (c == null) {
Logger.error('child undefined in ModelsWatcher.');
return;
}
if (c.model == null) {
Logger.error('child.model undefined in ModelsWatcher.');
return;
}
id = c.model[idKey];
if (mappedScopeModelIds[id] == null) {
return removals.push(c);
}
});
return {
adds: adds,
removals: removals,
updates: updates
};
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapPromise', [
'$q', '$timeout', 'uiGmapLogger', function($q, $timeout, $log) {
var ExposedPromise, SniffedPromise, defer, isInProgress, isResolved, promise, promiseStatus, promiseStatuses, promiseTypes, resolve, strPromiseStatuses;
promiseTypes = {
create: 'create',
update: 'update',
"delete": 'delete',
init: 'init'
};
promiseStatuses = {
IN_PROGRESS: 0,
RESOLVED: 1,
REJECTED: 2
};
strPromiseStatuses = (function() {
var obj;
obj = {};
obj["" + promiseStatuses.IN_PROGRESS] = 'in-progress';
obj["" + promiseStatuses.RESOLVED] = 'resolved';
obj["" + promiseStatuses.REJECTED] = 'rejected';
return obj;
})();
isInProgress = function(promise) {
if (promise.$$state) {
return promise.$$state.status === promiseStatuses.IN_PROGRESS;
}
if (!promise.hasOwnProperty("$$v")) {
return true;
}
};
isResolved = function(promise) {
if (promise.$$state) {
return promise.$$state.status === promiseStatuses.RESOLVED;
}
if (promise.hasOwnProperty("$$v")) {
return true;
}
};
promiseStatus = function(status) {
return strPromiseStatuses[status] || 'done w error';
};
ExposedPromise = function(promise) {
var cancelDeferred, combined, wrapped;
cancelDeferred = $q.defer();
combined = $q.all([promise, cancelDeferred.promise]);
wrapped = $q.defer();
promise.then(cancelDeferred.resolve, (function() {}), function(notify) {
cancelDeferred.notify(notify);
return wrapped.notify(notify);
});
combined.then(function(successes) {
return wrapped.resolve(successes[0] || successes[1]);
}, function(error) {
return wrapped.reject(error);
});
wrapped.promise.cancel = function(reason) {
if (reason == null) {
reason = 'canceled';
}
return cancelDeferred.reject(reason);
};
wrapped.promise.notify = function(msg) {
if (msg == null) {
msg = 'cancel safe';
}
wrapped.notify(msg);
if (promise.hasOwnProperty('notify')) {
return promise.notify(msg);
}
};
if (promise.promiseType != null) {
wrapped.promise.promiseType = promise.promiseType;
}
return wrapped.promise;
};
SniffedPromise = function(fnPromise, promiseType) {
return {
promise: fnPromise,
promiseType: promiseType
};
};
defer = function() {
return $q.defer();
};
resolve = function() {
var d;
d = $q.defer();
d.resolve.apply(void 0, arguments);
return d.promise;
};
promise = function(fnToWrap) {
var d;
if (!_.isFunction(fnToWrap)) {
$log.error("uiGmapPromise.promise() only accepts functions");
return;
}
d = $q.defer();
$timeout(function() {
var result;
result = fnToWrap();
return d.resolve(result);
});
return d.promise;
};
return {
defer: defer,
promise: promise,
resolve: resolve,
promiseTypes: promiseTypes,
isInProgress: isInProgress,
isResolved: isResolved,
promiseStatus: promiseStatus,
ExposedPromise: ExposedPromise,
SniffedPromise: SniffedPromise
};
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropMap", function() {
/*
Simple Object Map with a length property to make it easy to track length/size
*/
var PropMap;
return PropMap = (function() {
function PropMap() {
this.removeAll = bind(this.removeAll, this);
this.slice = bind(this.slice, this);
this.push = bind(this.push, this);
this.keys = bind(this.keys, this);
this.values = bind(this.values, this);
this.remove = bind(this.remove, this);
this.put = bind(this.put, this);
this.stateChanged = bind(this.stateChanged, this);
this.get = bind(this.get, this);
this.length = 0;
this.dict = {};
this.didValsStateChange = false;
this.didKeysStateChange = false;
this.allVals = [];
this.allKeys = [];
}
PropMap.prototype.get = function(key) {
return this.dict[key];
};
PropMap.prototype.stateChanged = function() {
this.didValsStateChange = true;
return this.didKeysStateChange = true;
};
PropMap.prototype.put = function(key, value) {
if (this.get(key) == null) {
this.length++;
}
this.stateChanged();
return this.dict[key] = value;
};
PropMap.prototype.remove = function(key, isSafe) {
var value;
if (isSafe == null) {
isSafe = false;
}
if (isSafe && !this.get(key)) {
return void 0;
}
value = this.dict[key];
delete this.dict[key];
this.length--;
this.stateChanged();
return value;
};
PropMap.prototype.valuesOrKeys = function(str) {
var keys, vals;
if (str == null) {
str = 'Keys';
}
if (!this["did" + str + "StateChange"]) {
return this['all' + str];
}
vals = [];
keys = [];
_.each(this.dict, function(v, k) {
vals.push(v);
return keys.push(k);
});
this.didKeysStateChange = false;
this.didValsStateChange = false;
this.allVals = vals;
this.allKeys = keys;
return this['all' + str];
};
PropMap.prototype.values = function() {
return this.valuesOrKeys('Vals');
};
PropMap.prototype.keys = function() {
return this.valuesOrKeys();
};
PropMap.prototype.push = function(obj, key) {
if (key == null) {
key = "key";
}
return this.put(obj[key], obj);
};
PropMap.prototype.slice = function() {
return this.keys().map((function(_this) {
return function(k) {
return _this.remove(k);
};
})(this));
};
PropMap.prototype.removeAll = function() {
return this.slice();
};
PropMap.prototype.each = function(cb) {
return _.each(this.dict, function(v, k) {
return cb(v);
});
};
PropMap.prototype.map = function(cb) {
return _.map(this.dict, function(v, k) {
return cb(v);
});
};
return PropMap;
})();
});
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropertyAction", [
"uiGmapLogger", function(Logger) {
var PropertyAction;
PropertyAction = function(setterFn) {
this.setIfChange = function(newVal, oldVal) {
var callingKey;
callingKey = this.exp;
if (!_.isEqual(oldVal, newVal)) {
return setterFn(callingKey, newVal);
}
};
this.sic = this.setIfChange;
return this;
};
return PropertyAction;
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module('uiGmapgoogle-maps.directives.api.managers').factory('uiGmapClustererMarkerManager', [
'uiGmapLogger', 'uiGmapFitHelper', 'uiGmapPropMap', function($log, FitHelper, PropMap) {
var ClustererMarkerManager;
ClustererMarkerManager = (function() {
ClustererMarkerManager.type = 'ClustererMarkerManager';
function ClustererMarkerManager(gMap, opt_markers, opt_options, opt_events) {
if (opt_markers == null) {
opt_markers = {};
}
this.opt_options = opt_options != null ? opt_options : {};
this.opt_events = opt_events;
this.checkSync = bind(this.checkSync, this);
this.getGMarkers = bind(this.getGMarkers, this);
this.fit = bind(this.fit, this);
this.destroy = bind(this.destroy, this);
this.clear = bind(this.clear, this);
this.draw = bind(this.draw, this);
this.removeMany = bind(this.removeMany, this);
this.remove = bind(this.remove, this);
this.addMany = bind(this.addMany, this);
this.update = bind(this.update, this);
this.add = bind(this.add, this);
this.type = ClustererMarkerManager.type;
this.clusterer = new NgMapMarkerClusterer(gMap, opt_markers, this.opt_options);
this.propMapGMarkers = new PropMap();
this.attachEvents(this.opt_events, 'opt_events');
this.clusterer.setIgnoreHidden(true);
this.noDrawOnSingleAddRemoves = true;
$log.info(this);
}
ClustererMarkerManager.prototype.checkKey = function(gMarker) {
var msg;
if (gMarker.key == null) {
msg = 'gMarker.key undefined and it is REQUIRED!!';
return $log.error(msg);
}
};
ClustererMarkerManager.prototype.add = function(gMarker) {
this.checkKey(gMarker);
this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves);
this.propMapGMarkers.put(gMarker.key, gMarker);
return this.checkSync();
};
ClustererMarkerManager.prototype.update = function(gMarker) {
this.remove(gMarker);
return this.add(gMarker);
};
ClustererMarkerManager.prototype.addMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(gMarker) {
return _this.add(gMarker);
};
})(this));
};
ClustererMarkerManager.prototype.remove = function(gMarker) {
var exists;
this.checkKey(gMarker);
exists = this.propMapGMarkers.get(gMarker.key);
if (exists) {
this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves);
this.propMapGMarkers.remove(gMarker.key);
}
return this.checkSync();
};
ClustererMarkerManager.prototype.removeMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(gMarker) {
return _this.remove(gMarker);
};
})(this));
};
ClustererMarkerManager.prototype.draw = function() {
return this.clusterer.repaint();
};
ClustererMarkerManager.prototype.clear = function() {
this.removeMany(this.getGMarkers());
return this.clusterer.repaint();
};
ClustererMarkerManager.prototype.attachEvents = function(options, optionsName) {
var eventHandler, eventName, results;
if (angular.isDefined(options) && (options != null) && angular.isObject(options)) {
results = [];
for (eventName in options) {
eventHandler = options[eventName];
if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) {
$log.info(optionsName + ": Attaching event: " + eventName + " to clusterer");
results.push(google.maps.event.addListener(this.clusterer, eventName, options[eventName]));
} else {
results.push(void 0);
}
}
return results;
}
};
ClustererMarkerManager.prototype.clearEvents = function(options, optionsName) {
var eventHandler, eventName, results;
if (angular.isDefined(options) && (options != null) && angular.isObject(options)) {
results = [];
for (eventName in options) {
eventHandler = options[eventName];
if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) {
$log.info(optionsName + ": Clearing event: " + eventName + " to clusterer");
results.push(google.maps.event.clearListeners(this.clusterer, eventName));
} else {
results.push(void 0);
}
}
return results;
}
};
ClustererMarkerManager.prototype.destroy = function() {
this.clearEvents(this.opt_events, 'opt_events');
return this.clear();
};
ClustererMarkerManager.prototype.fit = function() {
return FitHelper.fit(this.getGMarkers(), this.clusterer.getMap());
};
ClustererMarkerManager.prototype.getGMarkers = function() {
return this.clusterer.getMarkers().values();
};
ClustererMarkerManager.prototype.checkSync = function() {};
return ClustererMarkerManager;
})();
return ClustererMarkerManager;
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module("uiGmapgoogle-maps.directives.api.managers").factory("uiGmapMarkerManager", [
"uiGmapLogger", "uiGmapFitHelper", "uiGmapPropMap", function(Logger, FitHelper, PropMap) {
var MarkerManager;
MarkerManager = (function() {
MarkerManager.type = 'MarkerManager';
function MarkerManager(gMap, opt_markers, opt_options) {
this.getGMarkers = bind(this.getGMarkers, this);
this.fit = bind(this.fit, this);
this.handleOptDraw = bind(this.handleOptDraw, this);
this.clear = bind(this.clear, this);
this.draw = bind(this.draw, this);
this.removeMany = bind(this.removeMany, this);
this.remove = bind(this.remove, this);
this.addMany = bind(this.addMany, this);
this.update = bind(this.update, this);
this.add = bind(this.add, this);
this.type = MarkerManager.type;
this.gMap = gMap;
this.gMarkers = new PropMap();
this.$log = Logger;
this.$log.info(this);
}
MarkerManager.prototype.add = function(gMarker, optDraw) {
var exists, msg;
if (optDraw == null) {
optDraw = true;
}
if (gMarker.key == null) {
msg = "gMarker.key undefined and it is REQUIRED!!";
Logger.error(msg);
throw msg;
}
exists = this.gMarkers.get(gMarker.key);
if (!exists) {
this.handleOptDraw(gMarker, optDraw, true);
return this.gMarkers.put(gMarker.key, gMarker);
}
};
MarkerManager.prototype.update = function(gMarker, optDraw) {
if (optDraw == null) {
optDraw = true;
}
this.remove(gMarker, optDraw);
return this.add(gMarker, optDraw);
};
MarkerManager.prototype.addMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(gMarker) {
return _this.add(gMarker);
};
})(this));
};
MarkerManager.prototype.remove = function(gMarker, optDraw) {
if (optDraw == null) {
optDraw = true;
}
this.handleOptDraw(gMarker, optDraw, false);
if (this.gMarkers.get(gMarker.key)) {
return this.gMarkers.remove(gMarker.key);
}
};
MarkerManager.prototype.removeMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(marker) {
return _this.remove(marker);
};
})(this));
};
MarkerManager.prototype.draw = function() {
var deletes;
deletes = [];
this.gMarkers.each((function(_this) {
return function(gMarker) {
if (!gMarker.isDrawn) {
if (gMarker.doAdd) {
gMarker.setMap(_this.gMap);
return gMarker.isDrawn = true;
} else {
return deletes.push(gMarker);
}
}
};
})(this));
return deletes.forEach((function(_this) {
return function(gMarker) {
gMarker.isDrawn = false;
return _this.remove(gMarker, true);
};
})(this));
};
MarkerManager.prototype.clear = function() {
this.gMarkers.each(function(gMarker) {
return gMarker.setMap(null);
});
delete this.gMarkers;
return this.gMarkers = new PropMap();
};
MarkerManager.prototype.handleOptDraw = function(gMarker, optDraw, doAdd) {
if (optDraw === true) {
if (doAdd) {
gMarker.setMap(this.gMap);
} else {
gMarker.setMap(null);
}
return gMarker.isDrawn = true;
} else {
gMarker.isDrawn = false;
return gMarker.doAdd = doAdd;
}
};
MarkerManager.prototype.fit = function() {
return FitHelper.fit(this.getGMarkers(), this.gMap);
};
MarkerManager.prototype.getGMarkers = function() {
return this.gMarkers.values();
};
return MarkerManager;
})();
return MarkerManager;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').factory('uiGmapadd-events', [
'$timeout', function($timeout) {
var addEvent, addEvents;
addEvent = function(target, eventName, handler) {
return google.maps.event.addListener(target, eventName, function() {
handler.apply(this, arguments);
return $timeout((function() {}), true);
});
};
addEvents = function(target, eventName, handler) {
var remove;
if (handler) {
return addEvent(target, eventName, handler);
}
remove = [];
angular.forEach(eventName, function(_handler, key) {
return remove.push(addEvent(target, key, _handler));
});
return function() {
angular.forEach(remove, function(listener) {
return google.maps.event.removeListener(listener);
});
return remove = null;
};
};
return addEvents;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').factory('uiGmaparray-sync', [
'uiGmapadd-events', function(mapEvents) {
return function(mapArray, scope, pathEval, pathChangedFn) {
var geojsonArray, geojsonHandlers, geojsonWatcher, isSetFromScope, legacyHandlers, legacyWatcher, mapArrayListener, scopePath, watchListener;
isSetFromScope = false;
scopePath = scope.$eval(pathEval);
if (!scope["static"]) {
legacyHandlers = {
set_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return scopePath[index] = value;
} else {
scopePath[index].latitude = value.lat();
return scopePath[index].longitude = value.lng();
}
},
insert_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return scopePath.splice(index, 0, value);
} else {
return scopePath.splice(index, 0, {
latitude: value.lat(),
longitude: value.lng()
});
}
},
remove_at: function(index) {
if (isSetFromScope) {
return;
}
return scopePath.splice(index, 1);
}
};
geojsonArray;
if (scopePath.type === 'Polygon') {
geojsonArray = scopePath.coordinates[0];
} else if (scopePath.type === 'LineString') {
geojsonArray = scopePath.coordinates;
}
geojsonHandlers = {
set_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return;
}
geojsonArray[index][1] = value.lat();
return geojsonArray[index][0] = value.lng();
},
insert_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return;
}
return geojsonArray.splice(index, 0, [value.lng(), value.lat()]);
},
remove_at: function(index) {
if (isSetFromScope) {
return;
}
return geojsonArray.splice(index, 1);
}
};
mapArrayListener = mapEvents(mapArray, angular.isUndefined(scopePath.type) ? legacyHandlers : geojsonHandlers);
}
legacyWatcher = function(newPath) {
var changed, i, l, newLength, newValue, oldArray, oldLength, oldValue;
isSetFromScope = true;
oldArray = mapArray;
changed = false;
if (newPath) {
i = 0;
oldLength = oldArray.getLength();
newLength = newPath.length;
l = Math.min(oldLength, newLength);
newValue = void 0;
while (i < l) {
oldValue = oldArray.getAt(i);
newValue = newPath[i];
if (typeof newValue.equals === 'function') {
if (!newValue.equals(oldValue)) {
oldArray.setAt(i, newValue);
changed = true;
}
} else {
if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) {
oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude));
changed = true;
}
}
i++;
}
while (i < newLength) {
newValue = newPath[i];
if (typeof newValue.lat === 'function' && typeof newValue.lng === 'function') {
oldArray.push(newValue);
} else {
oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude));
}
changed = true;
i++;
}
while (i < oldLength) {
oldArray.pop();
changed = true;
i++;
}
}
isSetFromScope = false;
if (changed) {
return pathChangedFn(oldArray);
}
};
geojsonWatcher = function(newPath) {
var array, changed, i, l, newLength, newValue, oldArray, oldLength, oldValue;
isSetFromScope = true;
oldArray = mapArray;
changed = false;
if (newPath) {
array;
if (scopePath.type === 'Polygon') {
array = newPath.coordinates[0];
} else if (scopePath.type === 'LineString') {
array = newPath.coordinates;
}
i = 0;
oldLength = oldArray.getLength();
newLength = array.length;
l = Math.min(oldLength, newLength);
newValue = void 0;
while (i < l) {
oldValue = oldArray.getAt(i);
newValue = array[i];
if ((oldValue.lat() !== newValue[1]) || (oldValue.lng() !== newValue[0])) {
oldArray.setAt(i, new google.maps.LatLng(newValue[1], newValue[0]));
changed = true;
}
i++;
}
while (i < newLength) {
newValue = array[i];
oldArray.push(new google.maps.LatLng(newValue[1], newValue[0]));
changed = true;
i++;
}
while (i < oldLength) {
oldArray.pop();
changed = true;
i++;
}
}
isSetFromScope = false;
if (changed) {
return pathChangedFn(oldArray);
}
};
watchListener;
if (!scope["static"]) {
if (angular.isUndefined(scopePath.type)) {
watchListener = scope.$watchCollection(pathEval, legacyWatcher);
} else {
watchListener = scope.$watch(pathEval, geojsonWatcher, true);
}
}
return function() {
if (mapArrayListener) {
mapArrayListener();
mapArrayListener = null;
}
if (watchListener) {
watchListener();
return watchListener = null;
}
};
};
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapChromeFixes", [
'$timeout', function($timeout) {
return {
maybeRepaint: function(el) {
if (el) {
el.style.opacity = 0.9;
return $timeout(function() {
return el.style.opacity = 1;
});
}
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').service('uiGmapObjectIterators', function() {
var _ignores, _iterators, _slapForEach, _slapMap;
_ignores = ['length', 'forEach', 'map'];
_iterators = [];
_slapForEach = function(object) {
object.forEach = function(cb) {
return _.each(_.omit(object, _ignores), function(val) {
if (!_.isFunction(val)) {
return cb(val);
}
});
};
return object;
};
_iterators.push(_slapForEach);
_slapMap = function(object) {
object.map = function(cb) {
return _.map(_.omit(object, _ignores), function(val) {
if (!_.isFunction(val)) {
return cb(val);
}
});
};
return object;
};
_iterators.push(_slapMap);
return {
slapMap: _slapMap,
slapForEach: _slapForEach,
slapAll: function(object) {
_iterators.forEach(function(it) {
return it(object);
});
return object;
}
};
});
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.options.builders').service('uiGmapCommonOptionsBuilder', [
'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapModelKey', function(BaseObject, $log, ModelKey) {
var CommonOptionsBuilder;
return CommonOptionsBuilder = (function(superClass) {
extend(CommonOptionsBuilder, superClass);
function CommonOptionsBuilder() {
this.watchProps = bind(this.watchProps, this);
this.buildOpts = bind(this.buildOpts, this);
return CommonOptionsBuilder.__super__.constructor.apply(this, arguments);
}
CommonOptionsBuilder.prototype.props = [
'clickable', 'draggable', 'editable', 'visible', {
prop: 'stroke',
isColl: true
}
];
CommonOptionsBuilder.prototype.getCorrectModel = function(scope) {
if (angular.isDefined(scope != null ? scope.model : void 0)) {
return scope.model;
} else {
return scope;
}
};
CommonOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) {
var model, opts, stroke;
if (customOpts == null) {
customOpts = {};
}
if (forEachOpts == null) {
forEachOpts = {};
}
if (!this.scope) {
$log.error('this.scope not defined in CommonOptionsBuilder can not buildOpts');
return;
}
if (!this.map) {
$log.error('this.map not defined in CommonOptionsBuilder can not buildOpts');
return;
}
model = this.getCorrectModel(this.scope);
stroke = this.scopeOrModelVal('stroke', this.scope, model);
opts = angular.extend(customOpts, this.DEFAULTS, {
map: this.map,
strokeColor: stroke != null ? stroke.color : void 0,
strokeOpacity: stroke != null ? stroke.opacity : void 0,
strokeWeight: stroke != null ? stroke.weight : void 0
});
angular.forEach(angular.extend(forEachOpts, {
clickable: true,
draggable: false,
editable: false,
"static": false,
fit: false,
visible: true,
zIndex: 0,
icons: []
}), (function(_this) {
return function(defaultValue, key) {
var val;
val = cachedEval ? cachedEval[key] : _this.scopeOrModelVal(key, _this.scope, model);
if (angular.isUndefined(val)) {
return opts[key] = defaultValue;
} else {
return opts[key] = model[key];
}
};
})(this));
if (opts["static"]) {
opts.editable = false;
}
return opts;
};
CommonOptionsBuilder.prototype.watchProps = function(props) {
if (props == null) {
props = this.props;
}
return props.forEach((function(_this) {
return function(prop) {
if ((_this.attrs[prop] != null) || (_this.attrs[prop != null ? prop.prop : void 0] != null)) {
if (prop != null ? prop.isColl : void 0) {
return _this.scope.$watchCollection(prop.prop, _this.setMyOptions);
} else {
return _this.scope.$watch(prop, _this.setMyOptions);
}
}
};
})(this));
};
return CommonOptionsBuilder;
})(ModelKey);
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.options.builders').factory('uiGmapPolylineOptionsBuilder', [
'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) {
var PolylineOptionsBuilder;
return PolylineOptionsBuilder = (function(superClass) {
extend(PolylineOptionsBuilder, superClass);
function PolylineOptionsBuilder() {
return PolylineOptionsBuilder.__super__.constructor.apply(this, arguments);
}
PolylineOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) {
return PolylineOptionsBuilder.__super__.buildOpts.call(this, {
path: pathPoints
}, cachedEval, {
geodesic: false
});
};
return PolylineOptionsBuilder;
})(CommonOptionsBuilder);
}
]).factory('uiGmapShapeOptionsBuilder', [
'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) {
var ShapeOptionsBuilder;
return ShapeOptionsBuilder = (function(superClass) {
extend(ShapeOptionsBuilder, superClass);
function ShapeOptionsBuilder() {
return ShapeOptionsBuilder.__super__.constructor.apply(this, arguments);
}
ShapeOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) {
var fill, model;
model = this.getCorrectModel(this.scope);
fill = cachedEval ? cachedEval['fill'] : this.scopeOrModelVal('fill', this.scope, model);
customOpts = angular.extend(customOpts, {
fillColor: fill != null ? fill.color : void 0,
fillOpacity: fill != null ? fill.opacity : void 0
});
return ShapeOptionsBuilder.__super__.buildOpts.call(this, customOpts, cachedEval, forEachOpts);
};
return ShapeOptionsBuilder;
})(CommonOptionsBuilder);
}
]).factory('uiGmapPolygonOptionsBuilder', [
'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {
var PolygonOptionsBuilder;
return PolygonOptionsBuilder = (function(superClass) {
extend(PolygonOptionsBuilder, superClass);
function PolygonOptionsBuilder() {
return PolygonOptionsBuilder.__super__.constructor.apply(this, arguments);
}
PolygonOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) {
return PolygonOptionsBuilder.__super__.buildOpts.call(this, {
path: pathPoints
}, cachedEval, {
geodesic: false
});
};
return PolygonOptionsBuilder;
})(ShapeOptionsBuilder);
}
]).factory('uiGmapRectangleOptionsBuilder', [
'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {
var RectangleOptionsBuilder;
return RectangleOptionsBuilder = (function(superClass) {
extend(RectangleOptionsBuilder, superClass);
function RectangleOptionsBuilder() {
return RectangleOptionsBuilder.__super__.constructor.apply(this, arguments);
}
RectangleOptionsBuilder.prototype.buildOpts = function(bounds, cachedEval) {
return RectangleOptionsBuilder.__super__.buildOpts.call(this, {
bounds: bounds
}, cachedEval);
};
return RectangleOptionsBuilder;
})(ShapeOptionsBuilder);
}
]).factory('uiGmapCircleOptionsBuilder', [
'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {
var CircleOptionsBuilder;
return CircleOptionsBuilder = (function(superClass) {
extend(CircleOptionsBuilder, superClass);
function CircleOptionsBuilder() {
return CircleOptionsBuilder.__super__.constructor.apply(this, arguments);
}
CircleOptionsBuilder.prototype.buildOpts = function(center, radius, cachedEval) {
return CircleOptionsBuilder.__super__.buildOpts.call(this, {
center: center,
radius: radius
}, cachedEval);
};
return CircleOptionsBuilder;
})(ShapeOptionsBuilder);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.options').service('uiGmapMarkerOptions', [
'uiGmapLogger', 'uiGmapGmapUtil', function($log, GmapUtil) {
return _.extend(GmapUtil, {
createOptions: function(coords, icon, defaults, map) {
var opts;
if (defaults == null) {
defaults = {};
}
opts = angular.extend({}, defaults, {
position: defaults.position != null ? defaults.position : GmapUtil.getCoords(coords),
visible: defaults.visible != null ? defaults.visible : GmapUtil.validateCoords(coords)
});
if ((defaults.icon != null) || (icon != null)) {
opts = angular.extend(opts, {
icon: defaults.icon != null ? defaults.icon : icon
});
}
if (map != null) {
opts.map = map;
}
return opts;
},
isLabel: function(options) {
if (options == null) {
return false;
}
return (options.labelContent != null) || (options.labelAnchor != null) || (options.labelClass != null) || (options.labelStyle != null) || (options.labelVisible != null);
}
});
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapBasePolyChildModel', [
'uiGmapLogger', '$timeout', 'uiGmaparray-sync', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function($log, $timeout, arraySync, GmapUtil, EventsHelper) {
return function(Builder, gFactory) {
var BasePolyChildModel;
return BasePolyChildModel = (function(superClass) {
extend(BasePolyChildModel, superClass);
BasePolyChildModel.include(GmapUtil);
function BasePolyChildModel(scope, attrs, map, defaults, model) {
var create;
this.scope = scope;
this.attrs = attrs;
this.map = map;
this.defaults = defaults;
this.model = model;
this.clean = bind(this.clean, this);
this.clonedModel = _.clone(this.model, true);
this.isDragging = false;
this.internalEvents = {
dragend: (function(_this) {
return function() {
return _.defer(function() {
return _this.isDragging = false;
});
};
})(this),
dragstart: (function(_this) {
return function() {
return _this.isDragging = true;
};
})(this)
};
create = (function(_this) {
return function() {
var maybeCachedEval, pathPoints;
if (_this.isDragging) {
return;
}
pathPoints = _this.convertPathPoints(_this.scope.path);
if (_this.gObject != null) {
_this.clean();
}
if (_this.scope.model != null) {
maybeCachedEval = _this.scope;
}
if (pathPoints.length > 0) {
_this.gObject = gFactory(_this.buildOpts(pathPoints, maybeCachedEval));
}
if (_this.gObject) {
if (_this.scope.fit) {
_this.extendMapBounds(_this.map, pathPoints);
}
arraySync(_this.gObject.getPath(), _this.scope, 'path', function(pathPoints) {
if (_this.scope.fit) {
return _this.extendMapBounds(_this.map, pathPoints);
}
});
if (angular.isDefined(_this.scope.events) && angular.isObject(_this.scope.events)) {
_this.listeners = _this.model ? EventsHelper.setEvents(_this.gObject, _this.scope, _this.model) : EventsHelper.setEvents(_this.gObject, _this.scope, _this.scope);
}
return _this.internalListeners = _this.model ? EventsHelper.setEvents(_this.gObject, {
events: _this.internalEvents
}, _this.model) : EventsHelper.setEvents(_this.gObject, {
events: _this.internalEvents
}, _this.scope);
}
};
})(this);
create();
this.scope.$watch('path', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue) || !_this.gObject) {
return create();
}
};
})(this), true);
if (!this.scope["static"] && angular.isDefined(this.scope.editable)) {
this.scope.$watch('editable', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
return (ref = _this.gObject) != null ? ref.setEditable(newValue) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(this.scope.draggable)) {
this.scope.$watch('draggable', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
return (ref = _this.gObject) != null ? ref.setDraggable(newValue) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(this.scope.visible)) {
this.scope.$watch('visible', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
}
return (ref = _this.gObject) != null ? ref.setVisible(newValue) : void 0;
};
})(this), true);
}
if (angular.isDefined(this.scope.geodesic)) {
this.scope.$watch('geodesic', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.weight)) {
this.scope.$watch('stroke.weight', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.color)) {
this.scope.$watch('stroke.color', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.opacity)) {
this.scope.$watch('stroke.opacity', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(this.scope.icons)) {
this.scope.$watch('icons', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
this.scope.$on('$destroy', (function(_this) {
return function() {
_this.clean();
return _this.scope = null;
};
})(this));
if (angular.isDefined(this.scope.fill) && angular.isDefined(this.scope.fill.color)) {
this.scope.$watch('fill.color', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));
}
};
})(this));
}
if (angular.isDefined(this.scope.fill) && angular.isDefined(this.scope.fill.opacity)) {
this.scope.$watch('fill.opacity', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));
}
};
})(this));
}
if (angular.isDefined(this.scope.zIndex)) {
this.scope.$watch('zIndex', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));
}
};
})(this));
}
}
BasePolyChildModel.prototype.clean = function() {
var ref;
EventsHelper.removeEvents(this.listeners);
EventsHelper.removeEvents(this.internalListeners);
if ((ref = this.gObject) != null) {
ref.setMap(null);
}
return this.gObject = null;
};
return BasePolyChildModel;
})(Builder);
};
}
]);
}).call(this);
;
/*
@authors
Nicholas McCready - https://twitter.com/nmccready
Original idea from: http://stackoverflow.com/questions/22758950/google-map-drawing-freehand , &
http://jsfiddle.net/YsQdh/88/
*/
(function() {
angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapDrawFreeHandChildModel', [
'uiGmapLogger', '$q', function($log, $q) {
var drawFreeHand, freeHandMgr;
drawFreeHand = function(map, polys, done) {
var move, poly;
poly = new google.maps.Polyline({
map: map,
clickable: false
});
move = google.maps.event.addListener(map, 'mousemove', function(e) {
return poly.getPath().push(e.latLng);
});
google.maps.event.addListenerOnce(map, 'mouseup', function(e) {
var path;
google.maps.event.removeListener(move);
path = poly.getPath();
poly.setMap(null);
polys.push(new google.maps.Polygon({
map: map,
path: path
}));
poly = null;
google.maps.event.clearListeners(map.getDiv(), 'mousedown');
return done();
});
return void 0;
};
freeHandMgr = function(map1, scope) {
var disableMap, enableMap;
this.map = map1;
disableMap = (function(_this) {
return function() {
var mapOptions;
mapOptions = {
draggable: false,
disableDefaultUI: true,
scrollwheel: false,
disableDoubleClickZoom: false
};
$log.info('disabling map move');
return _this.map.setOptions(mapOptions);
};
})(this);
enableMap = (function(_this) {
return function() {
var mapOptions, ref;
mapOptions = {
draggable: true,
disableDefaultUI: false,
scrollwheel: true,
disableDoubleClickZoom: true
};
if ((ref = _this.deferred) != null) {
ref.resolve();
}
return _.defer(function() {
return _this.map.setOptions(_.extend(mapOptions, scope.options));
});
};
})(this);
this.engage = (function(_this) {
return function(polys1) {
_this.polys = polys1;
_this.deferred = $q.defer();
disableMap();
$log.info('DrawFreeHandChildModel is engaged (drawing).');
google.maps.event.addDomListener(_this.map.getDiv(), 'mousedown', function(e) {
return drawFreeHand(_this.map, _this.polys, enableMap);
});
return _this.deferred.promise;
};
})(this);
return this;
};
return freeHandMgr;
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapMarkerChildModel', [
'uiGmapModelKey', 'uiGmapGmapUtil', 'uiGmapLogger', 'uiGmapEventsHelper', 'uiGmapPropertyAction', 'uiGmapMarkerOptions', 'uiGmapIMarker', 'uiGmapMarkerManager', 'uiGmapPromise', function(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) {
var MarkerChildModel;
MarkerChildModel = (function(superClass) {
var destroy;
extend(MarkerChildModel, superClass);
MarkerChildModel.include(GmapUtil);
MarkerChildModel.include(EventsHelper);
MarkerChildModel.include(MarkerOptions);
destroy = function(child) {
if ((child != null ? child.gObject : void 0) != null) {
child.removeEvents(child.externalListeners);
child.removeEvents(child.internalListeners);
if (child != null ? child.gObject : void 0) {
if (child.removeFromManager) {
child.gManager.remove(child.gObject);
}
child.gObject.setMap(null);
return child.gObject = null;
}
}
};
function MarkerChildModel(scope, model1, keys, gMap, defaults, doClick, gManager, doDrawSelf, trackModel, needRedraw) {
var action;
this.model = model1;
this.keys = keys;
this.gMap = gMap;
this.defaults = defaults;
this.doClick = doClick;
this.gManager = gManager;
this.doDrawSelf = doDrawSelf != null ? doDrawSelf : true;
this.trackModel = trackModel != null ? trackModel : true;
this.needRedraw = needRedraw != null ? needRedraw : false;
this.internalEvents = bind(this.internalEvents, this);
this.setLabelOptions = bind(this.setLabelOptions, this);
this.setOptions = bind(this.setOptions, this);
this.setIcon = bind(this.setIcon, this);
this.setCoords = bind(this.setCoords, this);
this.isNotValid = bind(this.isNotValid, this);
this.maybeSetScopeValue = bind(this.maybeSetScopeValue, this);
this.createMarker = bind(this.createMarker, this);
this.setMyScope = bind(this.setMyScope, this);
this.updateModel = bind(this.updateModel, this);
this.handleModelChanges = bind(this.handleModelChanges, this);
this.destroy = bind(this.destroy, this);
this.clonedModel = _.clone(this.model, true);
this.deferred = uiGmapPromise.defer();
_.each(this.keys, (function(_this) {
return function(v, k) {
var keyValue;
keyValue = _this.keys[k];
if ((keyValue != null) && !_.isFunction(keyValue) && _.isString(keyValue)) {
return _this[k + 'Key'] = keyValue;
}
};
})(this));
this.idKey = this.idKeyKey || 'id';
if (this.model[this.idKey] != null) {
this.id = this.model[this.idKey];
}
MarkerChildModel.__super__.constructor.call(this, scope);
this.scope.getGMarker = (function(_this) {
return function() {
return _this.gObject;
};
})(this);
this.firstTime = true;
if (this.trackModel) {
this.scope.model = this.model;
this.scope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.handleModelChanges(newValue, oldValue);
}
};
})(this), true);
} else {
action = new PropertyAction((function(_this) {
return function(calledKey, newVal) {
if (!_this.firstTime) {
return _this.setMyScope(calledKey, scope);
}
};
})(this), false);
_.each(this.keys, function(v, k) {
return scope.$watch(k, action.sic, true);
});
}
this.scope.$on('$destroy', (function(_this) {
return function() {
return destroy(_this);
};
})(this));
this.createMarker(this.model);
$log.info(this);
}
MarkerChildModel.prototype.destroy = function(removeFromManager) {
if (removeFromManager == null) {
removeFromManager = true;
}
this.removeFromManager = removeFromManager;
return this.scope.$destroy();
};
MarkerChildModel.prototype.handleModelChanges = function(newValue, oldValue) {
var changes, ctr, len;
changes = this.getChanges(newValue, oldValue, IMarker.keys);
if (!this.firstTime) {
ctr = 0;
len = _.keys(changes).length;
return _.each(changes, (function(_this) {
return function(v, k) {
var doDraw;
ctr += 1;
doDraw = len === ctr;
_this.setMyScope(k, newValue, oldValue, false, true, doDraw);
return _this.needRedraw = true;
};
})(this));
}
};
MarkerChildModel.prototype.updateModel = function(model) {
this.clonedModel = _.clone(model, true);
return this.setMyScope('all', model, this.model);
};
MarkerChildModel.prototype.renderGMarker = function(doDraw, validCb) {
var coords;
if (doDraw == null) {
doDraw = true;
}
coords = this.getProp('coords', this.scope, this.model);
if (coords != null) {
if (!this.validateCoords(coords)) {
$log.debug('MarkerChild does not have coords yet. They may be defined later.');
return;
}
if (validCb != null) {
validCb();
}
if (doDraw && this.gObject) {
return this.gManager.add(this.gObject);
}
} else {
if (doDraw && this.gObject) {
return this.gManager.remove(this.gObject);
}
}
};
MarkerChildModel.prototype.setMyScope = function(thingThatChanged, model, oldModel, isInit, doDraw) {
var justCreated;
if (oldModel == null) {
oldModel = void 0;
}
if (isInit == null) {
isInit = false;
}
if (doDraw == null) {
doDraw = true;
}
if (model == null) {
model = this.model;
} else {
this.model = model;
}
if (!this.gObject) {
this.setOptions(this.scope, doDraw);
justCreated = true;
}
switch (thingThatChanged) {
case 'all':
return _.each(this.keys, (function(_this) {
return function(v, k) {
return _this.setMyScope(k, model, oldModel, isInit, doDraw);
};
})(this));
case 'icon':
return this.maybeSetScopeValue('icon', model, oldModel, this.iconKey, this.evalModelHandle, isInit, this.setIcon, doDraw);
case 'coords':
return this.maybeSetScopeValue('coords', model, oldModel, this.coordsKey, this.evalModelHandle, isInit, this.setCoords, doDraw);
case 'options':
if (!justCreated) {
return this.createMarker(model, oldModel, isInit, doDraw);
}
}
};
MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit, doDraw) {
if (oldModel == null) {
oldModel = void 0;
}
if (isInit == null) {
isInit = false;
}
if (doDraw == null) {
doDraw = true;
}
this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, this.evalModelHandle, isInit, this.setOptions, doDraw);
return this.firstTime = false;
};
MarkerChildModel.prototype.maybeSetScopeValue = function(scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter, doDraw) {
if (gSetter == null) {
gSetter = void 0;
}
if (doDraw == null) {
doDraw = true;
}
if (gSetter != null) {
return gSetter(this.scope, doDraw);
}
};
if (MarkerChildModel.doDrawSelf && doDraw) {
MarkerChildModel.gManager.draw();
}
MarkerChildModel.prototype.isNotValid = function(scope, doCheckGmarker) {
var hasIdenticalScopes, hasNoGmarker;
if (doCheckGmarker == null) {
doCheckGmarker = true;
}
hasNoGmarker = !doCheckGmarker ? false : this.gObject === void 0;
hasIdenticalScopes = !this.trackModel ? scope.$id !== this.scope.$id : false;
return hasIdenticalScopes || hasNoGmarker;
};
MarkerChildModel.prototype.setCoords = function(scope, doDraw) {
if (doDraw == null) {
doDraw = true;
}
if (this.isNotValid(scope) || (this.gObject == null)) {
return;
}
return this.renderGMarker(doDraw, (function(_this) {
return function() {
var newGValue, newModelVal, oldGValue;
newModelVal = _this.getProp('coords', scope, _this.model);
newGValue = _this.getCoords(newModelVal);
oldGValue = _this.gObject.getPosition();
if ((oldGValue != null) && (newGValue != null)) {
if (newGValue.lng() === oldGValue.lng() && newGValue.lat() === oldGValue.lat()) {
return;
}
}
_this.gObject.setPosition(newGValue);
return _this.gObject.setVisible(_this.validateCoords(newModelVal));
};
})(this));
};
MarkerChildModel.prototype.setIcon = function(scope, doDraw) {
if (doDraw == null) {
doDraw = true;
}
if (this.isNotValid(scope) || (this.gObject == null)) {
return;
}
return this.renderGMarker(doDraw, (function(_this) {
return function() {
var coords, newValue, oldValue;
oldValue = _this.gObject.getIcon();
newValue = _this.getProp('icon', scope, _this.model);
if (oldValue === newValue) {
return;
}
_this.gObject.setIcon(newValue);
coords = _this.getProp('coords', scope, _this.model);
_this.gObject.setPosition(_this.getCoords(coords));
return _this.gObject.setVisible(_this.validateCoords(coords));
};
})(this));
};
MarkerChildModel.prototype.setOptions = function(scope, doDraw) {
var ref;
if (doDraw == null) {
doDraw = true;
}
if (this.isNotValid(scope, false)) {
return;
}
this.renderGMarker(doDraw, (function(_this) {
return function() {
var _options, coords, icon;
coords = _this.getProp('coords', scope, _this.model);
icon = _this.getProp('icon', scope, _this.model);
_options = _this.getProp('options', scope, _this.model);
_this.opts = _this.createOptions(coords, icon, _options);
if (_this.isLabel(_this.gObject) !== _this.isLabel(_this.opts) && (_this.gObject != null)) {
_this.gManager.remove(_this.gObject);
_this.gObject = void 0;
}
if (_this.gObject != null) {
_this.gObject.setOptions(_this.setLabelOptions(_this.opts));
}
if (!_this.gObject) {
if (_this.isLabel(_this.opts)) {
_this.gObject = new MarkerWithLabel(_this.setLabelOptions(_this.opts));
} else if (_this.opts.content) {
_this.gObject = new RichMarker(_this.opts);
_this.gObject.getIcon = _this.gObject.getContent;
_this.gObject.setIcon = _this.gObject.setContent;
} else {
_this.gObject = new google.maps.Marker(_this.opts);
}
_.extend(_this.gObject, {
model: _this.model
});
}
if (_this.externalListeners) {
_this.removeEvents(_this.externalListeners);
}
if (_this.internalListeners) {
_this.removeEvents(_this.internalListeners);
}
_this.externalListeners = _this.setEvents(_this.gObject, _this.scope, _this.model, ['dragend']);
_this.internalListeners = _this.setEvents(_this.gObject, {
events: _this.internalEvents(),
$evalAsync: function() {}
}, _this.model);
if (_this.id != null) {
return _this.gObject.key = _this.id;
}
};
})(this));
if (this.gObject && (this.gObject.getMap() || this.gManager.type !== MarkerManager.type)) {
this.deferred.resolve(this.gObject);
} else {
if (!this.gObject) {
return this.deferred.reject('gObject is null');
}
if (!(((ref = this.gObject) != null ? ref.getMap() : void 0) && this.gManager.type === MarkerManager.type)) {
$log.debug('gObject has no map yet');
this.deferred.resolve(this.gObject);
}
}
if (this.model[this.fitKey]) {
return this.gManager.fit();
}
};
MarkerChildModel.prototype.setLabelOptions = function(opts) {
if (opts.labelAnchor) {
opts.labelAnchor = this.getLabelPositionPoint(opts.labelAnchor);
}
return opts;
};
MarkerChildModel.prototype.internalEvents = function() {
return {
dragend: (function(_this) {
return function(marker, eventName, model, mousearg) {
var events, modelToSet, newCoords;
modelToSet = _this.trackModel ? _this.scope.model : _this.model;
newCoords = _this.setCoordsFromEvent(_this.modelOrKey(modelToSet, _this.coordsKey), _this.gObject.getPosition());
modelToSet = _this.setVal(model, _this.coordsKey, newCoords);
events = _this.scope.events;
if ((events != null ? events.dragend : void 0) != null) {
events.dragend(marker, eventName, modelToSet, mousearg);
}
return _this.scope.$apply();
};
})(this),
click: (function(_this) {
return function(marker, eventName, model, mousearg) {
var click;
click = _this.getProp('click', _this.scope, _this.model);
if (_this.doClick && (click != null)) {
return _this.scope.$evalAsync(click(marker, eventName, _this.model, mousearg));
}
};
})(this)
};
};
return MarkerChildModel;
})(ModelKey);
return MarkerChildModel;
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygonChildModel', [
'uiGmapBasePolyChildModel', 'uiGmapPolygonOptionsBuilder', function(BaseGen, Builder) {
var PolygonChildModel, base, gFactory;
gFactory = function(opts) {
return new google.maps.Polygon(opts);
};
base = new BaseGen(Builder, gFactory);
return PolygonChildModel = (function(superClass) {
extend(PolygonChildModel, superClass);
function PolygonChildModel() {
return PolygonChildModel.__super__.constructor.apply(this, arguments);
}
return PolygonChildModel;
})(base);
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylineChildModel', [
'uiGmapBasePolyChildModel', 'uiGmapPolylineOptionsBuilder', function(BaseGen, Builder) {
var PolylineChildModel, base, gFactory;
gFactory = function(opts) {
return new google.maps.Polyline(opts);
};
base = BaseGen(Builder, gFactory);
return PolylineChildModel = (function(superClass) {
extend(PolylineChildModel, superClass);
function PolylineChildModel() {
return PolylineChildModel.__super__.constructor.apply(this, arguments);
}
return PolylineChildModel;
})(base);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapWindowChildModel', [
'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapLogger', '$compile', '$http', '$templateCache', 'uiGmapChromeFixes', 'uiGmapEventsHelper', function(BaseObject, GmapUtil, $log, $compile, $http, $templateCache, ChromeFixes, EventsHelper) {
var WindowChildModel;
WindowChildModel = (function(superClass) {
extend(WindowChildModel, superClass);
WindowChildModel.include(GmapUtil);
WindowChildModel.include(EventsHelper);
function WindowChildModel(model1, scope1, opts, isIconVisibleOnClick, mapCtrl, markerScope, element, needToManualDestroy, markerIsVisibleAfterWindowClose) {
var maybeMarker;
this.model = model1;
this.scope = scope1;
this.opts = opts;
this.isIconVisibleOnClick = isIconVisibleOnClick;
this.mapCtrl = mapCtrl;
this.markerScope = markerScope;
this.element = element;
this.needToManualDestroy = needToManualDestroy != null ? needToManualDestroy : false;
this.markerIsVisibleAfterWindowClose = markerIsVisibleAfterWindowClose != null ? markerIsVisibleAfterWindowClose : true;
this.updateModel = bind(this.updateModel, this);
this.destroy = bind(this.destroy, this);
this.remove = bind(this.remove, this);
this.getLatestPosition = bind(this.getLatestPosition, this);
this.hideWindow = bind(this.hideWindow, this);
this.showWindow = bind(this.showWindow, this);
this.handleClick = bind(this.handleClick, this);
this.watchOptions = bind(this.watchOptions, this);
this.watchCoords = bind(this.watchCoords, this);
this.createGWin = bind(this.createGWin, this);
this.watchElement = bind(this.watchElement, this);
this.watchAndDoShow = bind(this.watchAndDoShow, this);
this.doShow = bind(this.doShow, this);
this.clonedModel = _.clone(this.model, true);
this.getGmarker = function() {
var ref, ref1;
if (((ref = this.markerScope) != null ? ref['getGMarker'] : void 0) != null) {
return (ref1 = this.markerScope) != null ? ref1.getGMarker() : void 0;
}
};
this.listeners = [];
this.createGWin();
maybeMarker = this.getGmarker();
if (maybeMarker != null) {
maybeMarker.setClickable(true);
}
this.watchElement();
this.watchOptions();
this.watchCoords();
this.watchAndDoShow();
this.scope.$on('$destroy', (function(_this) {
return function() {
return _this.destroy();
};
})(this));
$log.info(this);
}
WindowChildModel.prototype.doShow = function(wasOpen) {
if (this.scope.show === true || wasOpen) {
return this.showWindow();
} else {
return this.hideWindow();
}
};
WindowChildModel.prototype.watchAndDoShow = function() {
if (this.model.show != null) {
this.scope.show = this.model.show;
}
this.scope.$watch('show', this.doShow, true);
return this.doShow();
};
WindowChildModel.prototype.watchElement = function() {
return this.scope.$watch((function(_this) {
return function() {
var ref, wasOpen;
if (!(_this.element || _this.html)) {
return;
}
if (_this.html !== _this.element.html() && _this.gObject) {
if ((ref = _this.opts) != null) {
ref.content = void 0;
}
wasOpen = _this.gObject.isOpen();
_this.remove();
return _this.createGWin(wasOpen);
}
};
})(this));
};
WindowChildModel.prototype.createGWin = function(isOpen) {
var _opts, defaults, maybeMarker, ref, ref1;
if (isOpen == null) {
isOpen = false;
}
maybeMarker = this.getGmarker();
defaults = {};
if (this.opts != null) {
if (this.scope.coords) {
this.opts.position = this.getCoords(this.scope.coords);
}
defaults = this.opts;
}
if (this.element) {
this.html = _.isObject(this.element) ? this.element.html() : this.element;
}
_opts = this.scope.options ? this.scope.options : defaults;
this.opts = this.createWindowOptions(maybeMarker, this.markerScope || this.scope, this.html, _opts);
if (this.opts != null) {
if (!this.gObject) {
if (this.opts.boxClass && (window.InfoBox && typeof window.InfoBox === 'function')) {
this.gObject = new window.InfoBox(this.opts);
} else {
this.gObject = new google.maps.InfoWindow(this.opts);
}
this.listeners.push(google.maps.event.addListener(this.gObject, 'domready', function() {
return ChromeFixes.maybeRepaint(this.content);
}));
this.listeners.push(google.maps.event.addListener(this.gObject, 'closeclick', (function(_this) {
return function() {
if (maybeMarker) {
maybeMarker.setAnimation(_this.oldMarkerAnimation);
if (_this.markerIsVisibleAfterWindowClose) {
_.delay(function() {
maybeMarker.setVisible(false);
return maybeMarker.setVisible(_this.markerIsVisibleAfterWindowClose);
}, 250);
}
}
_this.gObject.close();
_this.model.show = false;
if (_this.scope.closeClick != null) {
return _this.scope.$evalAsync(_this.scope.closeClick());
} else {
return _this.scope.$evalAsync();
}
};
})(this)));
}
this.gObject.setContent(this.opts.content);
this.handleClick(((ref = this.scope) != null ? (ref1 = ref.options) != null ? ref1.forceClick : void 0 : void 0) || isOpen);
return this.doShow(this.gObject.isOpen());
}
};
WindowChildModel.prototype.watchCoords = function() {
var scope;
scope = this.markerScope != null ? this.markerScope : this.scope;
return scope.$watch('coords', (function(_this) {
return function(newValue, oldValue) {
var pos;
if (newValue !== oldValue) {
if (newValue == null) {
_this.hideWindow();
} else if (!_this.validateCoords(newValue)) {
$log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model)));
return;
}
pos = _this.getCoords(newValue);
_this.doShow();
_this.gObject.setPosition(pos);
if (_this.opts) {
return _this.opts.position = pos;
}
}
};
})(this), true);
};
WindowChildModel.prototype.watchOptions = function() {
return this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.opts = newValue;
if (_this.gObject != null) {
_this.gObject.setOptions(_this.opts);
if ((_this.opts.visible != null) && _this.opts.visible) {
return _this.showWindow();
} else if (_this.opts.visible != null) {
return _this.hideWindow();
}
}
}
};
})(this), true);
};
WindowChildModel.prototype.handleClick = function(forceClick) {
var click, maybeMarker;
if (this.gObject == null) {
return;
}
maybeMarker = this.getGmarker();
click = (function(_this) {
return function() {
if (_this.gObject == null) {
_this.createGWin();
}
_this.showWindow();
if (maybeMarker != null) {
_this.initialMarkerVisibility = maybeMarker.getVisible();
_this.oldMarkerAnimation = maybeMarker.getAnimation();
return maybeMarker.setVisible(_this.isIconVisibleOnClick);
}
};
})(this);
if (forceClick) {
click();
}
if (maybeMarker) {
return this.listeners = this.listeners.concat(this.setEvents(maybeMarker, {
events: {
click: click
}
}, this.model));
}
};
WindowChildModel.prototype.showWindow = function() {
var compiled, show, templateScope;
if (this.gObject != null) {
show = (function(_this) {
return function() {
var isOpen, maybeMarker, pos;
if (!_this.gObject.isOpen()) {
maybeMarker = _this.getGmarker();
if ((_this.gObject != null) && (_this.gObject.getPosition != null)) {
pos = _this.gObject.getPosition();
}
if (maybeMarker) {
pos = maybeMarker.getPosition();
}
if (!pos) {
return;
}
_this.gObject.open(_this.mapCtrl, maybeMarker);
isOpen = _this.gObject.isOpen();
if (_this.model.show !== isOpen) {
return _this.model.show = isOpen;
}
}
};
})(this);
if (this.scope.templateUrl) {
return $http.get(this.scope.templateUrl, {
cache: $templateCache
}).then((function(_this) {
return function(content) {
var compiled, templateScope;
templateScope = _this.scope.$new();
if (angular.isDefined(_this.scope.templateParameter)) {
templateScope.parameter = _this.scope.templateParameter;
}
compiled = $compile(content.data)(templateScope);
_this.gObject.setContent(compiled[0]);
return show();
};
})(this));
} else if (this.scope.template) {
templateScope = this.scope.$new();
if (angular.isDefined(this.scope.templateParameter)) {
templateScope.parameter = this.scope.templateParameter;
}
compiled = $compile(this.scope.template)(templateScope);
this.gObject.setContent(compiled[0]);
return show();
} else {
return show();
}
}
};
WindowChildModel.prototype.hideWindow = function() {
if ((this.gObject != null) && this.gObject.isOpen()) {
return this.gObject.close();
}
};
WindowChildModel.prototype.getLatestPosition = function(overridePos) {
var maybeMarker;
maybeMarker = this.getGmarker();
if ((this.gObject != null) && (maybeMarker != null) && !overridePos) {
return this.gObject.setPosition(maybeMarker.getPosition());
} else {
if (overridePos) {
return this.gObject.setPosition(overridePos);
}
}
};
WindowChildModel.prototype.remove = function() {
this.hideWindow();
this.removeEvents(this.listeners);
this.listeners.length = 0;
delete this.gObject;
return delete this.opts;
};
WindowChildModel.prototype.destroy = function(manualOverride) {
var ref;
if (manualOverride == null) {
manualOverride = false;
}
this.remove();
if ((this.scope != null) && !((ref = this.scope) != null ? ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) {
return this.scope.$destroy();
}
};
WindowChildModel.prototype.updateModel = function(model) {
this.clonedModel = _.clone(model, true);
return _.extend(this.model, this.clonedModel);
};
return WindowChildModel;
})(BaseObject);
return WindowChildModel;
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapBasePolysParentModel', [
'$timeout', 'uiGmapLogger', 'uiGmapModelKey', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmap_async', 'uiGmapPromise', function($timeout, $log, ModelKey, ModelsWatcher, PropMap, _async, uiGmapPromise) {
return function(IPoly, PolyChildModel, gObjectName) {
var BasePolysParentModel;
return BasePolysParentModel = (function(superClass) {
extend(BasePolysParentModel, superClass);
BasePolysParentModel.include(ModelsWatcher);
function BasePolysParentModel(scope, element, attrs, gMap1, defaults) {
this.element = element;
this.attrs = attrs;
this.gMap = gMap1;
this.defaults = defaults;
this.createChild = bind(this.createChild, this);
this.pieceMeal = bind(this.pieceMeal, this);
this.createAllNew = bind(this.createAllNew, this);
this.watchIdKey = bind(this.watchIdKey, this);
this.createChildScopes = bind(this.createChildScopes, this);
this.watchDestroy = bind(this.watchDestroy, this);
this.onDestroy = bind(this.onDestroy, this);
this.rebuildAll = bind(this.rebuildAll, this);
this.doINeedToWipe = bind(this.doINeedToWipe, this);
this.watchModels = bind(this.watchModels, this);
BasePolysParentModel.__super__.constructor.call(this, scope);
this["interface"] = IPoly;
this.$log = $log;
this.plurals = new PropMap();
_.each(IPoly.scopeKeys, (function(_this) {
return function(name) {
return _this[name + 'Key'] = void 0;
};
})(this));
this.models = void 0;
this.firstTime = true;
this.$log.info(this);
this.createChildScopes();
}
BasePolysParentModel.prototype.watchModels = function(scope) {
return scope.$watchCollection('models', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
if (_this.doINeedToWipe(newValue) || scope.doRebuildAll) {
return _this.rebuildAll(scope, true, true);
} else {
return _this.createChildScopes(false);
}
}
};
})(this));
};
BasePolysParentModel.prototype.doINeedToWipe = function(newValue) {
var newValueIsEmpty;
newValueIsEmpty = newValue != null ? newValue.length === 0 : true;
return this.plurals.length > 0 && newValueIsEmpty;
};
BasePolysParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) {
return this.onDestroy(doDelete).then((function(_this) {
return function() {
if (doCreate) {
return _this.createChildScopes();
}
};
})(this));
};
BasePolysParentModel.prototype.onDestroy = function(scope) {
BasePolysParentModel.__super__.onDestroy.call(this, this.scope);
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.plurals.values(), function(child) {
return child.destroy(true);
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
var ref;
return (ref = _this.plurals) != null ? ref.removeAll() : void 0;
});
};
})(this));
};
BasePolysParentModel.prototype.watchDestroy = function(scope) {
return scope.$on('$destroy', (function(_this) {
return function() {
return _this.rebuildAll(scope, false, true);
};
})(this));
};
BasePolysParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
if (isCreatingFromScratch == null) {
isCreatingFromScratch = true;
}
if (angular.isUndefined(this.scope.models)) {
this.$log.error("No models to create " + gObjectName + "s from! I Need direct models!");
return;
}
if ((this.gMap == null) || (this.scope.models == null)) {
return;
}
this.watchIdKey(this.scope);
if (isCreatingFromScratch) {
return this.createAllNew(this.scope, false);
} else {
return this.pieceMeal(this.scope, false);
}
};
BasePolysParentModel.prototype.watchIdKey = function(scope) {
this.setIdKey(scope);
return scope.$watch('idKey', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue && (newValue == null)) {
_this.idKey = newValue;
return _this.rebuildAll(scope, true, true);
}
};
})(this));
};
BasePolysParentModel.prototype.createAllNew = function(scope, isArray) {
var maybeCanceled;
if (isArray == null) {
isArray = false;
}
this.models = scope.models;
if (this.firstTime) {
this.watchModels(scope);
this.watchDestroy(scope);
}
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
var child;
child = _this.createChild(model, _this.gMap);
if (maybeCanceled) {
$log.debug('createNew should fall through safely');
child.isEnabled = false;
}
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk)).then(function() {
return _this.firstTime = false;
});
};
})(this));
};
BasePolysParentModel.prototype.pieceMeal = function(scope, isArray) {
var maybeCanceled, payload;
if (isArray == null) {
isArray = true;
}
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
this.models = scope.models;
if ((scope != null) && this.modelsLength() && this.plurals.length) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise(function() {
return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison);
}).then(function(state) {
payload = state;
if (payload.updates.length) {
$log.info("polygons updates: " + payload.updates.length + " will be missed");
}
return _async.each(payload.removals, function(child) {
if (child != null) {
child.destroy();
_this.plurals.remove(child.model[_this.idKey]);
return maybeCanceled;
}
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
if (maybeCanceled) {
$log.debug('pieceMeal should fall through safely');
}
_this.createChild(modelToAdd, _this.gMap);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
});
};
})(this));
} else {
this.inProgress = false;
return this.rebuildAll(this.scope, true, true);
}
};
BasePolysParentModel.prototype.createChild = function(model, gMap) {
var child, childScope;
childScope = this.scope.$new(false);
this.setChildScope(IPoly.scopeKeys, childScope, model);
childScope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.setChildScope(childScope, newValue);
}
};
})(this), true);
childScope["static"] = this.scope["static"];
child = new PolyChildModel(childScope, this.attrs, gMap, this.defaults, model);
if (model[this.idKey] == null) {
this.$log.error(gObjectName + " model has no id to assign a child to.\nThis is required for performance. Please assign id,\nor redirect id to a different key.");
return;
}
this.plurals.put(model[this.idKey], child);
return child;
};
return BasePolysParentModel;
})(ModelKey);
};
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapCircleParentModel', [
'uiGmapLogger', '$timeout', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapCircleOptionsBuilder', function($log, $timeout, GmapUtil, EventsHelper, Builder) {
var CircleParentModel;
return CircleParentModel = (function(superClass) {
extend(CircleParentModel, superClass);
CircleParentModel.include(GmapUtil);
CircleParentModel.include(EventsHelper);
function CircleParentModel(scope, element, attrs, map, DEFAULTS) {
var clean, gObject, lastRadius;
this.attrs = attrs;
this.map = map;
this.DEFAULTS = DEFAULTS;
this.scope = scope;
lastRadius = null;
clean = (function(_this) {
return function() {
lastRadius = null;
if (_this.listeners != null) {
_this.removeEvents(_this.listeners);
return _this.listeners = void 0;
}
};
})(this);
gObject = new google.maps.Circle(this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius));
this.setMyOptions = (function(_this) {
return function(newVals, oldVals) {
if (!_.isEqual(newVals, oldVals)) {
return gObject.setOptions(_this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius));
}
};
})(this);
this.props = this.props.concat([
{
prop: 'center',
isColl: true
}, {
prop: 'fill',
isColl: true
}, 'radius', 'zIndex'
]);
this.watchProps();
if (this.scope.control != null) {
this.scope.control.getCircle = function() {
return gObject;
};
}
clean();
this.listeners = this.setEvents(gObject, scope, scope, ['radius_changed']);
if (this.listeners != null) {
this.listeners.push(google.maps.event.addListener(gObject, 'radius_changed', function() {
/*
possible google bug, and or because a circle has two radii
radius_changed appears to fire twice (original and new) which is not too helpful
therefore we will check for radius changes manually and bail out if nothing has changed
*/
var newRadius, work;
newRadius = gObject.getRadius();
if (newRadius === lastRadius) {
return;
}
lastRadius = newRadius;
work = function() {
var ref, ref1;
if (newRadius !== scope.radius) {
scope.radius = newRadius;
}
if (((ref = scope.events) != null ? ref.radius_changed : void 0) && _.isFunction((ref1 = scope.events) != null ? ref1.radius_changed : void 0)) {
return scope.events.radius_changed(gObject, 'radius_changed', scope, arguments);
}
};
if (!angular.mock) {
return scope.$evalAsync(function() {
return work();
});
} else {
return work();
}
}));
}
if (this.listeners != null) {
this.listeners.push(google.maps.event.addListener(gObject, 'center_changed', function() {
return scope.$evalAsync(function() {
if (angular.isDefined(scope.center.type)) {
scope.center.coordinates[1] = gObject.getCenter().lat();
return scope.center.coordinates[0] = gObject.getCenter().lng();
} else {
scope.center.latitude = gObject.getCenter().lat();
return scope.center.longitude = gObject.getCenter().lng();
}
});
}));
}
scope.$on('$destroy', (function(_this) {
return function() {
clean();
return gObject.setMap(null);
};
})(this));
$log.info(this);
}
return CircleParentModel;
})(Builder);
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapDrawingManagerParentModel', [
'uiGmapLogger', '$timeout', 'uiGmapBaseObject', 'uiGmapEventsHelper', function($log, $timeout, BaseObject, EventsHelper) {
var DrawingManagerParentModel;
return DrawingManagerParentModel = (function(superClass) {
extend(DrawingManagerParentModel, superClass);
DrawingManagerParentModel.include(EventsHelper);
function DrawingManagerParentModel(scope, element, attrs, map) {
var gObject, listeners;
this.scope = scope;
this.attrs = attrs;
this.map = map;
gObject = new google.maps.drawing.DrawingManager(this.scope.options);
gObject.setMap(this.map);
listeners = void 0;
if (this.scope.control != null) {
this.scope.control.getDrawingManager = function() {
return gObject;
};
}
if (!this.scope["static"] && this.scope.options) {
this.scope.$watch('options', function(newValue) {
return gObject != null ? gObject.setOptions(newValue) : void 0;
}, true);
}
if (this.scope.events != null) {
listeners = this.setEvents(gObject, this.scope, this.scope);
this.scope.$watch('events', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
if (listeners != null) {
_this.removeEvents(listeners);
}
return listeners = _this.setEvents(gObject, _this.scope, _this.scope);
}
};
})(this));
}
this.scope.$on('$destroy', (function(_this) {
return function() {
if (listeners != null) {
_this.removeEvents(listeners);
}
gObject.setMap(null);
return gObject = null;
};
})(this));
}
return DrawingManagerParentModel;
})(BaseObject);
}
]);
}).call(this);
;
/*
- interface for all markers to derrive from
- to enforce a minimum set of requirements
- attributes
- coords
- icon
- implementation needed on watches
*/
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIMarkerParentModel", [
"uiGmapModelKey", "uiGmapLogger", function(ModelKey, Logger) {
var IMarkerParentModel;
IMarkerParentModel = (function(superClass) {
extend(IMarkerParentModel, superClass);
IMarkerParentModel.prototype.DEFAULTS = {};
function IMarkerParentModel(scope1, element, attrs, map) {
this.scope = scope1;
this.element = element;
this.attrs = attrs;
this.map = map;
this.onWatch = bind(this.onWatch, this);
this.watch = bind(this.watch, this);
this.validateScope = bind(this.validateScope, this);
IMarkerParentModel.__super__.constructor.call(this, this.scope);
this.$log = Logger;
if (!this.validateScope(this.scope)) {
throw new String("Unable to construct IMarkerParentModel due to invalid scope");
}
this.doClick = angular.isDefined(this.attrs.click);
if (this.scope.options != null) {
this.DEFAULTS = this.scope.options;
}
this.watch('coords', this.scope);
this.watch('icon', this.scope);
this.watch('options', this.scope);
this.scope.$on("$destroy", (function(_this) {
return function() {
return _this.onDestroy(_this.scope);
};
})(this));
}
IMarkerParentModel.prototype.validateScope = function(scope) {
var ret;
if (scope == null) {
this.$log.error(this.constructor.name + ": invalid scope used");
return false;
}
ret = scope.coords != null;
if (!ret) {
this.$log.error(this.constructor.name + ": no valid coords attribute found");
return false;
}
return ret;
};
IMarkerParentModel.prototype.watch = function(propNameToWatch, scope, equalityCheck) {
if (equalityCheck == null) {
equalityCheck = true;
}
return scope.$watch(propNameToWatch, (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
return _this.onWatch(propNameToWatch, scope, newValue, oldValue);
}
};
})(this), equalityCheck);
};
IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {};
return IMarkerParentModel;
})(ModelKey);
return IMarkerParentModel;
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIWindowParentModel", [
"uiGmapModelKey", "uiGmapGmapUtil", "uiGmapLogger", function(ModelKey, GmapUtil, Logger) {
var IWindowParentModel;
return IWindowParentModel = (function(superClass) {
extend(IWindowParentModel, superClass);
IWindowParentModel.include(GmapUtil);
function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) {
IWindowParentModel.__super__.constructor.call(this, scope);
this.$log = Logger;
this.$timeout = $timeout;
this.$compile = $compile;
this.$http = $http;
this.$templateCache = $templateCache;
this.DEFAULTS = {};
if (scope.options != null) {
this.DEFAULTS = scope.options;
}
}
IWindowParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) {
if (modelsPropToIterate === 'models') {
return scope[modelsPropToIterate][index];
}
return scope[modelsPropToIterate].get(index);
};
return IWindowParentModel;
})(ModelKey);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapLayerParentModel', [
'uiGmapBaseObject', 'uiGmapLogger', '$timeout', function(BaseObject, Logger, $timeout) {
var LayerParentModel;
LayerParentModel = (function(superClass) {
extend(LayerParentModel, superClass);
function LayerParentModel(scope, element, attrs, gMap, onLayerCreated, $log) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0;
this.$log = $log != null ? $log : Logger;
this.createGoogleLayer = bind(this.createGoogleLayer, this);
if (this.attrs.type == null) {
this.$log.info('type attribute for the layer directive is mandatory. Layer creation aborted!!');
return;
}
this.createGoogleLayer();
this.doShow = true;
if (angular.isDefined(this.attrs.show)) {
this.doShow = this.scope.show;
}
if (this.doShow && (this.gMap != null)) {
this.gObject.setMap(this.gMap);
}
this.scope.$watch('show', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.doShow = newValue;
if (newValue) {
return _this.gObject.setMap(_this.gMap);
} else {
return _this.gObject.setMap(null);
}
}
};
})(this), true);
this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.gObject.setMap(null);
_this.gObject = null;
return _this.createGoogleLayer();
}
};
})(this), true);
this.scope.$on('$destroy', (function(_this) {
return function() {
return _this.gObject.setMap(null);
};
})(this));
}
LayerParentModel.prototype.createGoogleLayer = function() {
var base;
if (this.attrs.options == null) {
this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type]() : new google.maps[this.attrs.namespace][this.attrs.type]();
} else {
this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type](this.scope.options) : new google.maps[this.attrs.namespace][this.attrs.type](this.scope.options);
}
if ((this.gObject != null) && (this.onLayerCreated != null)) {
return typeof (base = this.onLayerCreated(this.scope, this.gObject)) === "function" ? base(this.gObject) : void 0;
}
};
return LayerParentModel;
})(BaseObject);
return LayerParentModel;
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapMapTypeParentModel', [
'uiGmapBaseObject', 'uiGmapLogger', function(BaseObject, Logger) {
var MapTypeParentModel;
MapTypeParentModel = (function(superClass) {
extend(MapTypeParentModel, superClass);
function MapTypeParentModel(scope, element, attrs, gMap, $log) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.$log = $log != null ? $log : Logger;
this.hideOverlay = bind(this.hideOverlay, this);
this.showOverlay = bind(this.showOverlay, this);
this.refreshMapType = bind(this.refreshMapType, this);
this.createMapType = bind(this.createMapType, this);
if (this.attrs.options == null) {
this.$log.info('options attribute for the map-type directive is mandatory. Map type creation aborted!!');
return;
}
this.id = this.gMap.overlayMapTypesCount = this.gMap.overlayMapTypesCount + 1 || 0;
this.doShow = true;
this.createMapType();
if (angular.isDefined(this.attrs.show)) {
this.doShow = this.scope.show;
}
if (this.doShow && (this.gMap != null)) {
this.showOverlay();
}
this.scope.$watch('show', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.doShow = newValue;
if (newValue) {
return _this.showOverlay();
} else {
return _this.hideOverlay();
}
}
};
})(this), true);
this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
return _this.refreshMapType();
}
};
})(this), true);
if (angular.isDefined(this.attrs.refresh)) {
this.scope.$watch('refresh', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
return _this.refreshMapType();
}
};
})(this), true);
}
this.scope.$on('$destroy', (function(_this) {
return function() {
_this.hideOverlay();
return _this.mapType = null;
};
})(this));
}
MapTypeParentModel.prototype.createMapType = function() {
if (this.scope.options.getTile != null) {
this.mapType = this.scope.options;
} else if (this.scope.options.getTileUrl != null) {
this.mapType = new google.maps.ImageMapType(this.scope.options);
} else {
this.$log.info('options should provide either getTile or getTileUrl methods. Map type creation aborted!!');
return;
}
if (this.attrs.id && this.scope.id) {
this.gMap.mapTypes.set(this.scope.id, this.mapType);
if (!angular.isDefined(this.attrs.show)) {
this.doShow = false;
}
}
return this.mapType.layerId = this.id;
};
MapTypeParentModel.prototype.refreshMapType = function() {
this.hideOverlay();
this.mapType = null;
this.createMapType();
if (this.doShow && (this.gMap != null)) {
return this.showOverlay();
}
};
MapTypeParentModel.prototype.showOverlay = function() {
return this.gMap.overlayMapTypes.push(this.mapType);
};
MapTypeParentModel.prototype.hideOverlay = function() {
var found;
found = false;
return this.gMap.overlayMapTypes.forEach((function(_this) {
return function(mapType, index) {
if (!found && mapType.layerId === _this.id) {
found = true;
_this.gMap.overlayMapTypes.removeAt(index);
}
};
})(this));
};
return MapTypeParentModel;
})(BaseObject);
return MapTypeParentModel;
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapMarkersParentModel", [
"uiGmapIMarkerParentModel", "uiGmapModelsWatcher", "uiGmapPropMap", "uiGmapMarkerChildModel", "uiGmap_async", "uiGmapClustererMarkerManager", "uiGmapMarkerManager", "$timeout", "uiGmapIMarker", "uiGmapPromise", "uiGmapGmapUtil", "uiGmapLogger", function(IMarkerParentModel, ModelsWatcher, PropMap, MarkerChildModel, _async, ClustererMarkerManager, MarkerManager, $timeout, IMarker, uiGmapPromise, GmapUtil, $log) {
var MarkersParentModel, _setPlurals;
_setPlurals = function(val, objToSet) {
objToSet.plurals = new PropMap();
objToSet.scope.plurals = objToSet.plurals;
return objToSet;
};
MarkersParentModel = (function(superClass) {
extend(MarkersParentModel, superClass);
MarkersParentModel.include(GmapUtil);
MarkersParentModel.include(ModelsWatcher);
function MarkersParentModel(scope, element, attrs, map) {
this.onDestroy = bind(this.onDestroy, this);
this.newChildMarker = bind(this.newChildMarker, this);
this.pieceMeal = bind(this.pieceMeal, this);
this.rebuildAll = bind(this.rebuildAll, this);
this.createAllNew = bind(this.createAllNew, this);
this.createChildScopes = bind(this.createChildScopes, this);
this.validateScope = bind(this.validateScope, this);
this.onWatch = bind(this.onWatch, this);
var self;
MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, map);
this["interface"] = IMarker;
self = this;
_setPlurals(new PropMap(), this);
this.scope.pluralsUpdate = {
updateCtr: 0
};
this.$log.info(this);
this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false;
this.setIdKey(this.scope);
this.scope.$watch('doRebuildAll', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.doRebuildAll = newValue;
}
};
})(this));
if (!this.modelsLength()) {
this.modelsRendered = false;
}
this.scope.$watch('models', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue) || !_this.modelsRendered) {
if (newValue.length === 0 && oldValue.length === 0) {
return;
}
_this.modelsRendered = true;
return _this.onWatch('models', _this.scope, newValue, oldValue);
}
};
})(this), !this.isTrue(attrs.modelsbyref));
this.watch('doCluster', this.scope);
this.watch('clusterOptions', this.scope);
this.watch('clusterEvents', this.scope);
this.watch('fit', this.scope);
this.watch('idKey', this.scope);
this.gManager = void 0;
this.createAllNew(this.scope);
}
MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {
if (propNameToWatch === "idKey" && newValue !== oldValue) {
this.idKey = newValue;
}
if (this.doRebuildAll || propNameToWatch === 'doCluster') {
return this.rebuildAll(scope);
} else {
return this.pieceMeal(scope);
}
};
MarkersParentModel.prototype.validateScope = function(scope) {
var modelsNotDefined;
modelsNotDefined = angular.isUndefined(scope.models) || scope.models === void 0;
if (modelsNotDefined) {
this.$log.error(this.constructor.name + ": no valid models attribute found");
}
return MarkersParentModel.__super__.validateScope.call(this, scope) || modelsNotDefined;
};
/*
Not used internally by this parent
created for consistency for external control in the API
*/
MarkersParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
if ((this.gMap == null) || (this.scope.models == null)) {
return;
}
if (isCreatingFromScratch) {
return this.createAllNew(this.scope, false);
} else {
return this.pieceMeal(this.scope, false);
}
};
MarkersParentModel.prototype.createAllNew = function(scope) {
var maybeCanceled, ref, ref1, ref2, self;
if (this.gManager != null) {
this.gManager.clear();
delete this.gManager;
}
if (scope.doCluster) {
if (scope.clusterEvents) {
self = this;
if (!this.origClusterEvents) {
this.origClusterEvents = {
click: (ref = scope.clusterEvents) != null ? ref.click : void 0,
mouseout: (ref1 = scope.clusterEvents) != null ? ref1.mouseout : void 0,
mouseover: (ref2 = scope.clusterEvents) != null ? ref2.mouseover : void 0
};
} else {
angular.extend(scope.clusterEvents, this.origClusterEvents);
}
angular.extend(scope.clusterEvents, {
click: function(cluster) {
return self.maybeExecMappedEvent(cluster, 'click');
},
mouseout: function(cluster) {
return self.maybeExecMappedEvent(cluster, 'mouseout');
},
mouseover: function(cluster) {
return self.maybeExecMappedEvent(cluster, 'mouseover');
}
});
}
this.gManager = new ClustererMarkerManager(this.map, void 0, scope.clusterOptions, scope.clusterEvents);
} else {
this.gManager = new MarkerManager(this.map);
}
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
_this.newChildMarker(model, scope);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk)).then(function() {
_this.modelsRendered = true;
if (scope.fit) {
_this.gManager.fit();
}
_this.gManager.draw();
return _this.scope.pluralsUpdate.updateCtr += 1;
}, _async.chunkSizeFrom(scope.chunk));
};
})(this));
};
MarkersParentModel.prototype.rebuildAll = function(scope) {
var ref;
if (!scope.doRebuild && scope.doRebuild !== void 0) {
return;
}
if ((ref = this.scope.plurals) != null ? ref.length : void 0) {
return this.onDestroy(scope).then((function(_this) {
return function() {
return _this.createAllNew(scope);
};
})(this));
} else {
return this.createAllNew(scope);
}
};
MarkersParentModel.prototype.pieceMeal = function(scope) {
var maybeCanceled, payload;
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
if (this.modelsLength() && this.scope.plurals.length) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise((function() {
return _this.figureOutState(_this.idKey, scope, _this.scope.plurals, _this.modelKeyComparison);
})).then(function(state) {
payload = state;
return _async.each(payload.removals, function(child) {
if (child != null) {
if (child.destroy != null) {
child.destroy();
}
_this.scope.plurals.remove(child.id);
return maybeCanceled;
}
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
_this.newChildMarker(modelToAdd, scope);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.updates, function(update) {
_this.updateChild(update.child, update.model);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
if (payload.adds.length > 0 || payload.removals.length > 0 || payload.updates.length > 0) {
scope.plurals = _this.scope.plurals;
if (scope.fit) {
_this.gManager.fit();
}
_this.gManager.draw();
}
return _this.scope.pluralsUpdate.updateCtr += 1;
});
};
})(this));
} else {
this.inProgress = false;
return this.rebuildAll(scope);
}
};
MarkersParentModel.prototype.newChildMarker = function(model, scope) {
var child, childScope, doDrawSelf, keys;
if (model[this.idKey] == null) {
this.$log.error("Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.");
return;
}
this.$log.info('child', child, 'markers', this.scope.markerModels);
childScope = scope.$new(false);
childScope.events = scope.events;
keys = {};
IMarker.scopeKeys.forEach(function(k) {
return keys[k] = scope[k];
});
child = new MarkerChildModel(childScope, model, keys, this.map, this.DEFAULTS, this.doClick, this.gManager, doDrawSelf = false);
this.scope.plurals.put(model[this.idKey], child);
return child;
};
MarkersParentModel.prototype.onDestroy = function(scope) {
MarkersParentModel.__super__.onDestroy.call(this, scope);
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.scope.plurals.values(), function(model) {
if (model != null) {
return model.destroy(false);
}
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
if (_this.gManager != null) {
_this.gManager.clear();
}
_this.plurals.removeAll();
if (_this.plurals !== _this.scope.plurals) {
console.error('plurals out of sync for MarkersParentModel');
}
return _this.scope.pluralsUpdate.updateCtr += 1;
});
};
})(this));
};
MarkersParentModel.prototype.maybeExecMappedEvent = function(cluster, fnName) {
var pair, ref;
if (_.isFunction((ref = this.scope.clusterEvents) != null ? ref[fnName] : void 0)) {
pair = this.mapClusterToPlurals(cluster);
if (this.origClusterEvents[fnName]) {
return this.origClusterEvents[fnName](pair.cluster, pair.mapped);
}
}
};
MarkersParentModel.prototype.mapClusterToPlurals = function(cluster) {
var mapped;
mapped = cluster.getMarkers().map((function(_this) {
return function(g) {
return _this.scope.plurals.get(g.key).model;
};
})(this));
return {
cluster: cluster,
mapped: mapped
};
};
MarkersParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) {
if (modelsPropToIterate === 'models') {
return scope[modelsPropToIterate][index];
}
return scope[modelsPropToIterate].get(index);
};
return MarkersParentModel;
})(IMarkerParentModel);
return MarkersParentModel;
}
]);
}).call(this);
;(function() {
['Polygon', 'Polyline'].forEach(function(name) {
return angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory("uiGmap" + name + "sParentModel", [
'uiGmapBasePolysParentModel', "uiGmap" + name + "ChildModel", "uiGmapI" + name, function(BasePolysParentModel, ChildModel, IPoly) {
return BasePolysParentModel(IPoly, ChildModel, name);
}
]);
});
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapRectangleParentModel', [
'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapRectangleOptionsBuilder', function($log, GmapUtil, EventsHelper, Builder) {
var RectangleParentModel;
return RectangleParentModel = (function(superClass) {
extend(RectangleParentModel, superClass);
RectangleParentModel.include(GmapUtil);
RectangleParentModel.include(EventsHelper);
function RectangleParentModel(scope, element, attrs, map, DEFAULTS) {
var bounds, clear, createBounds, dragging, fit, gObject, init, listeners, myListeners, settingBoundsFromScope, updateBounds;
this.scope = scope;
this.attrs = attrs;
this.map = map;
this.DEFAULTS = DEFAULTS;
bounds = void 0;
dragging = false;
myListeners = [];
listeners = void 0;
fit = (function(_this) {
return function() {
if (_this.isTrue(_this.attrs.fit)) {
return _this.fitMapBounds(_this.map, bounds);
}
};
})(this);
createBounds = (function(_this) {
return function() {
var ref, ref1, ref2;
if ((_this.scope.bounds != null) && (((ref = _this.scope.bounds) != null ? ref.sw : void 0) != null) && (((ref1 = _this.scope.bounds) != null ? ref1.ne : void 0) != null) && _this.validateBoundPoints(_this.scope.bounds)) {
bounds = _this.convertBoundPoints(_this.scope.bounds);
return $log.info("new new bounds created: " + (JSON.stringify(bounds)));
} else if ((_this.scope.bounds.getNorthEast != null) && (_this.scope.bounds.getSouthWest != null)) {
return bounds = _this.scope.bounds;
} else {
if (_this.scope.bounds != null) {
return $log.error("Invalid bounds for newValue: " + (JSON.stringify((ref2 = _this.scope) != null ? ref2.bounds : void 0)));
}
}
};
})(this);
createBounds();
gObject = new google.maps.Rectangle(this.buildOpts(bounds));
$log.info("gObject (rectangle) created: " + gObject);
settingBoundsFromScope = false;
updateBounds = (function(_this) {
return function() {
var b, ne, sw;
b = gObject.getBounds();
ne = b.getNorthEast();
sw = b.getSouthWest();
if (settingBoundsFromScope) {
return;
}
return _this.scope.$evalAsync(function(s) {
if ((s.bounds != null) && (s.bounds.sw != null) && (s.bounds.ne != null)) {
s.bounds.ne = {
latitude: ne.lat(),
longitude: ne.lng()
};
s.bounds.sw = {
latitude: sw.lat(),
longitude: sw.lng()
};
}
if ((s.bounds.getNorthEast != null) && (s.bounds.getSouthWest != null)) {
return s.bounds = b;
}
});
};
})(this);
init = (function(_this) {
return function() {
fit();
_this.removeEvents(myListeners);
myListeners.push(google.maps.event.addListener(gObject, 'dragstart', function() {
return dragging = true;
}));
myListeners.push(google.maps.event.addListener(gObject, 'dragend', function() {
dragging = false;
return updateBounds();
}));
return myListeners.push(google.maps.event.addListener(gObject, 'bounds_changed', function() {
if (dragging) {
return;
}
return updateBounds();
}));
};
})(this);
clear = (function(_this) {
return function() {
_this.removeEvents(myListeners);
if (listeners != null) {
_this.removeEvents(listeners);
}
return gObject.setMap(null);
};
})(this);
if (bounds != null) {
init();
}
this.scope.$watch('bounds', (function(newValue, oldValue) {
var isNew;
if (_.isEqual(newValue, oldValue) && (bounds != null) || dragging) {
return;
}
settingBoundsFromScope = true;
if (newValue == null) {
clear();
return;
}
if (bounds == null) {
isNew = true;
} else {
fit();
}
createBounds();
gObject.setBounds(bounds);
settingBoundsFromScope = false;
if (isNew && (bounds != null)) {
return init();
}
}), true);
this.setMyOptions = (function(_this) {
return function(newVals, oldVals) {
if (!_.isEqual(newVals, oldVals)) {
if ((bounds != null) && (newVals != null)) {
return gObject.setOptions(_this.buildOpts(bounds));
}
}
};
})(this);
this.props.push('bounds');
this.watchProps(this.props);
if (this.attrs.events != null) {
listeners = this.setEvents(gObject, this.scope, this.scope);
this.scope.$watch('events', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
if (listeners != null) {
_this.removeEvents(listeners);
}
return listeners = _this.setEvents(gObject, _this.scope, _this.scope);
}
};
})(this));
}
this.scope.$on('$destroy', (function(_this) {
return function() {
return clear();
};
})(this));
$log.info(this);
}
return RectangleParentModel;
})(Builder);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapSearchBoxParentModel', [
'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapEventsHelper', '$timeout', '$http', '$templateCache', function(BaseObject, Logger, EventsHelper, $timeout, $http, $templateCache) {
var SearchBoxParentModel;
SearchBoxParentModel = (function(superClass) {
extend(SearchBoxParentModel, superClass);
SearchBoxParentModel.include(EventsHelper);
function SearchBoxParentModel(scope, element, attrs, gMap, ctrlPosition, template, $log) {
var controlDiv;
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.ctrlPosition = ctrlPosition;
this.template = template;
this.$log = $log != null ? $log : Logger;
this.setVisibility = bind(this.setVisibility, this);
this.getBounds = bind(this.getBounds, this);
this.setBounds = bind(this.setBounds, this);
this.createSearchBox = bind(this.createSearchBox, this);
this.addToParentDiv = bind(this.addToParentDiv, this);
this.addAsMapControl = bind(this.addAsMapControl, this);
this.init = bind(this.init, this);
if (this.attrs.template == null) {
this.$log.error('template attribute for the search-box directive is mandatory. Places Search Box creation aborted!!');
return;
}
if (angular.isUndefined(this.scope.options)) {
this.scope.options = {};
this.scope.options.visible = true;
}
if (angular.isUndefined(this.scope.options.visible)) {
this.scope.options.visible = true;
}
if (angular.isUndefined(this.scope.options.autocomplete)) {
this.scope.options.autocomplete = false;
}
this.visible = this.scope.options.visible;
this.autocomplete = this.scope.options.autocomplete;
controlDiv = angular.element('<div></div>');
controlDiv.append(this.template);
this.input = controlDiv.find('input')[0];
this.init();
}
SearchBoxParentModel.prototype.init = function() {
this.createSearchBox();
this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (angular.isObject(newValue)) {
if (newValue.bounds != null) {
_this.setBounds(newValue.bounds);
}
if (newValue.visible != null) {
if (_this.visible !== newValue.visible) {
return _this.setVisibility(newValue.visible);
}
}
}
};
})(this), true);
if (this.attrs.parentdiv != null) {
this.addToParentDiv();
} else {
this.addAsMapControl();
}
if (this.autocomplete) {
this.listener = google.maps.event.addListener(this.gObject, 'place_changed', (function(_this) {
return function() {
return _this.places = _this.gObject.getPlace();
};
})(this));
} else {
this.listener = google.maps.event.addListener(this.gObject, 'places_changed', (function(_this) {
return function() {
return _this.places = _this.gObject.getPlaces();
};
})(this));
}
this.listeners = this.setEvents(this.gObject, this.scope, this.scope);
this.$log.info(this);
return this.scope.$on('$destroy', (function(_this) {
return function() {
return _this.gObject = null;
};
})(this));
};
SearchBoxParentModel.prototype.addAsMapControl = function() {
return this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input);
};
SearchBoxParentModel.prototype.addToParentDiv = function() {
this.parentDiv = angular.element(document.getElementById(this.scope.parentdiv));
return this.parentDiv.append(this.input);
};
SearchBoxParentModel.prototype.createSearchBox = function() {
if (this.autocomplete) {
return this.gObject = new google.maps.places.Autocomplete(this.input, this.scope.options);
} else {
return this.gObject = new google.maps.places.SearchBox(this.input, this.scope.options);
}
};
SearchBoxParentModel.prototype.setBounds = function(bounds) {
if (angular.isUndefined(bounds.isEmpty)) {
this.$log.error('Error: SearchBoxParentModel setBounds. Bounds not an instance of LatLngBounds.');
} else {
if (bounds.isEmpty() === false) {
if (this.gObject != null) {
return this.gObject.setBounds(bounds);
}
}
}
};
SearchBoxParentModel.prototype.getBounds = function() {
return this.gObject.getBounds();
};
SearchBoxParentModel.prototype.setVisibility = function(val) {
if (this.attrs.parentdiv != null) {
if (val === false) {
this.parentDiv.addClass("ng-hide");
} else {
this.parentDiv.removeClass("ng-hide");
}
} else {
if (val === false) {
this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].clear();
} else {
this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input);
}
}
return this.visible = val;
};
return SearchBoxParentModel;
})(BaseObject);
return SearchBoxParentModel;
}
]);
}).call(this);
;
/*
WindowsChildModel generator where there are many ChildModels to a parent.
*/
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapWindowsParentModel', [
'uiGmapIWindowParentModel', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapWindowChildModel', 'uiGmapLinked', 'uiGmap_async', 'uiGmapLogger', '$timeout', '$compile', '$http', '$templateCache', '$interpolate', 'uiGmapPromise', 'uiGmapIWindow', 'uiGmapGmapUtil', function(IWindowParentModel, ModelsWatcher, PropMap, WindowChildModel, Linked, _async, $log, $timeout, $compile, $http, $templateCache, $interpolate, uiGmapPromise, IWindow, GmapUtil) {
var WindowsParentModel;
WindowsParentModel = (function(superClass) {
extend(WindowsParentModel, superClass);
WindowsParentModel.include(ModelsWatcher);
function WindowsParentModel(scope, element, attrs, ctrls, gMap1, markersScope) {
this.gMap = gMap1;
this.markersScope = markersScope;
this.modelKeyComparison = bind(this.modelKeyComparison, this);
this.interpolateContent = bind(this.interpolateContent, this);
this.setChildScope = bind(this.setChildScope, this);
this.createWindow = bind(this.createWindow, this);
this.setContentKeys = bind(this.setContentKeys, this);
this.pieceMeal = bind(this.pieceMeal, this);
this.createAllNew = bind(this.createAllNew, this);
this.watchIdKey = bind(this.watchIdKey, this);
this.createChildScopes = bind(this.createChildScopes, this);
this.watchOurScope = bind(this.watchOurScope, this);
this.watchDestroy = bind(this.watchDestroy, this);
this.onDestroy = bind(this.onDestroy, this);
this.rebuildAll = bind(this.rebuildAll, this);
this.doINeedToWipe = bind(this.doINeedToWipe, this);
this.watchModels = bind(this.watchModels, this);
this.go = bind(this.go, this);
WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache);
this["interface"] = IWindow;
this.plurals = new PropMap();
_.each(IWindow.scopeKeys, (function(_this) {
return function(name) {
return _this[name + 'Key'] = void 0;
};
})(this));
this.linked = new Linked(scope, element, attrs, ctrls);
this.contentKeys = void 0;
this.isIconVisibleOnClick = void 0;
this.firstTime = true;
this.firstWatchModels = true;
this.$log.info(self);
this.parentScope = void 0;
this.go(scope);
}
WindowsParentModel.prototype.go = function(scope) {
this.watchOurScope(scope);
this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false;
scope.$watch('doRebuildAll', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.doRebuildAll = newValue;
}
};
})(this));
return this.createChildScopes();
};
WindowsParentModel.prototype.watchModels = function(scope) {
var itemToWatch;
itemToWatch = this.markersScope != null ? 'pluralsUpdate' : 'models';
return scope.$watch(itemToWatch, (function(_this) {
return function(newValue, oldValue) {
var doScratch;
if (!_.isEqual(newValue, oldValue) || _this.firstWatchModels) {
_this.firstWatchModels = false;
if (_this.doRebuildAll || _this.doINeedToWipe(scope.models)) {
return _this.rebuildAll(scope, true, true);
} else {
doScratch = _this.plurals.length === 0;
if (_this.existingPieces != null) {
return _.last(_this.existingPieces._content).then(function() {
return _this.createChildScopes(doScratch);
});
} else {
return _this.createChildScopes(doScratch);
}
}
}
};
})(this), true);
};
WindowsParentModel.prototype.doINeedToWipe = function(newValue) {
var newValueIsEmpty;
newValueIsEmpty = newValue != null ? newValue.length === 0 : true;
return this.plurals.length > 0 && newValueIsEmpty;
};
WindowsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) {
return this.onDestroy(doDelete).then((function(_this) {
return function() {
if (doCreate) {
return _this.createChildScopes();
}
};
})(this));
};
WindowsParentModel.prototype.onDestroy = function(scope) {
WindowsParentModel.__super__.onDestroy.call(this, this.scope);
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.plurals.values(), function(child) {
return child.destroy();
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
var ref;
return (ref = _this.plurals) != null ? ref.removeAll() : void 0;
});
};
})(this));
};
WindowsParentModel.prototype.watchDestroy = function(scope) {
return scope.$on('$destroy', (function(_this) {
return function() {
_this.firstWatchModels = true;
_this.firstTime = true;
return _this.rebuildAll(scope, false, true);
};
})(this));
};
WindowsParentModel.prototype.watchOurScope = function(scope) {
return _.each(IWindow.scopeKeys, (function(_this) {
return function(name) {
var nameKey;
nameKey = name + 'Key';
return _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name];
};
})(this));
};
WindowsParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
var modelsNotDefined, ref, ref1;
if (isCreatingFromScratch == null) {
isCreatingFromScratch = true;
}
/*
being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl)
we will assume that all scope values are string expressions either pointing to a key (propName) or using
'self' to point the model as container/object of interest.
This may force redundant information into the model, but this appears to be the most flexible approach.
*/
this.isIconVisibleOnClick = true;
if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) {
this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick;
}
modelsNotDefined = angular.isUndefined(this.linked.scope.models);
if (modelsNotDefined && (this.markersScope === void 0 || (((ref = this.markersScope) != null ? ref.plurals : void 0) === void 0 || ((ref1 = this.markersScope) != null ? ref1.models : void 0) === void 0))) {
this.$log.error('No models to create windows from! Need direct models or models derived from markers!');
return;
}
if (this.gMap != null) {
if (this.linked.scope.models != null) {
this.watchIdKey(this.linked.scope);
if (isCreatingFromScratch) {
return this.createAllNew(this.linked.scope, false);
} else {
return this.pieceMeal(this.linked.scope, false);
}
} else {
this.parentScope = this.markersScope;
this.watchIdKey(this.parentScope);
if (isCreatingFromScratch) {
return this.createAllNew(this.markersScope, true, 'plurals', false);
} else {
return this.pieceMeal(this.markersScope, true, 'plurals', false);
}
}
}
};
WindowsParentModel.prototype.watchIdKey = function(scope) {
this.setIdKey(scope);
return scope.$watch('idKey', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue && (newValue == null)) {
_this.idKey = newValue;
return _this.rebuildAll(scope, true, true);
}
};
})(this));
};
WindowsParentModel.prototype.createAllNew = function(scope, hasGMarker, modelsPropToIterate, isArray) {
var maybeCanceled;
if (modelsPropToIterate == null) {
modelsPropToIterate = 'models';
}
if (isArray == null) {
isArray = false;
}
if (this.firstTime) {
this.watchModels(scope);
this.watchDestroy(scope);
}
this.setContentKeys(scope.models);
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
var gMarker, ref;
gMarker = hasGMarker ? (ref = _this.getItem(scope, modelsPropToIterate, model[_this.idKey])) != null ? ref.gObject : void 0 : void 0;
if (!maybeCanceled) {
if (!gMarker && _this.markersScope) {
$log.error('Unable to get gMarker from markersScope!');
}
_this.createWindow(model, gMarker, _this.gMap);
}
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk)).then(function() {
return _this.firstTime = false;
});
};
})(this));
};
WindowsParentModel.prototype.pieceMeal = function(scope, hasGMarker, modelsPropToIterate, isArray) {
var maybeCanceled, payload;
if (modelsPropToIterate == null) {
modelsPropToIterate = 'models';
}
if (isArray == null) {
isArray = true;
}
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
if ((scope != null) && this.modelsLength() && this.plurals.length) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise((function() {
return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison);
})).then(function(state) {
payload = state;
return _async.each(payload.removals, function(child) {
if (child != null) {
_this.plurals.remove(child.id);
if (child.destroy != null) {
child.destroy(true);
}
return maybeCanceled;
}
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
var gMarker, ref;
gMarker = (ref = _this.getItem(scope, modelsPropToIterate, modelToAdd[_this.idKey])) != null ? ref.gObject : void 0;
if (!gMarker) {
throw 'Gmarker undefined';
}
_this.createWindow(modelToAdd, gMarker, _this.gMap);
return maybeCanceled;
});
}).then(function() {
return _async.each(payload.updates, function(update) {
_this.updateChild(update.child, update.model);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
});
};
})(this));
} else {
$log.debug('pieceMeal: rebuildAll');
return this.rebuildAll(this.scope, true, true);
}
};
WindowsParentModel.prototype.setContentKeys = function(models) {
if (this.modelsLength(models)) {
return this.contentKeys = Object.keys(models[0]);
}
};
WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) {
var child, childScope, fakeElement, opts, ref, ref1;
childScope = this.linked.scope.$new(false);
this.setChildScope(childScope, model);
childScope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.setChildScope(childScope, newValue);
}
};
})(this), true);
fakeElement = {
html: (function(_this) {
return function() {
return _this.interpolateContent(_this.linked.element.html(), model);
};
})(this)
};
this.DEFAULTS = this.scopeOrModelVal(this.optionsKey, this.scope, model) || {};
opts = this.createWindowOptions(gMarker, childScope, fakeElement.html(), this.DEFAULTS);
child = new WindowChildModel(model, childScope, opts, this.isIconVisibleOnClick, gMap, (ref = this.markersScope) != null ? (ref1 = ref.plurals.get(model[this.idKey])) != null ? ref1.scope : void 0 : void 0, fakeElement, false, true);
if (model[this.idKey] == null) {
this.$log.error('Window model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.');
return;
}
this.plurals.put(model[this.idKey], child);
return child;
};
WindowsParentModel.prototype.setChildScope = function(childScope, model) {
_.each(IWindow.scopeKeys, (function(_this) {
return function(name) {
var nameKey, newValue;
nameKey = name + 'Key';
newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]];
if (newValue !== childScope[name]) {
return childScope[name] = newValue;
}
};
})(this));
return childScope.model = model;
};
WindowsParentModel.prototype.interpolateContent = function(content, model) {
var exp, i, interpModel, key, len, ref;
if (this.contentKeys === void 0 || this.contentKeys.length === 0) {
return;
}
exp = $interpolate(content);
interpModel = {};
ref = this.contentKeys;
for (i = 0, len = ref.length; i < len; i++) {
key = ref[i];
interpModel[key] = model[key];
}
return exp(interpModel);
};
WindowsParentModel.prototype.modelKeyComparison = function(model1, model2) {
var isEqual, scope;
scope = this.scope.coords != null ? this.scope : this.parentScope;
if (scope == null) {
throw 'No scope or parentScope set!';
}
isEqual = GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords));
if (!isEqual) {
return isEqual;
}
isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) {
return function(k) {
return _this.evalModelHandle(model1, scope[k]) === _this.evalModelHandle(model2, scope[k]);
};
})(this));
return isEqual;
};
return WindowsParentModel;
})(IWindowParentModel);
return WindowsParentModel;
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapCircle", [
"uiGmapICircle", "uiGmapCircleParentModel", function(ICircle, CircleParentModel) {
return _.extend(ICircle, {
link: function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
return new CircleParentModel(scope, element, attrs, map);
};
})(this));
}
});
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapControl", [
"uiGmapIControl", "$http", "$templateCache", "$compile", "$controller", 'uiGmapGoogleMapApi', function(IControl, $http, $templateCache, $compile, $controller, GoogleMapApi) {
var Control;
return Control = (function(superClass) {
extend(Control, superClass);
function Control() {
this.link = bind(this.link, this);
Control.__super__.constructor.call(this);
}
Control.prototype.link = function(scope, element, attrs, ctrl) {
return GoogleMapApi.then((function(_this) {
return function(maps) {
var index, position;
if (angular.isUndefined(scope.template)) {
_this.$log.error('mapControl: could not find a valid template property');
return;
}
index = angular.isDefined(scope.index && !isNaN(parseInt(scope.index))) ? parseInt(scope.index) : void 0;
position = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_CENTER';
if (!maps.ControlPosition[position]) {
_this.$log.error('mapControl: invalid position property');
return;
}
return IControl.mapPromise(scope, ctrl).then(function(map) {
var control, controlDiv;
control = void 0;
controlDiv = angular.element('<div></div>');
return $http.get(scope.template, {
cache: $templateCache
}).success(function(template) {
var templateCtrl, templateScope;
templateScope = scope.$new();
controlDiv.append(template);
if (angular.isDefined(scope.controller)) {
templateCtrl = $controller(scope.controller, {
$scope: templateScope
});
controlDiv.children().data('$ngControllerController', templateCtrl);
}
control = $compile(controlDiv.children())(templateScope);
if (index) {
return control[0].index = index;
}
}).error(function(error) {
return _this.$log.error('mapControl: template could not be found');
}).then(function() {
return map.controls[google.maps.ControlPosition[position]].push(control[0]);
});
});
};
})(this));
};
return Control;
})(IControl);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapDragZoom', [
'uiGmapCtrlHandle', 'uiGmapPropertyAction', function(CtrlHandle, PropertyAction) {
return {
restrict: 'EMA',
transclude: true,
template: '<div class="angular-google-map-dragzoom" ng-transclude style="display: none"></div>',
require: '^' + 'uiGmapGoogleMap',
scope: {
keyboardkey: '=',
options: '=',
spec: '='
},
controller: [
'$scope', '$element', function($scope, $element) {
$scope.ctrlType = 'uiGmapDragZoom';
return _.extend(this, CtrlHandle.handle($scope, $element));
}
],
link: function(scope, element, attrs, ctrl) {
return CtrlHandle.mapPromise(scope, ctrl).then(function(map) {
var enableKeyDragZoom, setKeyAction, setOptionsAction;
enableKeyDragZoom = function(opts) {
map.enableKeyDragZoom(opts);
if (scope.spec) {
return scope.spec.enableKeyDragZoom(opts);
}
};
setKeyAction = new PropertyAction(function(key, newVal) {
if (newVal) {
return enableKeyDragZoom({
key: newVal
});
} else {
return enableKeyDragZoom();
}
});
setOptionsAction = new PropertyAction(function(key, newVal) {
if (newVal) {
return enableKeyDragZoom(newVal);
}
});
scope.$watch('keyboardkey', setKeyAction.sic);
setKeyAction.sic(scope.keyboardkey);
scope.$watch('options', setOptionsAction.sic);
return setOptionsAction.sic(scope.options);
});
}
};
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapDrawingManager", [
"uiGmapIDrawingManager", "uiGmapDrawingManagerParentModel", function(IDrawingManager, DrawingManagerParentModel) {
return _.extend(IDrawingManager, {
link: function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then(function(map) {
return new DrawingManagerParentModel(scope, element, attrs, map);
});
}
});
}
]);
}).call(this);
;
/*
- Link up Polygons to be sent back to a controller
- inject the draw function into a controllers scope so that controller can call the directive to draw on demand
- draw function creates the DrawFreeHandChildModel which manages itself
*/
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapApiFreeDrawPolygons', [
'uiGmapLogger', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapDrawFreeHandChildModel', 'uiGmapLodash', function($log, BaseObject, CtrlHandle, DrawFreeHandChildModel, uiGmapLodash) {
var FreeDrawPolygons;
return FreeDrawPolygons = (function(superClass) {
extend(FreeDrawPolygons, superClass);
function FreeDrawPolygons() {
this.link = bind(this.link, this);
return FreeDrawPolygons.__super__.constructor.apply(this, arguments);
}
FreeDrawPolygons.include(CtrlHandle);
FreeDrawPolygons.prototype.restrict = 'EMA';
FreeDrawPolygons.prototype.replace = true;
FreeDrawPolygons.prototype.require = '^' + 'uiGmapGoogleMap';
FreeDrawPolygons.prototype.scope = {
polygons: '=',
draw: '='
};
FreeDrawPolygons.prototype.link = function(scope, element, attrs, ctrl) {
return this.mapPromise(scope, ctrl).then((function(_this) {
return function(map) {
var freeHand, listener;
if (!scope.polygons) {
return $log.error('No polygons to bind to!');
}
if (!_.isArray(scope.polygons)) {
return $log.error('Free Draw Polygons must be of type Array!');
}
freeHand = new DrawFreeHandChildModel(map, ctrl.getScope());
listener = void 0;
return scope.draw = function() {
if (typeof listener === "function") {
listener();
}
return freeHand.engage(scope.polygons).then(function() {
var firstTime;
firstTime = true;
return listener = scope.$watchCollection('polygons', function(newValue, oldValue) {
var removals;
if (firstTime || newValue === oldValue) {
firstTime = false;
return;
}
removals = uiGmapLodash.differenceObjects(oldValue, newValue);
return removals.forEach(function(p) {
return p.setMap(null);
});
});
});
};
};
})(this));
};
return FreeDrawPolygons;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api").service("uiGmapICircle", [
function() {
var DEFAULTS;
DEFAULTS = {};
return {
restrict: "EA",
replace: true,
require: '^' + 'uiGmapGoogleMap',
scope: {
center: "=center",
radius: "=radius",
stroke: "=stroke",
fill: "=fill",
clickable: "=",
draggable: "=",
editable: "=",
geodesic: "=",
icons: "=icons",
visible: "=",
events: "=",
control: "=",
zIndex: "=zindex"
}
};
}
]);
}).call(this);
;
/*
- interface for all controls to derive from
- to enforce a minimum set of requirements
- attributes
- template
- position
- controller
- index
*/
(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapIControl", [
"uiGmapBaseObject", "uiGmapLogger", "uiGmapCtrlHandle", function(BaseObject, Logger, CtrlHandle) {
var IControl;
return IControl = (function(superClass) {
extend(IControl, superClass);
IControl.extend(CtrlHandle);
function IControl() {
this.restrict = 'EA';
this.replace = true;
this.require = '^' + 'uiGmapGoogleMap';
this.scope = {
template: '@template',
position: '@position',
controller: '@controller',
index: '@index'
};
this.$log = Logger;
}
IControl.prototype.link = function(scope, element, attrs, ctrl) {
throw new Exception("Not implemented!!");
};
return IControl;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIDrawingManager', [
function() {
return {
restrict: 'EA',
replace: true,
require: '^' + 'uiGmapGoogleMap',
scope: {
"static": '@',
control: '=',
options: '=',
events: '='
}
};
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIMarker', [
'uiGmapBaseObject', 'uiGmapCtrlHandle', function(BaseObject, CtrlHandle) {
var IMarker;
return IMarker = (function(superClass) {
extend(IMarker, superClass);
IMarker.scope = {
coords: '=coords',
icon: '=icon',
click: '&click',
options: '=options',
events: '=events',
fit: '=fit',
idKey: '=idkey',
control: '=control'
};
IMarker.scopeKeys = _.keys(IMarker.scope);
IMarker.keys = IMarker.scopeKeys;
IMarker.extend(CtrlHandle);
function IMarker() {
this.restrict = 'EMA';
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.replace = true;
this.scope = _.extend(this.scope || {}, IMarker.scope);
}
return IMarker;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolygon', [
'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) {
var IPolygon;
return IPolygon = (function(superClass) {
extend(IPolygon, superClass);
IPolygon.scope = {
path: '=path',
stroke: '=stroke',
clickable: '=',
draggable: '=',
editable: '=',
geodesic: '=',
fill: '=',
icons: '=icons',
visible: '=',
"static": '=',
events: '=',
zIndex: '=zindex',
fit: '=',
control: '=control'
};
IPolygon.scopeKeys = _.keys(IPolygon.scope);
IPolygon.include(GmapUtil);
IPolygon.extend(CtrlHandle);
function IPolygon() {}
IPolygon.prototype.restrict = 'EMA';
IPolygon.prototype.replace = true;
IPolygon.prototype.require = '^' + 'uiGmapGoogleMap';
IPolygon.prototype.scope = IPolygon.scope;
IPolygon.prototype.DEFAULTS = {};
IPolygon.prototype.$log = Logger;
return IPolygon;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolyline', [
'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) {
var IPolyline;
return IPolyline = (function(superClass) {
extend(IPolyline, superClass);
IPolyline.scope = {
path: '=',
stroke: '=',
clickable: '=',
draggable: '=',
editable: '=',
geodesic: '=',
icons: '=',
visible: '=',
"static": '=',
fit: '=',
events: '=',
zIndex: '=zindex'
};
IPolyline.scopeKeys = _.keys(IPolyline.scope);
IPolyline.include(GmapUtil);
IPolyline.extend(CtrlHandle);
function IPolyline() {}
IPolyline.prototype.restrict = 'EMA';
IPolyline.prototype.replace = true;
IPolyline.prototype.require = '^' + 'uiGmapGoogleMap';
IPolyline.prototype.scope = IPolyline.scope;
IPolyline.prototype.DEFAULTS = {};
IPolyline.prototype.$log = Logger;
return IPolyline;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIRectangle', [
function() {
'use strict';
var DEFAULTS;
DEFAULTS = {};
return {
restrict: 'EMA',
require: '^' + 'uiGmapGoogleMap',
replace: true,
scope: {
bounds: '=',
stroke: '=',
clickable: '=',
draggable: '=',
editable: '=',
fill: '=',
visible: '=',
events: '='
}
};
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIWindow', [
'uiGmapBaseObject', 'uiGmapChildEvents', 'uiGmapCtrlHandle', function(BaseObject, ChildEvents, CtrlHandle) {
var IWindow;
return IWindow = (function(superClass) {
extend(IWindow, superClass);
IWindow.scope = {
coords: '=coords',
template: '=template',
templateUrl: '=templateurl',
templateParameter: '=templateparameter',
isIconVisibleOnClick: '=isiconvisibleonclick',
closeClick: '&closeclick',
options: '=options',
control: '=control',
show: '=show'
};
IWindow.scopeKeys = _.keys(IWindow.scope);
IWindow.include(ChildEvents);
IWindow.extend(CtrlHandle);
function IWindow() {
this.restrict = 'EMA';
this.template = void 0;
this.transclude = true;
this.priority = -100;
this.require = '^' + 'uiGmapGoogleMap';
this.replace = true;
this.scope = _.extend(this.scope || {}, IWindow.scope);
}
return IWindow;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapMap', [
'$timeout', '$q', 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapIsReady', 'uiGmapuuid', 'uiGmapExtendGWin', 'uiGmapExtendMarkerClusterer', 'uiGmapGoogleMapsUtilV3', 'uiGmapGoogleMapApi', 'uiGmapEventsHelper', function($timeout, $q, $log, GmapUtil, BaseObject, CtrlHandle, IsReady, uuid, ExtendGWin, ExtendMarkerClusterer, GoogleMapsUtilV3, GoogleMapApi, EventsHelper) {
'use strict';
var DEFAULTS, Map, initializeItems;
DEFAULTS = void 0;
initializeItems = [GoogleMapsUtilV3, ExtendGWin, ExtendMarkerClusterer];
return Map = (function(superClass) {
extend(Map, superClass);
Map.include(GmapUtil);
function Map() {
this.link = bind(this.link, this);
var ctrlFn, self;
ctrlFn = function($scope) {
var ctrlObj, retCtrl;
retCtrl = void 0;
$scope.$on('$destroy', function() {
return IsReady.decrement();
});
ctrlObj = CtrlHandle.handle($scope);
$scope.ctrlType = 'Map';
$scope.deferred.promise.then(function() {
return initializeItems.forEach(function(i) {
return i.init();
});
});
ctrlObj.getMap = function() {
return $scope.map;
};
retCtrl = _.extend(this, ctrlObj);
return retCtrl;
};
this.controller = ['$scope', ctrlFn];
self = this;
}
Map.prototype.restrict = 'EMA';
Map.prototype.transclude = true;
Map.prototype.replace = false;
Map.prototype.template = '<div class="angular-google-map"><div class="angular-google-map-container"></div><div ng-transclude style="display: none"></div></div>';
Map.prototype.scope = {
center: '=',
zoom: '=',
dragging: '=',
control: '=',
options: '=',
events: '=',
eventOpts: '=',
styles: '=',
bounds: '=',
update: '='
};
Map.prototype.link = function(scope, element, attrs) {
var listeners, unbindCenterWatch;
listeners = [];
scope.$on('$destroy', function() {
return EventsHelper.removeEvents(listeners);
});
scope.idleAndZoomChanged = false;
if (scope.center == null) {
unbindCenterWatch = scope.$watch('center', (function(_this) {
return function() {
if (!scope.center) {
return;
}
unbindCenterWatch();
return _this.link(scope, element, attrs);
};
})(this));
return;
}
return GoogleMapApi.then((function(_this) {
return function(maps) {
var _gMap, customListeners, disabledEvents, dragging, el, eventName, getEventHandler, mapOptions, maybeHookToEvent, opts, ref, resolveSpawned, settingFromDirective, spawned, type, updateCenter, zoomPromise;
DEFAULTS = {
mapTypeId: maps.MapTypeId.ROADMAP
};
spawned = IsReady.spawn();
resolveSpawned = function() {
return spawned.deferred.resolve({
instance: spawned.instance,
map: _gMap
});
};
if (!_this.validateCoords(scope.center)) {
$log.error('angular-google-maps: could not find a valid center property');
return;
}
if (!angular.isDefined(scope.zoom)) {
$log.error('angular-google-maps: map zoom property not set');
return;
}
el = angular.element(element);
el.addClass('angular-google-map');
opts = {
options: {}
};
if (attrs.options) {
opts.options = scope.options;
}
if (attrs.styles) {
opts.styles = scope.styles;
}
if (attrs.type) {
type = attrs.type.toUpperCase();
if (google.maps.MapTypeId.hasOwnProperty(type)) {
opts.mapTypeId = google.maps.MapTypeId[attrs.type.toUpperCase()];
} else {
$log.error("angular-google-maps: invalid map type '" + attrs.type + "'");
}
}
mapOptions = angular.extend({}, DEFAULTS, opts, {
center: _this.getCoords(scope.center),
zoom: scope.zoom,
bounds: scope.bounds
});
_gMap = new google.maps.Map(el.find('div')[1], mapOptions);
_gMap['uiGmap_id'] = uuid.generate();
dragging = false;
listeners.push(google.maps.event.addListenerOnce(_gMap, 'idle', function() {
scope.deferred.resolve(_gMap);
return resolveSpawned();
}));
disabledEvents = attrs.events && (((ref = scope.events) != null ? ref.blacklist : void 0) != null) ? scope.events.blacklist : [];
if (_.isString(disabledEvents)) {
disabledEvents = [disabledEvents];
}
maybeHookToEvent = function(eventName, fn, prefn) {
if (!_.contains(disabledEvents, eventName)) {
if (prefn) {
prefn();
}
return listeners.push(google.maps.event.addListener(_gMap, eventName, function() {
var ref1;
if (!((ref1 = scope.update) != null ? ref1.lazy : void 0)) {
return fn();
}
}));
}
};
if (!_.contains(disabledEvents, 'all')) {
maybeHookToEvent('dragstart', function() {
dragging = true;
return scope.$evalAsync(function(s) {
if (s.dragging != null) {
return s.dragging = dragging;
}
});
});
maybeHookToEvent('dragend', function() {
dragging = false;
return scope.$evalAsync(function(s) {
if (s.dragging != null) {
return s.dragging = dragging;
}
});
});
updateCenter = function(c, s) {
if (c == null) {
c = _gMap.center;
}
if (s == null) {
s = scope;
}
if (_.contains(disabledEvents, 'center')) {
return;
}
if (angular.isDefined(s.center.type)) {
if (s.center.coordinates[1] !== c.lat()) {
s.center.coordinates[1] = c.lat();
}
if (s.center.coordinates[0] !== c.lng()) {
return s.center.coordinates[0] = c.lng();
}
} else {
if (s.center.latitude !== c.lat()) {
s.center.latitude = c.lat();
}
if (s.center.longitude !== c.lng()) {
return s.center.longitude = c.lng();
}
}
};
settingFromDirective = false;
maybeHookToEvent('idle', function() {
var b, ne, sw;
b = _gMap.getBounds();
ne = b.getNorthEast();
sw = b.getSouthWest();
settingFromDirective = true;
return scope.$evalAsync(function(s) {
updateCenter();
if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0 && !_.contains(disabledEvents, 'bounds')) {
s.bounds.northeast = {
latitude: ne.lat(),
longitude: ne.lng()
};
s.bounds.southwest = {
latitude: sw.lat(),
longitude: sw.lng()
};
}
if (!_.contains(disabledEvents, 'zoom')) {
s.zoom = _gMap.zoom;
scope.idleAndZoomChanged = !scope.idleAndZoomChanged;
}
return settingFromDirective = false;
});
});
}
if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) {
getEventHandler = function(eventName) {
return function() {
return scope.events[eventName].apply(scope, [_gMap, eventName, arguments]);
};
};
customListeners = [];
for (eventName in scope.events) {
if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) {
customListeners.push(google.maps.event.addListener(_gMap, eventName, getEventHandler(eventName)));
}
}
listeners.concat(customListeners);
}
_gMap.getOptions = function() {
return mapOptions;
};
scope.map = _gMap;
if ((attrs.control != null) && (scope.control != null)) {
scope.control.refresh = function(maybeCoords) {
var coords, ref1, ref2;
if (_gMap == null) {
return;
}
if (((typeof google !== "undefined" && google !== null ? (ref1 = google.maps) != null ? (ref2 = ref1.event) != null ? ref2.trigger : void 0 : void 0 : void 0) != null) && (_gMap != null)) {
google.maps.event.trigger(_gMap, 'resize');
}
if (((maybeCoords != null ? maybeCoords.latitude : void 0) != null) && ((maybeCoords != null ? maybeCoords.longitude : void 0) != null)) {
coords = _this.getCoords(maybeCoords);
if (_this.isTrue(attrs.pan)) {
return _gMap.panTo(coords);
} else {
return _gMap.setCenter(coords);
}
}
};
scope.control.getGMap = function() {
return _gMap;
};
scope.control.getMapOptions = function() {
return mapOptions;
};
scope.control.getCustomEventListeners = function() {
return customListeners;
};
scope.control.removeEvents = function(yourListeners) {
return EventsHelper.removeEvents(yourListeners);
};
}
scope.$watch('center', function(newValue, oldValue) {
var coords, settingCenterFromScope;
if (newValue === oldValue || settingFromDirective) {
return;
}
coords = _this.getCoords(scope.center);
if (coords.lat() === _gMap.center.lat() && coords.lng() === _gMap.center.lng()) {
return;
}
settingCenterFromScope = true;
if (!dragging) {
if (!_this.validateCoords(newValue)) {
$log.error("Invalid center for newValue: " + (JSON.stringify(newValue)));
}
if (_this.isTrue(attrs.pan) && scope.zoom === _gMap.zoom) {
_gMap.panTo(coords);
} else {
_gMap.setCenter(coords);
}
}
return settingCenterFromScope = false;
}, true);
zoomPromise = null;
scope.$watch('zoom', function(newValue, oldValue) {
var ref1, ref2, settingZoomFromScope;
if (newValue == null) {
return;
}
if (_.isEqual(newValue, oldValue) || (_gMap != null ? _gMap.getZoom() : void 0) === (scope != null ? scope.zoom : void 0) || settingFromDirective) {
return;
}
settingZoomFromScope = true;
if (zoomPromise != null) {
$timeout.cancel(zoomPromise);
}
return zoomPromise = $timeout(function() {
_gMap.setZoom(newValue);
return settingZoomFromScope = false;
}, ((ref1 = scope.eventOpts) != null ? (ref2 = ref1.debounce) != null ? ref2.zoomMs : void 0 : void 0) + 20, false);
});
scope.$watch('bounds', function(newValue, oldValue) {
var bounds, ne, ref1, ref2, ref3, ref4, sw;
if (newValue === oldValue) {
return;
}
if (((newValue != null ? (ref1 = newValue.northeast) != null ? ref1.latitude : void 0 : void 0) == null) || ((newValue != null ? (ref2 = newValue.northeast) != null ? ref2.longitude : void 0 : void 0) == null) || ((newValue != null ? (ref3 = newValue.southwest) != null ? ref3.latitude : void 0 : void 0) == null) || ((newValue != null ? (ref4 = newValue.southwest) != null ? ref4.longitude : void 0 : void 0) == null)) {
$log.error("Invalid map bounds for new value: " + (JSON.stringify(newValue)));
return;
}
ne = new google.maps.LatLng(newValue.northeast.latitude, newValue.northeast.longitude);
sw = new google.maps.LatLng(newValue.southwest.latitude, newValue.southwest.longitude);
bounds = new google.maps.LatLngBounds(sw, ne);
return _gMap.fitBounds(bounds);
});
return ['options', 'styles'].forEach(function(toWatch) {
return scope.$watch(toWatch, function(newValue, oldValue) {
var watchItem;
watchItem = this.exp;
if (_.isEqual(newValue, oldValue)) {
return;
}
if (watchItem === 'options') {
opts.options = newValue;
} else {
opts.options[watchItem] = newValue;
}
if (_gMap != null) {
return _gMap.setOptions(opts);
}
}, true);
});
};
})(this));
};
return Map;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarker", [
"uiGmapIMarker", "uiGmapMarkerChildModel", "uiGmapMarkerManager", "uiGmapLogger", function(IMarker, MarkerChildModel, MarkerManager, $log) {
var Marker;
return Marker = (function(superClass) {
extend(Marker, superClass);
function Marker() {
this.link = bind(this.link, this);
Marker.__super__.constructor.call(this);
this.template = '<span class="angular-google-map-marker" ng-transclude></span>';
$log.info(this);
}
Marker.prototype.controller = [
'$scope', '$element', function($scope, $element) {
$scope.ctrlType = 'Marker';
return _.extend(this, IMarker.handle($scope, $element));
}
];
Marker.prototype.link = function(scope, element, attrs, ctrl) {
var mapPromise;
mapPromise = IMarker.mapPromise(scope, ctrl);
mapPromise.then((function(_this) {
return function(map) {
var doClick, doDrawSelf, gManager, keys, m, trackModel;
gManager = new MarkerManager(map);
keys = _.object(IMarker.keys, IMarker.keys);
m = new MarkerChildModel(scope, scope, keys, map, {}, doClick = true, gManager, doDrawSelf = false, trackModel = false);
m.deferred.promise.then(function(gMarker) {
return scope.deferred.resolve(gMarker);
});
if (scope.control != null) {
return scope.control.getGMarkers = gManager.getGMarkers;
}
};
})(this));
return scope.$on('$destroy', (function(_this) {
return function() {
var gManager;
if (typeof gManager !== "undefined" && gManager !== null) {
gManager.clear();
}
return gManager = null;
};
})(this));
};
return Marker;
})(IMarker);
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarkers", [
"uiGmapIMarker", "uiGmapPlural", "uiGmapMarkersParentModel", "uiGmap_sync", "uiGmapLogger", function(IMarker, Plural, MarkersParentModel, _sync, $log) {
var Markers;
return Markers = (function(superClass) {
extend(Markers, superClass);
function Markers() {
Markers.__super__.constructor.call(this);
this.template = '<span class="angular-google-map-markers" ng-transclude></span>';
Plural.extend(this, {
doCluster: '=docluster',
clusterOptions: '=clusteroptions',
clusterEvents: '=clusterevents',
modelsByRef: '=modelsbyref'
});
$log.info(this);
}
Markers.prototype.controller = [
'$scope', '$element', function($scope, $element) {
$scope.ctrlType = 'Markers';
return _.extend(this, IMarker.handle($scope, $element));
}
];
Markers.prototype.link = function(scope, element, attrs, ctrl) {
var parentModel, ready;
parentModel = void 0;
ready = function() {
return scope.deferred.resolve();
};
return IMarker.mapPromise(scope, ctrl).then(function(map) {
var mapScope;
mapScope = ctrl.getScope();
mapScope.$watch('idleAndZoomChanged', function() {
return _.defer(parentModel.gManager.draw);
});
parentModel = new MarkersParentModel(scope, element, attrs, map);
Plural.link(scope, parentModel);
if (scope.control != null) {
scope.control.getGMarkers = function() {
var ref;
return (ref = parentModel.gManager) != null ? ref.getGMarkers() : void 0;
};
scope.control.getChildMarkers = function() {
return parentModel.plurals;
};
}
return _.last(parentModel.existingPieces._content).then(function() {
return ready();
});
});
};
return Markers;
})(IMarker);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapPlural', [
function() {
var _initControl;
_initControl = function(scope, parent) {
if (scope.control == null) {
return;
}
scope.control.updateModels = function(models) {
scope.models = models;
return parent.createChildScopes(false);
};
scope.control.newModels = function(models) {
scope.models = models;
return parent.rebuildAll(scope, true, true);
};
scope.control.clean = function() {
return parent.rebuildAll(scope, false, true);
};
scope.control.getPlurals = function() {
return parent.plurals;
};
scope.control.getManager = function() {
return parent.gManager;
};
scope.control.hasManager = function() {
return (parent.gManager != null) === true;
};
return scope.control.managerDraw = function() {
var ref;
if (scope.control.hasManager()) {
return (ref = scope.control.getManager()) != null ? ref.draw() : void 0;
}
};
};
return {
extend: function(obj, obj2) {
return _.extend(obj.scope || {}, obj2 || {}, {
idKey: '=idkey',
doRebuildAll: '=dorebuildall',
models: '=models',
chunk: '=chunk',
cleanchunk: '=cleanchunk',
control: '=control'
});
},
link: function(scope, parent) {
return _initControl(scope, parent);
}
};
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygon', [
'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonChildModel', function(IPolygon, $timeout, arraySync, PolygonChild) {
var Polygon;
return Polygon = (function(superClass) {
extend(Polygon, superClass);
function Polygon() {
this.link = bind(this.link, this);
return Polygon.__super__.constructor.apply(this, arguments);
}
Polygon.prototype.link = function(scope, element, attrs, mapCtrl) {
var children, promise;
children = [];
promise = IPolygon.mapPromise(scope, mapCtrl);
if (scope.control != null) {
scope.control.getInstance = this;
scope.control.polygons = children;
scope.control.promise = promise;
}
return promise.then((function(_this) {
return function(map) {
return children.push(new PolygonChild(scope, attrs, map, _this.DEFAULTS));
};
})(this));
};
return Polygon;
})(IPolygon);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygons', [
'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonsParentModel', 'uiGmapPlural', function(Interface, $timeout, arraySync, ParentModel, Plural) {
var Polygons;
return Polygons = (function(superClass) {
extend(Polygons, superClass);
function Polygons() {
this.link = bind(this.link, this);
Polygons.__super__.constructor.call(this);
Plural.extend(this);
this.$log.info(this);
}
Polygons.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
if (angular.isUndefined(scope.path) || scope.path === null) {
_this.$log.warn('polygons: no valid path attribute found');
}
if (!scope.models) {
_this.$log.warn('polygons: no models found to create from');
}
return Plural.link(scope, new ParentModel(scope, element, attrs, map, _this.DEFAULTS));
};
})(this));
};
return Polygons;
})(Interface);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolyline', [
'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylineChildModel', function(IPolyline, $timeout, arraySync, PolylineChildModel) {
var Polyline;
return Polyline = (function(superClass) {
extend(Polyline, superClass);
function Polyline() {
this.link = bind(this.link, this);
return Polyline.__super__.constructor.apply(this, arguments);
}
Polyline.prototype.link = function(scope, element, attrs, mapCtrl) {
return IPolyline.mapPromise(scope, mapCtrl).then((function(_this) {
return function(map) {
if (angular.isUndefined(scope.path) || scope.path === null || !_this.validatePath(scope.path)) {
_this.$log.warn('polyline: no valid path attribute found');
}
return new PolylineChildModel(scope, attrs, map, _this.DEFAULTS);
};
})(this));
};
return Polyline;
})(IPolyline);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylines', [
'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylinesParentModel', 'uiGmapPlural', function(IPolyline, $timeout, arraySync, PolylinesParentModel, Plural) {
var Polylines;
return Polylines = (function(superClass) {
extend(Polylines, superClass);
function Polylines() {
this.link = bind(this.link, this);
Polylines.__super__.constructor.call(this);
Plural.extend(this);
this.$log.info(this);
}
Polylines.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
if (angular.isUndefined(scope.path) || scope.path === null) {
_this.$log.warn('polylines: no valid path attribute found');
}
if (!scope.models) {
_this.$log.warn('polylines: no models found to create from');
}
return Plural.link(scope, new PolylinesParentModel(scope, element, attrs, map, _this.DEFAULTS));
};
})(this));
};
return Polylines;
})(IPolyline);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapRectangle', [
'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapIRectangle', 'uiGmapRectangleParentModel', function($log, GmapUtil, IRectangle, RectangleParentModel) {
return _.extend(IRectangle, {
link: function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
return new RectangleParentModel(scope, element, attrs, map);
};
})(this));
}
});
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindow', [
'uiGmapIWindow', 'uiGmapGmapUtil', 'uiGmapWindowChildModel', 'uiGmapLodash', 'uiGmapLogger', function(IWindow, GmapUtil, WindowChildModel, uiGmapLodash, $log) {
var Window;
return Window = (function(superClass) {
extend(Window, superClass);
Window.include(GmapUtil);
function Window() {
this.link = bind(this.link, this);
Window.__super__.constructor.call(this);
this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarker'];
this.template = '<span class="angular-google-maps-window" ng-transclude></span>';
$log.debug(this);
this.childWindows = [];
}
Window.prototype.link = function(scope, element, attrs, ctrls) {
var markerCtrl, markerScope;
markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0;
markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0;
this.mapPromise = IWindow.mapPromise(scope, ctrls[0]);
return this.mapPromise.then((function(_this) {
return function(mapCtrl) {
var isIconVisibleOnClick;
isIconVisibleOnClick = true;
if (angular.isDefined(attrs.isiconvisibleonclick)) {
isIconVisibleOnClick = scope.isIconVisibleOnClick;
}
if (!markerCtrl) {
_this.init(scope, element, isIconVisibleOnClick, mapCtrl);
return;
}
return markerScope.deferred.promise.then(function(gMarker) {
return _this.init(scope, element, isIconVisibleOnClick, mapCtrl, markerScope);
});
};
})(this));
};
Window.prototype.init = function(scope, element, isIconVisibleOnClick, mapCtrl, markerScope) {
var childWindow, defaults, gMarker, hasScopeCoords, opts;
defaults = scope.options != null ? scope.options : {};
hasScopeCoords = (scope != null) && this.validateCoords(scope.coords);
if ((markerScope != null ? markerScope['getGMarker'] : void 0) != null) {
gMarker = markerScope.getGMarker();
}
opts = hasScopeCoords ? this.createWindowOptions(gMarker, scope, element.html(), defaults) : defaults;
if (mapCtrl != null) {
childWindow = new WindowChildModel({}, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element);
this.childWindows.push(childWindow);
scope.$on('$destroy', (function(_this) {
return function() {
_this.childWindows = uiGmapLodash.withoutObjects(_this.childWindows, [childWindow], function(child1, child2) {
return child1.scope.$id === child2.scope.$id;
});
return _this.childWindows.length = 0;
};
})(this));
}
if (scope.control != null) {
scope.control.getGWindows = (function(_this) {
return function() {
return _this.childWindows.map(function(child) {
return child.gObject;
});
};
})(this);
scope.control.getChildWindows = (function(_this) {
return function() {
return _this.childWindows;
};
})(this);
scope.control.getPlurals = scope.control.getChildWindows;
scope.control.showWindow = (function(_this) {
return function() {
return _this.childWindows.map(function(child) {
return child.showWindow();
});
};
})(this);
scope.control.hideWindow = (function(_this) {
return function() {
return _this.childWindows.map(function(child) {
return child.hideWindow();
});
};
})(this);
}
if ((this.onChildCreation != null) && (childWindow != null)) {
return this.onChildCreation(childWindow);
}
};
return Window;
})(IWindow);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindows', [
'uiGmapIWindow', 'uiGmapPlural', 'uiGmapWindowsParentModel', 'uiGmapPromise', 'uiGmapLogger', function(IWindow, Plural, WindowsParentModel, uiGmapPromise, $log) {
/*
Windows directive where many windows map to the models property
*/
var Windows;
return Windows = (function(superClass) {
extend(Windows, superClass);
function Windows() {
this.init = bind(this.init, this);
this.link = bind(this.link, this);
Windows.__super__.constructor.call(this);
this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarkers'];
this.template = '<span class="angular-google-maps-windows" ng-transclude></span>';
Plural.extend(this);
$log.debug(this);
}
Windows.prototype.link = function(scope, element, attrs, ctrls) {
var mapScope, markerCtrl, markerScope;
mapScope = ctrls[0].getScope();
markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0;
markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0;
return mapScope.deferred.promise.then((function(_this) {
return function(map) {
var promise, ref;
promise = (markerScope != null ? (ref = markerScope.deferred) != null ? ref.promise : void 0 : void 0) || uiGmapPromise.resolve();
return promise.then(function() {
var pieces, ref1;
pieces = (ref1 = _this.parentModel) != null ? ref1.existingPieces : void 0;
if (pieces) {
return pieces.then(function() {
return _this.init(scope, element, attrs, ctrls, map, markerScope);
});
} else {
return _this.init(scope, element, attrs, ctrls, map, markerScope);
}
});
};
})(this));
};
Windows.prototype.init = function(scope, element, attrs, ctrls, map, additionalScope) {
var parentModel;
parentModel = new WindowsParentModel(scope, element, attrs, ctrls, map, additionalScope);
Plural.link(scope, parentModel);
if (scope.control != null) {
scope.control.getGWindows = (function(_this) {
return function() {
return parentModel.plurals.map(function(child) {
return child.gObject;
});
};
})(this);
return scope.control.getChildWindows = (function(_this) {
return function() {
return parentModel.plurals;
};
})(this);
}
};
return Windows;
})(IWindow);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Nick Baugh - https://github.com/niftylettuce
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapGoogleMap", [
"uiGmapMap", function(Map) {
return new Map();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map marker directive
This directive is used to create a marker on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute icon optional} string url to image used for marker icon
{attribute animate optional} if set to false, the marker won't be animated (on by default)
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapMarker', [
'$timeout', 'uiGmapMarker', function($timeout, Marker) {
return new Marker($timeout);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map marker directive
This directive is used to create a marker on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute icon optional} string url to image used for marker icon
{attribute animate optional} if set to false, the marker won't be animated (on by default)
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapMarkers', [
'$timeout', 'uiGmapMarkers', function($timeout, Markers) {
return new Markers($timeout);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Rick Huizinga - https://plus.google.com/+RickHuizinga
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapPolygon', [
'uiGmapPolygon', function(Polygon) {
return new Polygon();
}
]);
}).call(this);
;
/*
@authors
Julian Popescu - https://github.com/jpopesculian
Rick Huizinga - https://plus.google.com/+RickHuizinga
*/
(function() {
angular.module('uiGmapgoogle-maps').directive("uiGmapCircle", [
"uiGmapCircle", function(Circle) {
return Circle;
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapPolyline", [
"uiGmapPolyline", function(Polyline) {
return new Polyline();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapPolylines', [
'uiGmapPolylines', function(Polylines) {
return new Polylines();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Chentsu Lin - https://github.com/ChenTsuLin
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapRectangle", [
"uiGmapLogger", "uiGmapRectangle", function($log, Rectangle) {
return Rectangle;
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map info window directive
This directive is used to create an info window on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute show optional} map will show when this expression returns true
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapWindow", [
"$timeout", "$compile", "$http", "$templateCache", "uiGmapWindow", function($timeout, $compile, $http, $templateCache, Window) {
return new Window($timeout, $compile, $http, $templateCache);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map info window directive
This directive is used to create an info window on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute show optional} map will show when this expression returns true
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapWindows", [
"$timeout", "$compile", "$http", "$templateCache", "$interpolate", "uiGmapWindows", function($timeout, $compile, $http, $templateCache, $interpolate, Windows) {
return new Windows($timeout, $compile, $http, $templateCache, $interpolate);
}
]);
}).call(this);
;
/*
@authors:
- Nicolas Laplante https://plus.google.com/108189012221374960701
- Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map Layer directive
This directive is used to create any type of Layer from the google maps sdk.
This directive creates a new scope.
{attribute show optional} true (default) shows the trafficlayer otherwise it is hidden
*/
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module('uiGmapgoogle-maps').directive('uiGmapLayer', [
'$timeout', 'uiGmapLogger', 'uiGmapLayerParentModel', function($timeout, Logger, LayerParentModel) {
var Layer;
Layer = (function() {
function Layer() {
this.link = bind(this.link, this);
this.$log = Logger;
this.restrict = 'EMA';
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.template = '<span class=\'angular-google-map-layer\' ng-transclude></span>';
this.replace = true;
this.scope = {
show: '=show',
type: '=type',
namespace: '=namespace',
options: '=options',
onCreated: '&oncreated'
};
}
Layer.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
if (scope.onCreated != null) {
return new LayerParentModel(scope, element, attrs, map, scope.onCreated);
} else {
return new LayerParentModel(scope, element, attrs, map);
}
};
})(this));
};
return Layer;
})();
return new Layer();
}
]);
}).call(this);
;
/*
@authors
Adam Kreitals, [email protected]
*/
/*
mapControl directive
This directive is used to create a custom control element on an existing map.
This directive creates a new scope.
{attribute template required} string url of the template to be used for the control
{attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER
{attribute controller optional} string controller to be applied to the template
{attribute index optional} number index for controlling the order of similarly positioned mapControl elements
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapMapControl", [
"uiGmapControl", function(Control) {
return new Control();
}
]);
}).call(this);
;
/*
@authors
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapDragZoom', [
'uiGmapDragZoom', function(DragZoom) {
return DragZoom;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').directive("uiGmapDrawingManager", [
"uiGmapDrawingManager", function(DrawingManager) {
return DrawingManager;
}
]);
}).call(this);
;
/*
@authors
Nicholas McCready - https://twitter.com/nmccready
* Brunt of the work is in DrawFreeHandChildModel
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapFreeDrawPolygons', [
'uiGmapApiFreeDrawPolygons', function(FreeDrawPolygons) {
return new FreeDrawPolygons();
}
]);
}).call(this);
;
/*
Map Layer directive
This directive is used to create any type of Layer from the google maps sdk.
This directive creates a new scope.
{attribute show optional} true (default) shows the trafficlayer otherwise it is hidden
*/
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module("uiGmapgoogle-maps").directive("uiGmapMapType", [
"$timeout", "uiGmapLogger", "uiGmapMapTypeParentModel", function($timeout, Logger, MapTypeParentModel) {
var MapType;
MapType = (function() {
function MapType() {
this.link = bind(this.link, this);
this.$log = Logger;
this.restrict = "EMA";
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>';
this.replace = true;
this.scope = {
show: "=show",
options: '=options',
refresh: '=refresh',
id: '@'
};
}
MapType.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
return new MapTypeParentModel(scope, element, attrs, map);
};
})(this));
};
return MapType;
})();
return new MapType();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Rick Huizinga - https://plus.google.com/+RickHuizinga
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapPolygons', [
'uiGmapPolygons', function(Polygons) {
return new Polygons();
}
]);
}).call(this);
;
/*
@authors:
- Nicolas Laplante https://plus.google.com/108189012221374960701
- Nicholas McCready - https://twitter.com/nmccready
- Carrie Kengle - http://about.me/carrie
*/
/*
Places Search Box directive
This directive is used to create a Places Search Box.
This directive creates a new scope.
{attribute input required} HTMLInputElement
{attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification)
*/
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module('uiGmapgoogle-maps').directive('uiGmapSearchBox', [
'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapSearchBoxParentModel', '$http', '$templateCache', '$compile', function(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache, $compile) {
var SearchBox;
SearchBox = (function() {
SearchBox.prototype.require = 'ngModel';
function SearchBox() {
this.link = bind(this.link, this);
this.$log = Logger;
this.restrict = 'EMA';
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.template = '<span class=\'angular-google-map-search\' ng-transclude></span>';
this.replace = true;
this.scope = {
template: '=template',
events: '=events',
position: '=?position',
options: '=?options',
parentdiv: '=?parentdiv',
ngModel: "=?"
};
}
SearchBox.prototype.link = function(scope, element, attrs, mapCtrl) {
return GoogleMapApi.then((function(_this) {
return function(maps) {
return $http.get(scope.template, {
cache: $templateCache
}).success(function(template) {
if (angular.isUndefined(scope.events)) {
_this.$log.error('searchBox: the events property is required');
return;
}
return mapCtrl.getScope().deferred.promise.then(function(map) {
var ctrlPosition;
ctrlPosition = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_LEFT';
if (!maps.ControlPosition[ctrlPosition]) {
_this.$log.error('searchBox: invalid position property');
return;
}
return new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, $compile(template)(scope));
});
});
};
})(this));
};
return SearchBox;
})();
return new SearchBox();
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapShow', [
'$animate', 'uiGmapLogger', function($animate, $log) {
return {
scope: {
'uiGmapShow': '=',
'uiGmapAfterShow': '&',
'uiGmapAfterHide': '&'
},
link: function(scope, element) {
var angular_post_1_3_handle, angular_pre_1_3_handle, handle;
angular_post_1_3_handle = function(animateAction, cb) {
return $animate[animateAction](element, 'ng-hide').then(function() {
return cb();
});
};
angular_pre_1_3_handle = function(animateAction, cb) {
return $animate[animateAction](element, 'ng-hide', cb);
};
handle = function(animateAction, cb) {
if (angular.version.major > 1) {
return $log.error("uiGmapShow is not supported for Angular Major greater than 1.\nYour Major is " + angular.version.major + "\"");
}
if (angular.version.major === 1 && angular.version.minor < 3) {
return angular_pre_1_3_handle(animateAction, cb);
}
return angular_post_1_3_handle(animateAction, cb);
};
return scope.$watch('uiGmapShow', function(show) {
if (show) {
handle('removeClass', scope.uiGmapAfterShow);
}
if (!show) {
return handle('addClass', scope.uiGmapAfterHide);
}
});
}
};
}
]);
}).call(this);
;
/*
@authors:
- Nicholas McCready - https://twitter.com/nmccready
*/
/*
StreetViewPanorama Directive to care of basic initialization of StreetViewPanorama
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapStreetViewPanorama', [
'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function(GoogleMapApi, $log, GmapUtil, EventsHelper) {
var name;
name = 'uiGmapStreetViewPanorama';
return {
restrict: 'EMA',
template: '<div class="angular-google-map-street-view-panorama"></div>',
replace: true,
scope: {
focalcoord: '=',
radius: '=?',
events: '=?',
options: '=?',
control: '=?',
povoptions: '=?',
imagestatus: '='
},
link: function(scope, element, attrs) {
return GoogleMapApi.then((function(_this) {
return function(maps) {
var clean, create, didCreateOptionsFromDirective, firstTime, handleSettings, listeners, opts, pano, povOpts, sv;
pano = void 0;
sv = void 0;
didCreateOptionsFromDirective = false;
listeners = void 0;
opts = null;
povOpts = null;
clean = function() {
EventsHelper.removeEvents(listeners);
if (pano != null) {
pano.unbind('position');
pano.setVisible(false);
}
if (sv != null) {
if ((sv != null ? sv.setVisible : void 0) != null) {
sv.setVisible(false);
}
return sv = void 0;
}
};
handleSettings = function(perspectivePoint, focalPoint) {
var heading;
heading = google.maps.geometry.spherical.computeHeading(perspectivePoint, focalPoint);
didCreateOptionsFromDirective = true;
scope.radius = scope.radius || 50;
povOpts = angular.extend({
heading: heading,
zoom: 1,
pitch: 0
}, scope.povoptions || {});
opts = opts = angular.extend({
navigationControl: false,
addressControl: false,
linksControl: false,
position: perspectivePoint,
pov: povOpts,
visible: true
}, scope.options || {});
return didCreateOptionsFromDirective = false;
};
create = function() {
var focalPoint;
if (!scope.focalcoord) {
$log.error(name + ": focalCoord needs to be defined");
return;
}
if (!scope.radius) {
$log.error(name + ": needs a radius to set the camera view from its focal target.");
return;
}
clean();
if (sv == null) {
sv = new google.maps.StreetViewService();
}
if (scope.events) {
listeners = EventsHelper.setEvents(sv, scope, scope);
}
focalPoint = GmapUtil.getCoords(scope.focalcoord);
return sv.getPanoramaByLocation(focalPoint, scope.radius, function(streetViewPanoramaData, status) {
var ele, perspectivePoint, ref;
if (scope.imagestatus != null) {
scope.imagestatus = status;
}
if (((ref = scope.events) != null ? ref.image_status_changed : void 0) != null) {
scope.events.image_status_changed(sv, 'image_status_changed', scope, status);
}
if (status === "OK") {
perspectivePoint = streetViewPanoramaData.location.latLng;
handleSettings(perspectivePoint, focalPoint);
ele = element[0];
return pano = new google.maps.StreetViewPanorama(ele, opts);
}
});
};
if (scope.control != null) {
scope.control.getOptions = function() {
return opts;
};
scope.control.getPovOptions = function() {
return povOpts;
};
scope.control.getGObject = function() {
return sv;
};
scope.control.getGPano = function() {
return pano;
};
}
scope.$watch('options', function(newValue, oldValue) {
if (newValue === oldValue || newValue === opts || didCreateOptionsFromDirective) {
return;
}
return create();
});
firstTime = true;
scope.$watch('focalcoord', function(newValue, oldValue) {
if (newValue === oldValue && !firstTime) {
return;
}
if (newValue == null) {
return;
}
firstTime = false;
return create();
});
return scope.$on('$destroy', function() {
return clean();
});
};
})(this));
}
};
}
]);
}).call(this);
;angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapuuid', function() {
//BEGIN REPLACE
/*
Version: core-1.0
The MIT License: Copyright (c) 2012 LiosK.
*/
function UUID(){}UUID.generate=function(){var a=UUID._gri,b=UUID._ha;return b(a(32),8)+"-"+b(a(16),4)+"-"+b(16384|a(12),4)+"-"+b(32768|a(14),4)+"-"+b(a(48),12)};UUID._gri=function(a){return 0>a?NaN:30>=a?0|Math.random()*(1<<a):53>=a?(0|1073741824*Math.random())+1073741824*(0|Math.random()*(1<<a-30)):NaN};UUID._ha=function(a,b){for(var c=a.toString(16),d=b-c.length,e="0";0<d;d>>>=1,e+=e)d&1&&(c=e+c);return c};
//END REPLACE
return UUID;
});
;// wrap the utility libraries needed in ./lib
// http://google-maps-utility-library-v3.googlecode.com/svn/
angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapGoogleMapsUtilV3', function () {
return {
init: _.once(function () {
//BEGIN REPLACE
/**
* @name InfoBox
* @version 1.1.13 [March 19, 2014]
* @author Gary Little (inspired by proof-of-concept code from Pamela Fox of Google)
* @copyright Copyright 2010 Gary Little [gary at luxcentral.com]
* @fileoverview InfoBox extends the Google Maps JavaScript API V3 <tt>OverlayView</tt> class.
* <p>
* An InfoBox behaves like a <tt>google.maps.InfoWindow</tt>, but it supports several
* additional properties for advanced styling. An InfoBox can also be used as a map label.
* <p>
* An InfoBox also fires the same events as a <tt>google.maps.InfoWindow</tt>.
*/
/*!
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint browser:true */
/*global google */
/**
* @name InfoBoxOptions
* @class This class represents the optional parameter passed to the {@link InfoBox} constructor.
* @property {string|Node} content The content of the InfoBox (plain text or an HTML DOM node).
* @property {boolean} [disableAutoPan=false] Disable auto-pan on <tt>open</tt>.
* @property {number} maxWidth The maximum width (in pixels) of the InfoBox. Set to 0 if no maximum.
* @property {Size} pixelOffset The offset (in pixels) from the top left corner of the InfoBox
* (or the bottom left corner if the <code>alignBottom</code> property is <code>true</code>)
* to the map pixel corresponding to <tt>position</tt>.
* @property {LatLng} position The geographic location at which to display the InfoBox.
* @property {number} zIndex The CSS z-index style value for the InfoBox.
* Note: This value overrides a zIndex setting specified in the <tt>boxStyle</tt> property.
* @property {string} [boxClass="infoBox"] The name of the CSS class defining the styles for the InfoBox container.
* @property {Object} [boxStyle] An object literal whose properties define specific CSS
* style values to be applied to the InfoBox. Style values defined here override those that may
* be defined in the <code>boxClass</code> style sheet. If this property is changed after the
* InfoBox has been created, all previously set styles (except those defined in the style sheet)
* are removed from the InfoBox before the new style values are applied.
* @property {string} closeBoxMargin The CSS margin style value for the close box.
* The default is "2px" (a 2-pixel margin on all sides).
* @property {string} closeBoxURL The URL of the image representing the close box.
* Note: The default is the URL for Google's standard close box.
* Set this property to "" if no close box is required.
* @property {Size} infoBoxClearance Minimum offset (in pixels) from the InfoBox to the
* map edge after an auto-pan.
* @property {boolean} [isHidden=false] Hide the InfoBox on <tt>open</tt>.
* [Deprecated in favor of the <tt>visible</tt> property.]
* @property {boolean} [visible=true] Show the InfoBox on <tt>open</tt>.
* @property {boolean} alignBottom Align the bottom left corner of the InfoBox to the <code>position</code>
* location (default is <tt>false</tt> which means that the top left corner of the InfoBox is aligned).
* @property {string} pane The pane where the InfoBox is to appear (default is "floatPane").
* Set the pane to "mapPane" if the InfoBox is being used as a map label.
* Valid pane names are the property names for the <tt>google.maps.MapPanes</tt> object.
* @property {boolean} enableEventPropagation Propagate mousedown, mousemove, mouseover, mouseout,
* mouseup, click, dblclick, touchstart, touchend, touchmove, and contextmenu events in the InfoBox
* (default is <tt>false</tt> to mimic the behavior of a <tt>google.maps.InfoWindow</tt>). Set
* this property to <tt>true</tt> if the InfoBox is being used as a map label.
*/
/**
* Creates an InfoBox with the options specified in {@link InfoBoxOptions}.
* Call <tt>InfoBox.open</tt> to add the box to the map.
* @constructor
* @param {InfoBoxOptions} [opt_opts]
*/
function InfoBox(opt_opts) {
opt_opts = opt_opts || {};
google.maps.OverlayView.apply(this, arguments);
// Standard options (in common with google.maps.InfoWindow):
//
this.content_ = opt_opts.content || "";
this.disableAutoPan_ = opt_opts.disableAutoPan || false;
this.maxWidth_ = opt_opts.maxWidth || 0;
this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0);
this.position_ = opt_opts.position || new google.maps.LatLng(0, 0);
this.zIndex_ = opt_opts.zIndex || null;
// Additional options (unique to InfoBox):
//
this.boxClass_ = opt_opts.boxClass || "infoBox";
this.boxStyle_ = opt_opts.boxStyle || {};
this.closeBoxMargin_ = opt_opts.closeBoxMargin || "2px";
this.closeBoxURL_ = opt_opts.closeBoxURL || "http://www.google.com/intl/en_us/mapfiles/close.gif";
if (opt_opts.closeBoxURL === "") {
this.closeBoxURL_ = "";
}
this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1);
if (typeof opt_opts.visible === "undefined") {
if (typeof opt_opts.isHidden === "undefined") {
opt_opts.visible = true;
} else {
opt_opts.visible = !opt_opts.isHidden;
}
}
this.isHidden_ = !opt_opts.visible;
this.alignBottom_ = opt_opts.alignBottom || false;
this.pane_ = opt_opts.pane || "floatPane";
this.enableEventPropagation_ = opt_opts.enableEventPropagation || false;
this.div_ = null;
this.closeListener_ = null;
this.moveListener_ = null;
this.contextListener_ = null;
this.eventListeners_ = null;
this.fixedWidthSet_ = null;
}
/* InfoBox extends OverlayView in the Google Maps API v3.
*/
InfoBox.prototype = new google.maps.OverlayView();
/**
* Creates the DIV representing the InfoBox.
* @private
*/
InfoBox.prototype.createInfoBoxDiv_ = function () {
var i;
var events;
var bw;
var me = this;
// This handler prevents an event in the InfoBox from being passed on to the map.
//
var cancelHandler = function (e) {
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
};
// This handler ignores the current event in the InfoBox and conditionally prevents
// the event from being passed on to the map. It is used for the contextmenu event.
//
var ignoreHandler = function (e) {
e.returnValue = false;
if (e.preventDefault) {
e.preventDefault();
}
if (!me.enableEventPropagation_) {
cancelHandler(e);
}
};
if (!this.div_) {
this.div_ = document.createElement("div");
this.setBoxStyle_();
if (typeof this.content_.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + this.content_;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(this.content_);
}
// Add the InfoBox DIV to the DOM
this.getPanes()[this.pane_].appendChild(this.div_);
this.addClickHandler_();
if (this.div_.style.width) {
this.fixedWidthSet_ = true;
} else {
if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) {
this.div_.style.width = this.maxWidth_;
this.div_.style.overflow = "auto";
this.fixedWidthSet_ = true;
} else { // The following code is needed to overcome problems with MSIE
bw = this.getBoxWidths_();
this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px";
this.fixedWidthSet_ = false;
}
}
this.panBox_(this.disableAutoPan_);
if (!this.enableEventPropagation_) {
this.eventListeners_ = [];
// Cancel event propagation.
//
// Note: mousemove not included (to resolve Issue 152)
events = ["mousedown", "mouseover", "mouseout", "mouseup",
"click", "dblclick", "touchstart", "touchend", "touchmove"];
for (i = 0; i < events.length; i++) {
this.eventListeners_.push(google.maps.event.addDomListener(this.div_, events[i], cancelHandler));
}
// Workaround for Google bug that causes the cursor to change to a pointer
// when the mouse moves over a marker underneath InfoBox.
this.eventListeners_.push(google.maps.event.addDomListener(this.div_, "mouseover", function (e) {
this.style.cursor = "default";
}));
}
this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler);
/**
* This event is fired when the DIV containing the InfoBox's content is attached to the DOM.
* @name InfoBox#domready
* @event
*/
google.maps.event.trigger(this, "domready");
}
};
/**
* Returns the HTML <IMG> tag for the close box.
* @private
*/
InfoBox.prototype.getCloseBoxImg_ = function () {
var img = "";
if (this.closeBoxURL_ !== "") {
img = "<img";
img += " src='" + this.closeBoxURL_ + "'";
img += " align=right"; // Do this because Opera chokes on style='float: right;'
img += " style='";
img += " position: relative;"; // Required by MSIE
img += " cursor: pointer;";
img += " margin: " + this.closeBoxMargin_ + ";";
img += "'>";
}
return img;
};
/**
* Adds the click handler to the InfoBox close box.
* @private
*/
InfoBox.prototype.addClickHandler_ = function () {
var closeBox;
if (this.closeBoxURL_ !== "") {
closeBox = this.div_.firstChild;
this.closeListener_ = google.maps.event.addDomListener(closeBox, "click", this.getCloseClickHandler_());
} else {
this.closeListener_ = null;
}
};
/**
* Returns the function to call when the user clicks the close box of an InfoBox.
* @private
*/
InfoBox.prototype.getCloseClickHandler_ = function () {
var me = this;
return function (e) {
// 1.0.3 fix: Always prevent propagation of a close box click to the map:
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
/**
* This event is fired when the InfoBox's close box is clicked.
* @name InfoBox#closeclick
* @event
*/
google.maps.event.trigger(me, "closeclick");
me.close();
};
};
/**
* Pans the map so that the InfoBox appears entirely within the map's visible area.
* @private
*/
InfoBox.prototype.panBox_ = function (disablePan) {
var map;
var bounds;
var xOffset = 0, yOffset = 0;
if (!disablePan) {
map = this.getMap();
if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama
if (!map.getBounds().contains(this.position_)) {
// Marker not in visible area of map, so set center
// of map to the marker position first.
map.setCenter(this.position_);
}
bounds = map.getBounds();
var mapDiv = map.getDiv();
var mapWidth = mapDiv.offsetWidth;
var mapHeight = mapDiv.offsetHeight;
var iwOffsetX = this.pixelOffset_.width;
var iwOffsetY = this.pixelOffset_.height;
var iwWidth = this.div_.offsetWidth;
var iwHeight = this.div_.offsetHeight;
var padX = this.infoBoxClearance_.width;
var padY = this.infoBoxClearance_.height;
var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_);
if (pixPosition.x < (-iwOffsetX + padX)) {
xOffset = pixPosition.x + iwOffsetX - padX;
} else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) {
xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth;
}
if (this.alignBottom_) {
if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) {
yOffset = pixPosition.y + iwOffsetY - padY - iwHeight;
} else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) {
yOffset = pixPosition.y + iwOffsetY + padY - mapHeight;
}
} else {
if (pixPosition.y < (-iwOffsetY + padY)) {
yOffset = pixPosition.y + iwOffsetY - padY;
} else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) {
yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight;
}
}
if (!(xOffset === 0 && yOffset === 0)) {
// Move the map to the shifted center.
//
var c = map.getCenter();
map.panBy(xOffset, yOffset);
}
}
}
};
/**
* Sets the style of the InfoBox by setting the style sheet and applying
* other specific styles requested.
* @private
*/
InfoBox.prototype.setBoxStyle_ = function () {
var i, boxStyle;
if (this.div_) {
// Apply style values from the style sheet defined in the boxClass parameter:
this.div_.className = this.boxClass_;
// Clear existing inline style values:
this.div_.style.cssText = "";
// Apply style values defined in the boxStyle parameter:
boxStyle = this.boxStyle_;
for (i in boxStyle) {
if (boxStyle.hasOwnProperty(i)) {
this.div_.style[i] = boxStyle[i];
}
}
// Fix for iOS disappearing InfoBox problem.
// See http://stackoverflow.com/questions/9229535/google-maps-markers-disappear-at-certain-zoom-level-only-on-iphone-ipad
this.div_.style.WebkitTransform = "translateZ(0)";
// Fix up opacity style for benefit of MSIE:
//
if (typeof this.div_.style.opacity !== "undefined" && this.div_.style.opacity !== "") {
// See http://www.quirksmode.org/css/opacity.html
this.div_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(Opacity=" + (this.div_.style.opacity * 100) + ")\"";
this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")";
}
// Apply required styles:
//
this.div_.style.position = "absolute";
this.div_.style.visibility = 'hidden';
if (this.zIndex_ !== null) {
this.div_.style.zIndex = this.zIndex_;
}
}
};
/**
* Get the widths of the borders of the InfoBox.
* @private
* @return {Object} widths object (top, bottom left, right)
*/
InfoBox.prototype.getBoxWidths_ = function () {
var computedStyle;
var bw = {top: 0, bottom: 0, left: 0, right: 0};
var box = this.div_;
if (document.defaultView && document.defaultView.getComputedStyle) {
computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, "");
if (computedStyle) {
// The computed styles are always in pixel units (good!)
bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;
}
} else if (document.documentElement.currentStyle) { // MSIE
if (box.currentStyle) {
// The current styles may not be in pixel units, but assume they are (bad!)
bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0;
}
}
return bw;
};
/**
* Invoked when <tt>close</tt> is called. Do not call it directly.
*/
InfoBox.prototype.onRemove = function () {
if (this.div_) {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
/**
* Draws the InfoBox based on the current map projection and zoom level.
*/
InfoBox.prototype.draw = function () {
this.createInfoBoxDiv_();
var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_);
this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + "px";
if (this.alignBottom_) {
this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + "px";
} else {
this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + "px";
}
if (this.isHidden_) {
this.div_.style.visibility = "hidden";
} else {
this.div_.style.visibility = "visible";
}
};
/**
* Sets the options for the InfoBox. Note that changes to the <tt>maxWidth</tt>,
* <tt>closeBoxMargin</tt>, <tt>closeBoxURL</tt>, and <tt>enableEventPropagation</tt>
* properties have no affect until the current InfoBox is <tt>close</tt>d and a new one
* is <tt>open</tt>ed.
* @param {InfoBoxOptions} opt_opts
*/
InfoBox.prototype.setOptions = function (opt_opts) {
if (typeof opt_opts.boxClass !== "undefined") { // Must be first
this.boxClass_ = opt_opts.boxClass;
this.setBoxStyle_();
}
if (typeof opt_opts.boxStyle !== "undefined") { // Must be second
this.boxStyle_ = opt_opts.boxStyle;
this.setBoxStyle_();
}
if (typeof opt_opts.content !== "undefined") {
this.setContent(opt_opts.content);
}
if (typeof opt_opts.disableAutoPan !== "undefined") {
this.disableAutoPan_ = opt_opts.disableAutoPan;
}
if (typeof opt_opts.maxWidth !== "undefined") {
this.maxWidth_ = opt_opts.maxWidth;
}
if (typeof opt_opts.pixelOffset !== "undefined") {
this.pixelOffset_ = opt_opts.pixelOffset;
}
if (typeof opt_opts.alignBottom !== "undefined") {
this.alignBottom_ = opt_opts.alignBottom;
}
if (typeof opt_opts.position !== "undefined") {
this.setPosition(opt_opts.position);
}
if (typeof opt_opts.zIndex !== "undefined") {
this.setZIndex(opt_opts.zIndex);
}
if (typeof opt_opts.closeBoxMargin !== "undefined") {
this.closeBoxMargin_ = opt_opts.closeBoxMargin;
}
if (typeof opt_opts.closeBoxURL !== "undefined") {
this.closeBoxURL_ = opt_opts.closeBoxURL;
}
if (typeof opt_opts.infoBoxClearance !== "undefined") {
this.infoBoxClearance_ = opt_opts.infoBoxClearance;
}
if (typeof opt_opts.isHidden !== "undefined") {
this.isHidden_ = opt_opts.isHidden;
}
if (typeof opt_opts.visible !== "undefined") {
this.isHidden_ = !opt_opts.visible;
}
if (typeof opt_opts.enableEventPropagation !== "undefined") {
this.enableEventPropagation_ = opt_opts.enableEventPropagation;
}
if (this.div_) {
this.draw();
}
};
/**
* Sets the content of the InfoBox.
* The content can be plain text or an HTML DOM node.
* @param {string|Node} content
*/
InfoBox.prototype.setContent = function (content) {
this.content_ = content;
if (this.div_) {
if (this.closeListener_) {
google.maps.event.removeListener(this.closeListener_);
this.closeListener_ = null;
}
// Odd code required to make things work with MSIE.
//
if (!this.fixedWidthSet_) {
this.div_.style.width = "";
}
if (typeof content.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + content;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(content);
}
// Perverse code required to make things work with MSIE.
// (Ensures the close box does, in fact, float to the right.)
//
if (!this.fixedWidthSet_) {
this.div_.style.width = this.div_.offsetWidth + "px";
if (typeof content.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + content;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(content);
}
}
this.addClickHandler_();
}
/**
* This event is fired when the content of the InfoBox changes.
* @name InfoBox#content_changed
* @event
*/
google.maps.event.trigger(this, "content_changed");
};
/**
* Sets the geographic location of the InfoBox.
* @param {LatLng} latlng
*/
InfoBox.prototype.setPosition = function (latlng) {
this.position_ = latlng;
if (this.div_) {
this.draw();
}
/**
* This event is fired when the position of the InfoBox changes.
* @name InfoBox#position_changed
* @event
*/
google.maps.event.trigger(this, "position_changed");
};
/**
* Sets the zIndex style for the InfoBox.
* @param {number} index
*/
InfoBox.prototype.setZIndex = function (index) {
this.zIndex_ = index;
if (this.div_) {
this.div_.style.zIndex = index;
}
/**
* This event is fired when the zIndex of the InfoBox changes.
* @name InfoBox#zindex_changed
* @event
*/
google.maps.event.trigger(this, "zindex_changed");
};
/**
* Sets the visibility of the InfoBox.
* @param {boolean} isVisible
*/
InfoBox.prototype.setVisible = function (isVisible) {
this.isHidden_ = !isVisible;
if (this.div_) {
this.div_.style.visibility = (this.isHidden_ ? "hidden" : "visible");
}
};
/**
* Returns the content of the InfoBox.
* @returns {string}
*/
InfoBox.prototype.getContent = function () {
return this.content_;
};
/**
* Returns the geographic location of the InfoBox.
* @returns {LatLng}
*/
InfoBox.prototype.getPosition = function () {
return this.position_;
};
/**
* Returns the zIndex for the InfoBox.
* @returns {number}
*/
InfoBox.prototype.getZIndex = function () {
return this.zIndex_;
};
/**
* Returns a flag indicating whether the InfoBox is visible.
* @returns {boolean}
*/
InfoBox.prototype.getVisible = function () {
var isVisible;
if ((typeof this.getMap() === "undefined") || (this.getMap() === null)) {
isVisible = false;
} else {
isVisible = !this.isHidden_;
}
return isVisible;
};
/**
* Shows the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.]
*/
InfoBox.prototype.show = function () {
this.isHidden_ = false;
if (this.div_) {
this.div_.style.visibility = "visible";
}
};
/**
* Hides the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.]
*/
InfoBox.prototype.hide = function () {
this.isHidden_ = true;
if (this.div_) {
this.div_.style.visibility = "hidden";
}
};
/**
* Adds the InfoBox to the specified map or Street View panorama. If <tt>anchor</tt>
* (usually a <tt>google.maps.Marker</tt>) is specified, the position
* of the InfoBox is set to the position of the <tt>anchor</tt>. If the
* anchor is dragged to a new location, the InfoBox moves as well.
* @param {Map|StreetViewPanorama} map
* @param {MVCObject} [anchor]
*/
InfoBox.prototype.open = function (map, anchor) {
var me = this;
if (anchor) {
this.position_ = anchor.getPosition();
this.moveListener_ = google.maps.event.addListener(anchor, "position_changed", function () {
me.setPosition(this.getPosition());
});
}
this.setMap(map);
if (this.div_) {
this.panBox_();
}
};
/**
* Removes the InfoBox from the map.
*/
InfoBox.prototype.close = function () {
var i;
if (this.closeListener_) {
google.maps.event.removeListener(this.closeListener_);
this.closeListener_ = null;
}
if (this.eventListeners_) {
for (i = 0; i < this.eventListeners_.length; i++) {
google.maps.event.removeListener(this.eventListeners_[i]);
}
this.eventListeners_ = null;
}
if (this.moveListener_) {
google.maps.event.removeListener(this.moveListener_);
this.moveListener_ = null;
}
if (this.contextListener_) {
google.maps.event.removeListener(this.contextListener_);
this.contextListener_ = null;
}
this.setMap(null);
};
/**
* @name KeyDragZoom for V3
* @version 2.0.9 [December 17, 2012] NOT YET RELEASED
* @author: Nianwei Liu [nianwei at gmail dot com] & Gary Little [gary at luxcentral dot com]
* @fileoverview This library adds a drag zoom capability to a V3 Google map.
* When drag zoom is enabled, holding down a designated hot key <code>(shift | ctrl | alt)</code>
* while dragging a box around an area of interest will zoom the map in to that area when
* the mouse button is released. Optionally, a visual control can also be supplied for turning
* a drag zoom operation on and off.
* Only one line of code is needed: <code>google.maps.Map.enableKeyDragZoom();</code>
* <p>
* NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2,
* it causes a context menu to appear when running on the Macintosh.
* <p>
* Note that if the map's container has a border around it, the border widths must be specified
* in pixel units (or as thin, medium, or thick). This is required because of an MSIE limitation.
* <p>NL: 2009-05-28: initial port to core API V3.
* <br>NL: 2009-11-02: added a temp fix for -moz-transform for FF3.5.x using code from Paul Kulchenko (http://notebook.kulchenko.com/maps/gridmove).
* <br>NL: 2010-02-02: added a fix for IE flickering on divs onmousemove, caused by scroll value when get mouse position.
* <br>GL: 2010-06-15: added a visual control option.
*/
/*!
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function () {
/*jslint browser:true */
/*global window,google */
/* Utility functions use "var funName=function()" syntax to allow use of the */
/* Dean Edwards Packer compression tool (with Shrink variables, without Base62 encode). */
/**
* Converts "thin", "medium", and "thick" to pixel widths
* in an MSIE environment. Not called for other browsers
* because getComputedStyle() returns pixel widths automatically.
* @param {string} widthValue The value of the border width parameter.
*/
var toPixels = function (widthValue) {
var px;
switch (widthValue) {
case "thin":
px = "2px";
break;
case "medium":
px = "4px";
break;
case "thick":
px = "6px";
break;
default:
px = widthValue;
}
return px;
};
/**
* Get the widths of the borders of an HTML element.
*
* @param {Node} h The HTML element.
* @return {Object} The width object {top, bottom left, right}.
*/
var getBorderWidths = function (h) {
var computedStyle;
var bw = {};
if (document.defaultView && document.defaultView.getComputedStyle) {
computedStyle = h.ownerDocument.defaultView.getComputedStyle(h, "");
if (computedStyle) {
// The computed styles are always in pixel units (good!)
bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;
return bw;
}
} else if (document.documentElement.currentStyle) { // MSIE
if (h.currentStyle) {
// The current styles may not be in pixel units so try to convert (bad!)
bw.top = parseInt(toPixels(h.currentStyle.borderTopWidth), 10) || 0;
bw.bottom = parseInt(toPixels(h.currentStyle.borderBottomWidth), 10) || 0;
bw.left = parseInt(toPixels(h.currentStyle.borderLeftWidth), 10) || 0;
bw.right = parseInt(toPixels(h.currentStyle.borderRightWidth), 10) || 0;
return bw;
}
}
// Shouldn't get this far for any modern browser
bw.top = parseInt(h.style["border-top-width"], 10) || 0;
bw.bottom = parseInt(h.style["border-bottom-width"], 10) || 0;
bw.left = parseInt(h.style["border-left-width"], 10) || 0;
bw.right = parseInt(h.style["border-right-width"], 10) || 0;
return bw;
};
// Page scroll values for use by getMousePosition. To prevent flickering on MSIE
// they are calculated only when the document actually scrolls, not every time the
// mouse moves (as they would be if they were calculated inside getMousePosition).
var scroll = {
x: 0,
y: 0
};
var getScrollValue = function (e) {
scroll.x = (typeof document.documentElement.scrollLeft !== "undefined" ? document.documentElement.scrollLeft : document.body.scrollLeft);
scroll.y = (typeof document.documentElement.scrollTop !== "undefined" ? document.documentElement.scrollTop : document.body.scrollTop);
};
getScrollValue();
/**
* Get the position of the mouse relative to the document.
* @param {Event} e The mouse event.
* @return {Object} The position object {left, top}.
*/
var getMousePosition = function (e) {
var posX = 0, posY = 0;
e = e || window.event;
if (typeof e.pageX !== "undefined") {
posX = e.pageX;
posY = e.pageY;
} else if (typeof e.clientX !== "undefined") { // MSIE
posX = e.clientX + scroll.x;
posY = e.clientY + scroll.y;
}
return {
left: posX,
top: posY
};
};
/**
* Get the position of an HTML element relative to the document.
* @param {Node} h The HTML element.
* @return {Object} The position object {left, top}.
*/
var getElementPosition = function (h) {
var posX = h.offsetLeft;
var posY = h.offsetTop;
var parent = h.offsetParent;
// Add offsets for all ancestors in the hierarchy
while (parent !== null) {
// Adjust for scrolling elements which may affect the map position.
//
// See http://www.howtocreate.co.uk/tutorials/javascript/browserspecific
//
// "...make sure that every element [on a Web page] with an overflow
// of anything other than visible also has a position style set to
// something other than the default static..."
if (parent !== document.body && parent !== document.documentElement) {
posX -= parent.scrollLeft;
posY -= parent.scrollTop;
}
// See http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/4cb86c0c1037a5e5
// Example: http://notebook.kulchenko.com/maps/gridmove
var m = parent;
// This is the "normal" way to get offset information:
var moffx = m.offsetLeft;
var moffy = m.offsetTop;
// This covers those cases where a transform is used:
if (!moffx && !moffy && window.getComputedStyle) {
var matrix = document.defaultView.getComputedStyle(m, null).MozTransform ||
document.defaultView.getComputedStyle(m, null).WebkitTransform;
if (matrix) {
if (typeof matrix === "string") {
var parms = matrix.split(",");
moffx += parseInt(parms[4], 10) || 0;
moffy += parseInt(parms[5], 10) || 0;
}
}
}
posX += moffx;
posY += moffy;
parent = parent.offsetParent;
}
return {
left: posX,
top: posY
};
};
/**
* Set the properties of an object to those from another object.
* @param {Object} obj The target object.
* @param {Object} vals The source object.
*/
var setVals = function (obj, vals) {
if (obj && vals) {
for (var x in vals) {
if (vals.hasOwnProperty(x)) {
obj[x] = vals[x];
}
}
}
return obj;
};
/**
* Set the opacity. If op is not passed in, this function just performs an MSIE fix.
* @param {Node} h The HTML element.
* @param {number} op The opacity value (0-1).
*/
var setOpacity = function (h, op) {
if (typeof op !== "undefined") {
h.style.opacity = op;
}
if (typeof h.style.opacity !== "undefined" && h.style.opacity !== "") {
h.style.filter = "alpha(opacity=" + (h.style.opacity * 100) + ")";
}
};
/**
* @name KeyDragZoomOptions
* @class This class represents the optional parameter passed into <code>google.maps.Map.enableKeyDragZoom</code>.
* @property {string} [key="shift"] The hot key to hold down to activate a drag zoom, <code>shift | ctrl | alt</code>.
* NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2,
* it causes a context menu to appear when running on the Macintosh. Also note that the
* <code>alt</code> hot key refers to the Option key on a Macintosh.
* @property {Object} [boxStyle={border: "4px solid #736AFF"}]
* An object literal defining the CSS styles of the zoom box.
* Border widths must be specified in pixel units (or as thin, medium, or thick).
* @property {Object} [veilStyle={backgroundColor: "gray", opacity: 0.25, cursor: "crosshair"}]
* An object literal defining the CSS styles of the veil pane which covers the map when a drag
* zoom is activated. The previous name for this property was <code>paneStyle</code> but the use
* of this name is now deprecated.
* @property {boolean} [noZoom=false] A flag indicating whether to disable zooming after an area is
* selected. Set this to <code>true</code> to allow KeyDragZoom to be used as a simple area
* selection tool.
* @property {boolean} [visualEnabled=false] A flag indicating whether a visual control is to be used.
* @property {string} [visualClass=""] The name of the CSS class defining the styles for the visual
* control. To prevent the visual control from being printed, set this property to the name of
* a class, defined inside a <code>@media print</code> rule, which sets the CSS
* <code>display</code> style to <code>none</code>.
* @property {ControlPosition} [visualPosition=google.maps.ControlPosition.LEFT_TOP]
* The position of the visual control.
* @property {Size} [visualPositionOffset=google.maps.Size(35, 0)] The width and height values
* provided by this property are the offsets (in pixels) from the location at which the control
* would normally be drawn to the desired drawing location.
* @property {number} [visualPositionIndex=null] The index of the visual control.
* The index is for controlling the placement of the control relative to other controls at the
* position given by <code>visualPosition</code>; controls with a lower index are placed first.
* Use a negative value to place the control <i>before</i> any default controls. No index is
* generally required.
* @property {String} [visualSprite="http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png"]
* The URL of the sprite image used for showing the visual control in the on, off, and hot
* (i.e., when the mouse is over the control) states. The three images within the sprite must
* be the same size and arranged in on-hot-off order in a single row with no spaces between images.
* @property {Size} [visualSize=google.maps.Size(20, 20)] The width and height values provided by
* this property are the size (in pixels) of each of the images within <code>visualSprite</code>.
* @property {Object} [visualTips={off: "Turn on drag zoom mode", on: "Turn off drag zoom mode"}]
* An object literal defining the help tips that appear when
* the mouse moves over the visual control. The <code>off</code> property is the tip to be shown
* when the control is off and the <code>on</code> property is the tip to be shown when the
* control is on.
*/
/**
* @name DragZoom
* @class This class represents a drag zoom object for a map. The object is activated by holding down the hot key
* or by turning on the visual control.
* This object is created when <code>google.maps.Map.enableKeyDragZoom</code> is called; it cannot be created directly.
* Use <code>google.maps.Map.getDragZoomObject</code> to gain access to this object in order to attach event listeners.
* @param {Map} map The map to which the DragZoom object is to be attached.
* @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters.
*/
function DragZoom(map, opt_zoomOpts) {
var me = this;
var ov = new google.maps.OverlayView();
ov.onAdd = function () {
me.init_(map, opt_zoomOpts);
};
ov.draw = function () {
};
ov.onRemove = function () {
};
ov.setMap(map);
this.prjov_ = ov;
}
/**
* Initialize the tool.
* @param {Map} map The map to which the DragZoom object is to be attached.
* @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters.
*/
DragZoom.prototype.init_ = function (map, opt_zoomOpts) {
var i;
var me = this;
this.map_ = map;
opt_zoomOpts = opt_zoomOpts || {};
this.key_ = opt_zoomOpts.key || "shift";
this.key_ = this.key_.toLowerCase();
this.borderWidths_ = getBorderWidths(this.map_.getDiv());
this.veilDiv_ = [];
for (i = 0; i < 4; i++) {
this.veilDiv_[i] = document.createElement("div");
// Prevents selection of other elements on the webpage
// when a drag zoom operation is in progress:
this.veilDiv_[i].onselectstart = function () {
return false;
};
// Apply default style values for the veil:
setVals(this.veilDiv_[i].style, {
backgroundColor: "gray",
opacity: 0.25,
cursor: "crosshair"
});
// Apply style values specified in veilStyle parameter:
setVals(this.veilDiv_[i].style, opt_zoomOpts.paneStyle); // Old option name was "paneStyle"
setVals(this.veilDiv_[i].style, opt_zoomOpts.veilStyle); // New name is "veilStyle"
// Apply mandatory style values:
setVals(this.veilDiv_[i].style, {
position: "absolute",
overflow: "hidden",
display: "none"
});
// Workaround for Firefox Shift-Click problem:
if (this.key_ === "shift") {
this.veilDiv_[i].style.MozUserSelect = "none";
}
setOpacity(this.veilDiv_[i]);
// An IE fix: If the background is transparent it cannot capture mousedown
// events, so if it is, change the background to white with 0 opacity.
if (this.veilDiv_[i].style.backgroundColor === "transparent") {
this.veilDiv_[i].style.backgroundColor = "white";
setOpacity(this.veilDiv_[i], 0);
}
this.map_.getDiv().appendChild(this.veilDiv_[i]);
}
this.noZoom_ = opt_zoomOpts.noZoom || false;
this.visualEnabled_ = opt_zoomOpts.visualEnabled || false;
this.visualClass_ = opt_zoomOpts.visualClass || "";
this.visualPosition_ = opt_zoomOpts.visualPosition || google.maps.ControlPosition.LEFT_TOP;
this.visualPositionOffset_ = opt_zoomOpts.visualPositionOffset || new google.maps.Size(35, 0);
this.visualPositionIndex_ = opt_zoomOpts.visualPositionIndex || null;
this.visualSprite_ = opt_zoomOpts.visualSprite || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png";
this.visualSize_ = opt_zoomOpts.visualSize || new google.maps.Size(20, 20);
this.visualTips_ = opt_zoomOpts.visualTips || {};
this.visualTips_.off = this.visualTips_.off || "Turn on drag zoom mode";
this.visualTips_.on = this.visualTips_.on || "Turn off drag zoom mode";
this.boxDiv_ = document.createElement("div");
// Apply default style values for the zoom box:
setVals(this.boxDiv_.style, {
border: "4px solid #736AFF"
});
// Apply style values specified in boxStyle parameter:
setVals(this.boxDiv_.style, opt_zoomOpts.boxStyle);
// Apply mandatory style values:
setVals(this.boxDiv_.style, {
position: "absolute",
display: "none"
});
setOpacity(this.boxDiv_);
this.map_.getDiv().appendChild(this.boxDiv_);
this.boxBorderWidths_ = getBorderWidths(this.boxDiv_);
this.listeners_ = [
google.maps.event.addDomListener(document, "keydown", function (e) {
me.onKeyDown_(e);
}),
google.maps.event.addDomListener(document, "keyup", function (e) {
me.onKeyUp_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[0], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[1], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[2], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[3], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(document, "mousedown", function (e) {
me.onMouseDownDocument_(e);
}),
google.maps.event.addDomListener(document, "mousemove", function (e) {
me.onMouseMove_(e);
}),
google.maps.event.addDomListener(document, "mouseup", function (e) {
me.onMouseUp_(e);
}),
google.maps.event.addDomListener(window, "scroll", getScrollValue)
];
this.hotKeyDown_ = false;
this.mouseDown_ = false;
this.dragging_ = false;
this.startPt_ = null;
this.endPt_ = null;
this.mapWidth_ = null;
this.mapHeight_ = null;
this.mousePosn_ = null;
this.mapPosn_ = null;
if (this.visualEnabled_) {
this.buttonDiv_ = this.initControl_(this.visualPositionOffset_);
if (this.visualPositionIndex_ !== null) {
this.buttonDiv_.index = this.visualPositionIndex_;
}
this.map_.controls[this.visualPosition_].push(this.buttonDiv_);
this.controlIndex_ = this.map_.controls[this.visualPosition_].length - 1;
}
};
/**
* Initializes the visual control and returns its DOM element.
* @param {Size} offset The offset of the control from its normal position.
* @return {Node} The DOM element containing the visual control.
*/
DragZoom.prototype.initControl_ = function (offset) {
var control;
var image;
var me = this;
control = document.createElement("div");
control.className = this.visualClass_;
control.style.position = "relative";
control.style.overflow = "hidden";
control.style.height = this.visualSize_.height + "px";
control.style.width = this.visualSize_.width + "px";
control.title = this.visualTips_.off;
image = document.createElement("img");
image.src = this.visualSprite_;
image.style.position = "absolute";
image.style.left = -(this.visualSize_.width * 2) + "px";
image.style.top = 0 + "px";
control.appendChild(image);
control.onclick = function (e) {
me.hotKeyDown_ = !me.hotKeyDown_;
if (me.hotKeyDown_) {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px";
me.buttonDiv_.title = me.visualTips_.on;
me.activatedByControl_ = true;
google.maps.event.trigger(me, "activate");
} else {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px";
me.buttonDiv_.title = me.visualTips_.off;
google.maps.event.trigger(me, "deactivate");
}
me.onMouseMove_(e); // Updates the veil
};
control.onmouseover = function () {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 1) + "px";
};
control.onmouseout = function () {
if (me.hotKeyDown_) {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px";
me.buttonDiv_.title = me.visualTips_.on;
} else {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px";
me.buttonDiv_.title = me.visualTips_.off;
}
};
control.ondragstart = function () {
return false;
};
setVals(control.style, {
cursor: "pointer",
marginTop: offset.height + "px",
marginLeft: offset.width + "px"
});
return control;
};
/**
* Returns <code>true</code> if the hot key is being pressed when an event occurs.
* @param {Event} e The keyboard event.
* @return {boolean} Flag indicating whether the hot key is down.
*/
DragZoom.prototype.isHotKeyDown_ = function (e) {
var isHot;
e = e || window.event;
isHot = (e.shiftKey && this.key_ === "shift") || (e.altKey && this.key_ === "alt") || (e.ctrlKey && this.key_ === "ctrl");
if (!isHot) {
// Need to look at keyCode for Opera because it
// doesn't set the shiftKey, altKey, ctrlKey properties
// unless a non-modifier event is being reported.
//
// See http://cross-browser.com/x/examples/shift_mode.php
// Also see http://unixpapa.com/js/key.html
switch (e.keyCode) {
case 16:
if (this.key_ === "shift") {
isHot = true;
}
break;
case 17:
if (this.key_ === "ctrl") {
isHot = true;
}
break;
case 18:
if (this.key_ === "alt") {
isHot = true;
}
break;
}
}
return isHot;
};
/**
* Returns <code>true</code> if the mouse is on top of the map div.
* The position is captured in onMouseMove_.
* @return {boolean}
*/
DragZoom.prototype.isMouseOnMap_ = function () {
var mousePosn = this.mousePosn_;
if (mousePosn) {
var mapPosn = this.mapPosn_;
var mapDiv = this.map_.getDiv();
return mousePosn.left > mapPosn.left && mousePosn.left < (mapPosn.left + mapDiv.offsetWidth) &&
mousePosn.top > mapPosn.top && mousePosn.top < (mapPosn.top + mapDiv.offsetHeight);
} else {
// if user never moved mouse
return false;
}
};
/**
* Show the veil if the hot key is down and the mouse is over the map,
* otherwise hide the veil.
*/
DragZoom.prototype.setVeilVisibility_ = function () {
var i;
if (this.map_ && this.hotKeyDown_ && this.isMouseOnMap_()) {
var mapDiv = this.map_.getDiv();
this.mapWidth_ = mapDiv.offsetWidth - (this.borderWidths_.left + this.borderWidths_.right);
this.mapHeight_ = mapDiv.offsetHeight - (this.borderWidths_.top + this.borderWidths_.bottom);
if (this.activatedByControl_) { // Veil covers entire map (except control)
var left = parseInt(this.buttonDiv_.style.left, 10) + this.visualPositionOffset_.width;
var top = parseInt(this.buttonDiv_.style.top, 10) + this.visualPositionOffset_.height;
var width = this.visualSize_.width;
var height = this.visualSize_.height;
// Left veil rectangle:
this.veilDiv_[0].style.top = "0px";
this.veilDiv_[0].style.left = "0px";
this.veilDiv_[0].style.width = left + "px";
this.veilDiv_[0].style.height = this.mapHeight_ + "px";
// Right veil rectangle:
this.veilDiv_[1].style.top = "0px";
this.veilDiv_[1].style.left = (left + width) + "px";
this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px";
this.veilDiv_[1].style.height = this.mapHeight_ + "px";
// Top veil rectangle:
this.veilDiv_[2].style.top = "0px";
this.veilDiv_[2].style.left = left + "px";
this.veilDiv_[2].style.width = width + "px";
this.veilDiv_[2].style.height = top + "px";
// Bottom veil rectangle:
this.veilDiv_[3].style.top = (top + height) + "px";
this.veilDiv_[3].style.left = left + "px";
this.veilDiv_[3].style.width = width + "px";
this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px";
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "block";
}
} else {
this.veilDiv_[0].style.left = "0px";
this.veilDiv_[0].style.top = "0px";
this.veilDiv_[0].style.width = this.mapWidth_ + "px";
this.veilDiv_[0].style.height = this.mapHeight_ + "px";
for (i = 1; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.width = "0px";
this.veilDiv_[i].style.height = "0px";
}
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "block";
}
}
} else {
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "none";
}
}
};
/**
* Handle key down. Show the veil if the hot key has been pressed.
* @param {Event} e The keyboard event.
*/
DragZoom.prototype.onKeyDown_ = function (e) {
if (this.map_ && !this.hotKeyDown_ && this.isHotKeyDown_(e)) {
this.mapPosn_ = getElementPosition(this.map_.getDiv());
this.hotKeyDown_ = true;
this.activatedByControl_ = false;
this.setVeilVisibility_();
/**
* This event is fired when the hot key is pressed.
* @name DragZoom#activate
* @event
*/
google.maps.event.trigger(this, "activate");
}
};
/**
* Get the <code>google.maps.Point</code> of the mouse position.
* @param {Event} e The mouse event.
* @return {Point} The mouse position.
*/
DragZoom.prototype.getMousePoint_ = function (e) {
var mousePosn = getMousePosition(e);
var p = new google.maps.Point();
p.x = mousePosn.left - this.mapPosn_.left - this.borderWidths_.left;
p.y = mousePosn.top - this.mapPosn_.top - this.borderWidths_.top;
p.x = Math.min(p.x, this.mapWidth_);
p.y = Math.min(p.y, this.mapHeight_);
p.x = Math.max(p.x, 0);
p.y = Math.max(p.y, 0);
return p;
};
/**
* Handle mouse down.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseDown_ = function (e) {
if (this.map_ && this.hotKeyDown_) {
this.mapPosn_ = getElementPosition(this.map_.getDiv());
this.dragging_ = true;
this.startPt_ = this.endPt_ = this.getMousePoint_(e);
this.boxDiv_.style.width = this.boxDiv_.style.height = "0px";
var prj = this.prjov_.getProjection();
var latlng = prj.fromContainerPixelToLatLng(this.startPt_);
/**
* This event is fired when the drag operation begins.
* The parameter passed is the geographic position of the starting point.
* @name DragZoom#dragstart
* @param {LatLng} latlng The geographic position of the starting point.
* @event
*/
google.maps.event.trigger(this, "dragstart", latlng);
}
};
/**
* Handle mouse down at the document level.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseDownDocument_ = function (e) {
this.mouseDown_ = true;
};
/**
* Handle mouse move.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseMove_ = function (e) {
this.mousePosn_ = getMousePosition(e);
if (this.dragging_) {
this.endPt_ = this.getMousePoint_(e);
var left = Math.min(this.startPt_.x, this.endPt_.x);
var top = Math.min(this.startPt_.y, this.endPt_.y);
var width = Math.abs(this.startPt_.x - this.endPt_.x);
var height = Math.abs(this.startPt_.y - this.endPt_.y);
// For benefit of MSIE 7/8 ensure following values are not negative:
var boxWidth = Math.max(0, width - (this.boxBorderWidths_.left + this.boxBorderWidths_.right));
var boxHeight = Math.max(0, height - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom));
// Left veil rectangle:
this.veilDiv_[0].style.top = "0px";
this.veilDiv_[0].style.left = "0px";
this.veilDiv_[0].style.width = left + "px";
this.veilDiv_[0].style.height = this.mapHeight_ + "px";
// Right veil rectangle:
this.veilDiv_[1].style.top = "0px";
this.veilDiv_[1].style.left = (left + width) + "px";
this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px";
this.veilDiv_[1].style.height = this.mapHeight_ + "px";
// Top veil rectangle:
this.veilDiv_[2].style.top = "0px";
this.veilDiv_[2].style.left = left + "px";
this.veilDiv_[2].style.width = width + "px";
this.veilDiv_[2].style.height = top + "px";
// Bottom veil rectangle:
this.veilDiv_[3].style.top = (top + height) + "px";
this.veilDiv_[3].style.left = left + "px";
this.veilDiv_[3].style.width = width + "px";
this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px";
// Selection rectangle:
this.boxDiv_.style.top = top + "px";
this.boxDiv_.style.left = left + "px";
this.boxDiv_.style.width = boxWidth + "px";
this.boxDiv_.style.height = boxHeight + "px";
this.boxDiv_.style.display = "block";
/**
* This event is fired repeatedly while the user drags a box across the area of interest.
* The southwest and northeast point are passed as parameters of type <code>google.maps.Point</code>
* (for performance reasons), relative to the map container. Also passed is the projection object
* so that the event listener, if necessary, can convert the pixel positions to geographic
* coordinates using <code>google.maps.MapCanvasProjection.fromContainerPixelToLatLng</code>.
* @name DragZoom#drag
* @param {Point} southwestPixel The southwest point of the selection area.
* @param {Point} northeastPixel The northeast point of the selection area.
* @param {MapCanvasProjection} prj The projection object.
* @event
*/
google.maps.event.trigger(this, "drag", new google.maps.Point(left, top + height), new google.maps.Point(left + width, top), this.prjov_.getProjection());
} else if (!this.mouseDown_) {
this.mapPosn_ = getElementPosition(this.map_.getDiv());
this.setVeilVisibility_();
}
};
/**
* Handle mouse up.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseUp_ = function (e) {
var z;
var me = this;
this.mouseDown_ = false;
if (this.dragging_) {
if ((this.getMousePoint_(e).x === this.startPt_.x) && (this.getMousePoint_(e).y === this.startPt_.y)) {
this.onKeyUp_(e); // Cancel event
return;
}
var left = Math.min(this.startPt_.x, this.endPt_.x);
var top = Math.min(this.startPt_.y, this.endPt_.y);
var width = Math.abs(this.startPt_.x - this.endPt_.x);
var height = Math.abs(this.startPt_.y - this.endPt_.y);
// Google Maps API bug: setCenter() doesn't work as expected if the map has a
// border on the left or top. The code here includes a workaround for this problem.
var kGoogleCenteringBug = true;
if (kGoogleCenteringBug) {
left += this.borderWidths_.left;
top += this.borderWidths_.top;
}
var prj = this.prjov_.getProjection();
var sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height));
var ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top));
var bnds = new google.maps.LatLngBounds(sw, ne);
if (this.noZoom_) {
this.boxDiv_.style.display = "none";
} else {
// Sometimes fitBounds causes a zoom OUT, so restore original zoom level if this happens.
z = this.map_.getZoom();
this.map_.fitBounds(bnds);
if (this.map_.getZoom() < z) {
this.map_.setZoom(z);
}
// Redraw box after zoom:
var swPt = prj.fromLatLngToContainerPixel(sw);
var nePt = prj.fromLatLngToContainerPixel(ne);
if (kGoogleCenteringBug) {
swPt.x -= this.borderWidths_.left;
swPt.y -= this.borderWidths_.top;
nePt.x -= this.borderWidths_.left;
nePt.y -= this.borderWidths_.top;
}
this.boxDiv_.style.left = swPt.x + "px";
this.boxDiv_.style.top = nePt.y + "px";
this.boxDiv_.style.width = (Math.abs(nePt.x - swPt.x) - (this.boxBorderWidths_.left + this.boxBorderWidths_.right)) + "px";
this.boxDiv_.style.height = (Math.abs(nePt.y - swPt.y) - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom)) + "px";
// Hide box asynchronously after 1 second:
setTimeout(function () {
me.boxDiv_.style.display = "none";
}, 1000);
}
this.dragging_ = false;
this.onMouseMove_(e); // Updates the veil
/**
* This event is fired when the drag operation ends.
* The parameter passed is the geographic bounds of the selected area.
* Note that this event is <i>not</i> fired if the hot key is released before the drag operation ends.
* @name DragZoom#dragend
* @param {LatLngBounds} bnds The geographic bounds of the selected area.
* @event
*/
google.maps.event.trigger(this, "dragend", bnds);
// if the hot key isn't down, the drag zoom must have been activated by turning
// on the visual control. In this case, finish up by simulating a key up event.
if (!this.isHotKeyDown_(e)) {
this.onKeyUp_(e);
}
}
};
/**
* Handle key up.
* @param {Event} e The keyboard event.
*/
DragZoom.prototype.onKeyUp_ = function (e) {
var i;
var left, top, width, height, prj, sw, ne;
var bnds = null;
if (this.map_ && this.hotKeyDown_) {
this.hotKeyDown_ = false;
if (this.dragging_) {
this.boxDiv_.style.display = "none";
this.dragging_ = false;
// Calculate the bounds when drag zoom was cancelled
left = Math.min(this.startPt_.x, this.endPt_.x);
top = Math.min(this.startPt_.y, this.endPt_.y);
width = Math.abs(this.startPt_.x - this.endPt_.x);
height = Math.abs(this.startPt_.y - this.endPt_.y);
prj = this.prjov_.getProjection();
sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height));
ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top));
bnds = new google.maps.LatLngBounds(sw, ne);
}
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "none";
}
if (this.visualEnabled_) {
this.buttonDiv_.firstChild.style.left = -(this.visualSize_.width * 2) + "px";
this.buttonDiv_.title = this.visualTips_.off;
this.buttonDiv_.style.display = "";
}
/**
* This event is fired when the hot key is released.
* The parameter passed is the geographic bounds of the selected area immediately
* before the hot key was released.
* @name DragZoom#deactivate
* @param {LatLngBounds} bnds The geographic bounds of the selected area immediately
* before the hot key was released.
* @event
*/
google.maps.event.trigger(this, "deactivate", bnds);
}
};
/**
* @name google.maps.Map
* @class These are new methods added to the Google Maps JavaScript API V3's
* <a href="http://code.google.com/apis/maps/documentation/javascript/reference.html#Map">Map</a>
* class.
*/
/**
* Enables drag zoom. The user can zoom to an area of interest by holding down the hot key
* <code>(shift | ctrl | alt )</code> while dragging a box around the area or by turning
* on the visual control then dragging a box around the area.
* @param {KeyDragZoomOptions} opt_zoomOpts The optional parameters.
*/
google.maps.Map.prototype.enableKeyDragZoom = function (opt_zoomOpts) {
this.dragZoom_ = new DragZoom(this, opt_zoomOpts);
};
/**
* Disables drag zoom.
*/
google.maps.Map.prototype.disableKeyDragZoom = function () {
var i;
var d = this.dragZoom_;
if (d) {
for (i = 0; i < d.listeners_.length; ++i) {
google.maps.event.removeListener(d.listeners_[i]);
}
this.getDiv().removeChild(d.boxDiv_);
for (i = 0; i < d.veilDiv_.length; i++) {
this.getDiv().removeChild(d.veilDiv_[i]);
}
if (d.visualEnabled_) {
// Remove the custom control:
this.controls[d.visualPosition_].removeAt(d.controlIndex_);
}
d.prjov_.setMap(null);
this.dragZoom_ = null;
}
};
/**
* Returns <code>true</code> if the drag zoom feature has been enabled.
* @return {boolean}
*/
google.maps.Map.prototype.keyDragZoomEnabled = function () {
return this.dragZoom_ !== null;
};
/**
* Returns the DragZoom object which is created when <code>google.maps.Map.enableKeyDragZoom</code> is called.
* With this object you can use <code>google.maps.event.addListener</code> to attach event listeners
* for the "activate", "deactivate", "dragstart", "drag", and "dragend" events.
* @return {DragZoom}
*/
google.maps.Map.prototype.getDragZoomObject = function () {
return this.dragZoom_;
};
})();
/**
* @name MarkerClustererPlus for Google Maps V3
* @version 2.1.1 [November 4, 2013]
* @author Gary Little
* @fileoverview
* The library creates and manages per-zoom-level clusters for large amounts of markers.
* <p>
* This is an enhanced V3 implementation of the
* <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/"
* >V2 MarkerClusterer</a> by Xiaoxi Wu. It is based on the
* <a href="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/"
* >V3 MarkerClusterer</a> port by Luke Mahe. MarkerClustererPlus was created by Gary Little.
* <p>
* v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It
* adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>batchSizeIE</code>,
* and <code>calculator</code> properties as well as support for four more events. It also allows
* greater control over the styling of the text that appears on the cluster marker. The
* documentation has been significantly improved and the overall code has been simplified and
* polished. Very large numbers of markers can now be managed without causing Javascript timeout
* errors on Internet Explorer. Note that the name of the <code>clusterclick</code> event has been
* deprecated. The new name is <code>click</code>, so please change your application code now.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @name ClusterIconStyle
* @class This class represents the object for values in the <code>styles</code> array passed
* to the {@link MarkerClusterer} constructor. The element in this array that is used to
* style the cluster icon is determined by calling the <code>calculator</code> function.
*
* @property {string} url The URL of the cluster icon image file. Required.
* @property {number} height The display height (in pixels) of the cluster icon. Required.
* @property {number} width The display width (in pixels) of the cluster icon. Required.
* @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to
* where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code>
* where <code>yoffset</code> increases as you go down from center and <code>xoffset</code>
* increases to the right of center. The default is <code>[0, 0]</code>.
* @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the
* spot on the cluster icon that is to be aligned with the cluster position. The format is
* <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and
* <code>xoffset</code> increases to the right of the top-left corner of the icon. The default
* anchor position is the center of the cluster icon.
* @property {string} [textColor="black"] The color of the label text shown on the
* cluster icon.
* @property {number} [textSize=11] The size (in pixels) of the label text shown on the
* cluster icon.
* @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code>
* property for the label text shown on the cluster icon.
* @property {string} [backgroundPosition="0 0"] The position of the cluster icon image
* within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code>
* (the same format as for the CSS <code>background-position</code> property). You must set
* this property appropriately when the image defined by <code>url</code> represents a sprite
* containing multiple images. Note that the position <i>must</i> be specified in px units.
*/
/**
* @name ClusterIconInfo
* @class This class is an object containing general information about a cluster icon. This is
* the object that a <code>calculator</code> function returns.
*
* @property {string} text The text of the label to be shown on the cluster icon.
* @property {number} index The index plus 1 of the element in the <code>styles</code>
* array to be used to style the cluster icon.
* @property {string} title The tooltip to display when the mouse moves over the cluster icon.
* If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the
* value of the <code>title</code> property passed to the MarkerClusterer.
*/
/**
* A cluster icon.
*
* @constructor
* @extends google.maps.OverlayView
* @param {Cluster} cluster The cluster with which the icon is to be associated.
* @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons
* to use for various cluster sizes.
* @private
*/
function ClusterIcon(cluster, styles) {
cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);
this.cluster_ = cluster;
this.className_ = cluster.getMarkerClusterer().getClusterClass();
this.styles_ = styles;
this.center_ = null;
this.div_ = null;
this.sums_ = null;
this.visible_ = false;
this.setMap(cluster.getMap()); // Note: this causes onAdd to be called
}
/**
* Adds the icon to the DOM.
*/
ClusterIcon.prototype.onAdd = function () {
var cClusterIcon = this;
var cMouseDownInCluster;
var cDraggingMapByCluster;
this.div_ = document.createElement("div");
this.div_.className = this.className_;
if (this.visible_) {
this.show();
}
this.getPanes().overlayMouseTarget.appendChild(this.div_);
// Fix for Issue 157
this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), "bounds_changed", function () {
cDraggingMapByCluster = cMouseDownInCluster;
});
google.maps.event.addDomListener(this.div_, "mousedown", function () {
cMouseDownInCluster = true;
cDraggingMapByCluster = false;
});
google.maps.event.addDomListener(this.div_, "click", function (e) {
cMouseDownInCluster = false;
if (!cDraggingMapByCluster) {
var theBounds;
var mz;
var mc = cClusterIcon.cluster_.getMarkerClusterer();
/**
* This event is fired when a cluster marker is clicked.
* @name MarkerClusterer#click
* @param {Cluster} c The cluster that was clicked.
* @event
*/
google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name
// The default click handler follows. Disable it by setting
// the zoomOnClick property to false.
if (mc.getZoomOnClick()) {
// Zoom into the cluster.
mz = mc.getMaxZoom();
theBounds = cClusterIcon.cluster_.getBounds();
mc.getMap().fitBounds(theBounds);
// There is a fix for Issue 170 here:
setTimeout(function () {
mc.getMap().fitBounds(theBounds);
// Don't zoom beyond the max zoom level
if (mz !== null && (mc.getMap().getZoom() > mz)) {
mc.getMap().setZoom(mz + 1);
}
}, 100);
}
// Prevent event propagation to the map:
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
}
});
google.maps.event.addDomListener(this.div_, "mouseover", function () {
var mc = cClusterIcon.cluster_.getMarkerClusterer();
/**
* This event is fired when the mouse moves over a cluster marker.
* @name MarkerClusterer#mouseover
* @param {Cluster} c The cluster that the mouse moved over.
* @event
*/
google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_);
});
google.maps.event.addDomListener(this.div_, "mouseout", function () {
var mc = cClusterIcon.cluster_.getMarkerClusterer();
/**
* This event is fired when the mouse moves out of a cluster marker.
* @name MarkerClusterer#mouseout
* @param {Cluster} c The cluster that the mouse moved out of.
* @event
*/
google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_);
});
};
/**
* Removes the icon from the DOM.
*/
ClusterIcon.prototype.onRemove = function () {
if (this.div_ && this.div_.parentNode) {
this.hide();
google.maps.event.removeListener(this.boundsChangedListener_);
google.maps.event.clearInstanceListeners(this.div_);
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
/**
* Draws the icon.
*/
ClusterIcon.prototype.draw = function () {
if (this.visible_) {
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.top = pos.y + "px";
this.div_.style.left = pos.x + "px";
}
};
/**
* Hides the icon.
*/
ClusterIcon.prototype.hide = function () {
if (this.div_) {
this.div_.style.display = "none";
}
this.visible_ = false;
};
/**
* Positions and shows the icon.
*/
ClusterIcon.prototype.show = function () {
if (this.div_) {
var img = "";
// NOTE: values must be specified in px units
var bp = this.backgroundPosition_.split(" ");
var spriteH = parseInt(bp[0].trim(), 10);
var spriteV = parseInt(bp[1].trim(), 10);
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.cssText = this.createCss(pos);
img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; ";
if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) {
img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " +
((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);";
}
img += "'>";
this.div_.innerHTML = img + "<div style='" +
"position: absolute;" +
"top: " + this.anchorText_[0] + "px;" +
"left: " + this.anchorText_[1] + "px;" +
"color: " + this.textColor_ + ";" +
"font-size: " + this.textSize_ + "px;" +
"font-family: " + this.fontFamily_ + ";" +
"font-weight: " + this.fontWeight_ + ";" +
"font-style: " + this.fontStyle_ + ";" +
"text-decoration: " + this.textDecoration_ + ";" +
"text-align: center;" +
"width: " + this.width_ + "px;" +
"line-height:" + this.height_ + "px;" +
"'>" + this.sums_.text + "</div>";
if (typeof this.sums_.title === "undefined" || this.sums_.title === "") {
this.div_.title = this.cluster_.getMarkerClusterer().getTitle();
} else {
this.div_.title = this.sums_.title;
}
this.div_.style.display = "";
}
this.visible_ = true;
};
/**
* Sets the icon styles to the appropriate element in the styles array.
*
* @param {ClusterIconInfo} sums The icon label text and styles index.
*/
ClusterIcon.prototype.useStyle = function (sums) {
this.sums_ = sums;
var index = Math.max(0, sums.index - 1);
index = Math.min(this.styles_.length - 1, index);
var style = this.styles_[index];
this.url_ = style.url;
this.height_ = style.height;
this.width_ = style.width;
this.anchorText_ = style.anchorText || [0, 0];
this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)];
this.textColor_ = style.textColor || "black";
this.textSize_ = style.textSize || 11;
this.textDecoration_ = style.textDecoration || "none";
this.fontWeight_ = style.fontWeight || "bold";
this.fontStyle_ = style.fontStyle || "normal";
this.fontFamily_ = style.fontFamily || "Arial,sans-serif";
this.backgroundPosition_ = style.backgroundPosition || "0 0";
};
/**
* Sets the position at which to center the icon.
*
* @param {google.maps.LatLng} center The latlng to set as the center.
*/
ClusterIcon.prototype.setCenter = function (center) {
this.center_ = center;
};
/**
* Creates the cssText style parameter based on the position of the icon.
*
* @param {google.maps.Point} pos The position of the icon.
* @return {string} The CSS style text.
*/
ClusterIcon.prototype.createCss = function (pos) {
var style = [];
style.push("cursor: pointer;");
style.push("position: absolute; top: " + pos.y + "px; left: " + pos.x + "px;");
style.push("width: " + this.width_ + "px; height: " + this.height_ + "px;");
return style.join("");
};
/**
* Returns the position at which to place the DIV depending on the latlng.
*
* @param {google.maps.LatLng} latlng The position in latlng.
* @return {google.maps.Point} The position in pixels.
*/
ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) {
var pos = this.getProjection().fromLatLngToDivPixel(latlng);
pos.x -= this.anchorIcon_[1];
pos.y -= this.anchorIcon_[0];
pos.x = parseInt(pos.x, 10);
pos.y = parseInt(pos.y, 10);
return pos;
};
/**
* Creates a single cluster that manages a group of proximate markers.
* Used internally, do not call this constructor directly.
* @constructor
* @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this
* cluster is associated.
*/
function Cluster(mc) {
this.markerClusterer_ = mc;
this.map_ = mc.getMap();
this.gridSize_ = mc.getGridSize();
this.minClusterSize_ = mc.getMinimumClusterSize();
this.averageCenter_ = mc.getAverageCenter();
this.markers_ = [];
this.center_ = null;
this.bounds_ = null;
this.clusterIcon_ = new ClusterIcon(this, mc.getStyles());
}
/**
* Returns the number of markers managed by the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {number} The number of markers in the cluster.
*/
Cluster.prototype.getSize = function () {
return this.markers_.length;
};
/**
* Returns the array of markers managed by the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {Array} The array of markers in the cluster.
*/
Cluster.prototype.getMarkers = function () {
return this.markers_;
};
/**
* Returns the center of the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {google.maps.LatLng} The center of the cluster.
*/
Cluster.prototype.getCenter = function () {
return this.center_;
};
/**
* Returns the map with which the cluster is associated.
*
* @return {google.maps.Map} The map.
* @ignore
*/
Cluster.prototype.getMap = function () {
return this.map_;
};
/**
* Returns the <code>MarkerClusterer</code> object with which the cluster is associated.
*
* @return {MarkerClusterer} The associated marker clusterer.
* @ignore
*/
Cluster.prototype.getMarkerClusterer = function () {
return this.markerClusterer_;
};
/**
* Returns the bounds of the cluster.
*
* @return {google.maps.LatLngBounds} the cluster bounds.
* @ignore
*/
Cluster.prototype.getBounds = function () {
var i;
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
var markers = this.getMarkers();
for (i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
return bounds;
};
/**
* Removes the cluster from the map.
*
* @ignore
*/
Cluster.prototype.remove = function () {
this.clusterIcon_.setMap(null);
this.markers_ = [];
delete this.markers_;
};
/**
* Adds a marker to the cluster.
*
* @param {google.maps.Marker} marker The marker to be added.
* @return {boolean} True if the marker was added.
* @ignore
*/
Cluster.prototype.addMarker = function (marker) {
var i;
var mCount;
var mz;
if (this.isMarkerAlreadyAdded_(marker)) {
return false;
}
if (!this.center_) {
this.center_ = marker.getPosition();
this.calculateBounds_();
} else {
if (this.averageCenter_) {
var l = this.markers_.length + 1;
var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;
var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;
this.center_ = new google.maps.LatLng(lat, lng);
this.calculateBounds_();
}
}
marker.isAdded = true;
this.markers_.push(marker);
mCount = this.markers_.length;
mz = this.markerClusterer_.getMaxZoom();
if (mz !== null && this.map_.getZoom() > mz) {
// Zoomed in past max zoom, so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount < this.minClusterSize_) {
// Min cluster size not reached so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount === this.minClusterSize_) {
// Hide the markers that were showing.
for (i = 0; i < mCount; i++) {
this.markers_[i].setMap(null);
}
} else {
marker.setMap(null);
}
this.updateIcon_();
return true;
};
/**
* Determines if a marker lies within the cluster's bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker lies in the bounds.
* @ignore
*/
Cluster.prototype.isMarkerInClusterBounds = function (marker) {
return this.bounds_.contains(marker.getPosition());
};
/**
* Calculates the extended bounds of the cluster with the grid.
*/
Cluster.prototype.calculateBounds_ = function () {
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);
};
/**
* Updates the cluster icon.
*/
Cluster.prototype.updateIcon_ = function () {
var mCount = this.markers_.length;
var mz = this.markerClusterer_.getMaxZoom();
if (mz !== null && this.map_.getZoom() > mz) {
this.clusterIcon_.hide();
return;
}
if (mCount < this.minClusterSize_) {
// Min cluster size not yet reached.
this.clusterIcon_.hide();
return;
}
var numStyles = this.markerClusterer_.getStyles().length;
var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);
this.clusterIcon_.setCenter(this.center_);
this.clusterIcon_.useStyle(sums);
this.clusterIcon_.show();
};
/**
* Determines if a marker has already been added to the cluster.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker has already been added.
*/
Cluster.prototype.isMarkerAlreadyAdded_ = function (marker) {
var i;
if (this.markers_.indexOf) {
return this.markers_.indexOf(marker) !== -1;
} else {
for (i = 0; i < this.markers_.length; i++) {
if (marker === this.markers_[i]) {
return true;
}
}
}
return false;
};
/**
* @name MarkerClustererOptions
* @class This class represents the optional parameter passed to
* the {@link MarkerClusterer} constructor.
* @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square.
* @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or
* <code>null</code> if clustering is to be enabled at all zoom levels.
* @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is
* clicked. You may want to set this to <code>false</code> if you have installed a handler
* for the <code>click</code> event and it deals with zooming on its own.
* @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be
* the average position of all markers in the cluster. If set to <code>false</code>, the
* cluster marker is positioned at the location of the first marker added to the cluster.
* @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster
* before the markers are hidden and a cluster marker appears.
* @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You
* may want to set this to <code>true</code> to ensure that hidden markers are not included
* in the marker count that appears on a cluster marker (this count is the value of the
* <code>text</code> property of the result returned by the default <code>calculator</code>).
* If set to <code>true</code> and you change the visibility of a marker being clustered, be
* sure to also call <code>MarkerClusterer.repaint()</code>.
* @property {string} [title=""] The tooltip to display when the mouse moves over a cluster
* marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a
* different tooltip for each cluster marker.)
* @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine
* the text to be displayed on a cluster marker and the index indicating which style to use
* for the cluster marker. The input parameters for the function are (1) the array of markers
* represented by a cluster marker and (2) the number of cluster icon styles. It returns a
* {@link ClusterIconInfo} object. The default <code>calculator</code> returns a
* <code>text</code> property which is the number of markers in the cluster and an
* <code>index</code> property which is one higher than the lowest integer such that
* <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles
* array, whichever is less. The <code>styles</code> array element used has an index of
* <code>index</code> minus 1. For example, the default <code>calculator</code> returns a
* <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code>
* for a cluster icon representing 125 markers so the element used in the <code>styles</code>
* array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code>
* property that contains the text of the tooltip to be used for the cluster marker. If
* <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code>
* property for the MarkerClusterer.
* @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles
* for the cluster markers. Use this class to define CSS styles that are not set up by the code
* that processes the <code>styles</code> array.
* @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles
* of the cluster markers to be used. The element to be used to style a given cluster marker
* is determined by the function defined by the <code>calculator</code> property.
* The default is an array of {@link ClusterIconStyle} elements whose properties are derived
* from the values for <code>imagePath</code>, <code>imageExtension</code>, and
* <code>imageSizes</code>.
* @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that
* have sizes that are some multiple (typically double) of their actual display size. Icons such
* as these look better when viewed on high-resolution monitors such as Apple's Retina displays.
* Note: if this property is <code>true</code>, sprites cannot be used as cluster icons.
* @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the
* number of markers to be processed in a single batch when using a browser other than
* Internet Explorer (for Internet Explorer, use the batchSizeIE property instead).
* @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is
* being used, markers are processed in several batches with a small delay inserted between
* each batch in an attempt to avoid Javascript timeout errors. Set this property to the
* number of markers to be processed in a single batch; select as high a number as you can
* without causing a timeout error in the browser. This number might need to be as low as 100
* if 15,000 markers are being managed, for example.
* @property {string} [imagePath=MarkerClusterer.IMAGE_PATH]
* The full URL of the root name of the group of image files to use for cluster icons.
* The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code>
* where n is the image file number (1, 2, etc.).
* @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION]
* The extension name for the cluster icon image files (e.g., <code>"png"</code> or
* <code>"jpg"</code>).
* @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES]
* An array of numbers containing the widths of the group of
* <code>imagePath</code>n.<code>imageExtension</code> image files.
* (The images are assumed to be square.)
*/
/**
* Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}.
* @constructor
* @extends google.maps.OverlayView
* @param {google.maps.Map} map The Google map to attach to.
* @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster.
* @param {MarkerClustererOptions} [opt_options] The optional parameters.
*/
function MarkerClusterer(map, opt_markers, opt_options) {
// MarkerClusterer implements google.maps.OverlayView interface. We use the
// extend function to extend MarkerClusterer with google.maps.OverlayView
// because it might not always be available when the code is defined so we
// look for it at the last possible moment. If it doesn't exist now then
// there is no point going ahead :)
this.extend(MarkerClusterer, google.maps.OverlayView);
opt_markers = opt_markers || [];
opt_options = opt_options || {};
this.markers_ = [];
this.clusters_ = [];
this.listeners_ = [];
this.activeMap_ = null;
this.ready_ = false;
this.gridSize_ = opt_options.gridSize || 60;
this.minClusterSize_ = opt_options.minimumClusterSize || 2;
this.maxZoom_ = opt_options.maxZoom || null;
this.styles_ = opt_options.styles || [];
this.title_ = opt_options.title || "";
this.zoomOnClick_ = true;
if (opt_options.zoomOnClick !== undefined) {
this.zoomOnClick_ = opt_options.zoomOnClick;
}
this.averageCenter_ = false;
if (opt_options.averageCenter !== undefined) {
this.averageCenter_ = opt_options.averageCenter;
}
this.ignoreHidden_ = false;
if (opt_options.ignoreHidden !== undefined) {
this.ignoreHidden_ = opt_options.ignoreHidden;
}
this.enableRetinaIcons_ = false;
if (opt_options.enableRetinaIcons !== undefined) {
this.enableRetinaIcons_ = opt_options.enableRetinaIcons;
}
this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH;
this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION;
this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES;
this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR;
this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE;
this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE;
this.clusterClass_ = opt_options.clusterClass || "cluster";
if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) {
// Try to avoid IE timeout when processing a huge number of markers:
this.batchSize_ = this.batchSizeIE_;
}
this.setupStyles_();
this.addMarkers(opt_markers, true);
this.setMap(map); // Note: this causes onAdd to be called
}
/**
* Implementation of the onAdd interface method.
* @ignore
*/
MarkerClusterer.prototype.onAdd = function () {
var cMarkerClusterer = this;
this.activeMap_ = this.getMap();
this.ready_ = true;
this.repaint();
// Add the map event listeners
this.listeners_ = [
google.maps.event.addListener(this.getMap(), "zoom_changed", function () {
cMarkerClusterer.resetViewport_(false);
// Workaround for this Google bug: when map is at level 0 and "-" of
// zoom slider is clicked, a "zoom_changed" event is fired even though
// the map doesn't zoom out any further. In this situation, no "idle"
// event is triggered so the cluster markers that have been removed
// do not get redrawn. Same goes for a zoom in at maxZoom.
if (this.getZoom() === (this.get("minZoom") || 0) || this.getZoom() === this.get("maxZoom")) {
google.maps.event.trigger(this, "idle");
}
}),
google.maps.event.addListener(this.getMap(), "idle", function () {
cMarkerClusterer.redraw_();
})
];
};
/**
* Implementation of the onRemove interface method.
* Removes map event listeners and all cluster icons from the DOM.
* All managed markers are also put back on the map.
* @ignore
*/
MarkerClusterer.prototype.onRemove = function () {
var i;
// Put all the managed markers back on the map:
for (i = 0; i < this.markers_.length; i++) {
if (this.markers_[i].getMap() !== this.activeMap_) {
this.markers_[i].setMap(this.activeMap_);
}
}
// Remove all clusters:
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].remove();
}
this.clusters_ = [];
// Remove map event listeners:
for (i = 0; i < this.listeners_.length; i++) {
google.maps.event.removeListener(this.listeners_[i]);
}
this.listeners_ = [];
this.activeMap_ = null;
this.ready_ = false;
};
/**
* Implementation of the draw interface method.
* @ignore
*/
MarkerClusterer.prototype.draw = function () {};
/**
* Sets up the styles object.
*/
MarkerClusterer.prototype.setupStyles_ = function () {
var i, size;
if (this.styles_.length > 0) {
return;
}
for (i = 0; i < this.imageSizes_.length; i++) {
size = this.imageSizes_[i];
this.styles_.push({
url: this.imagePath_ + (i + 1) + "." + this.imageExtension_,
height: size,
width: size
});
}
};
/**
* Fits the map to the bounds of the markers managed by the clusterer.
*/
MarkerClusterer.prototype.fitMapToMarkers = function () {
var i;
var markers = this.getMarkers();
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
this.getMap().fitBounds(bounds);
};
/**
* Returns the value of the <code>gridSize</code> property.
*
* @return {number} The grid size.
*/
MarkerClusterer.prototype.getGridSize = function () {
return this.gridSize_;
};
/**
* Sets the value of the <code>gridSize</code> property.
*
* @param {number} gridSize The grid size.
*/
MarkerClusterer.prototype.setGridSize = function (gridSize) {
this.gridSize_ = gridSize;
};
/**
* Returns the value of the <code>minimumClusterSize</code> property.
*
* @return {number} The minimum cluster size.
*/
MarkerClusterer.prototype.getMinimumClusterSize = function () {
return this.minClusterSize_;
};
/**
* Sets the value of the <code>minimumClusterSize</code> property.
*
* @param {number} minimumClusterSize The minimum cluster size.
*/
MarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) {
this.minClusterSize_ = minimumClusterSize;
};
/**
* Returns the value of the <code>maxZoom</code> property.
*
* @return {number} The maximum zoom level.
*/
MarkerClusterer.prototype.getMaxZoom = function () {
return this.maxZoom_;
};
/**
* Sets the value of the <code>maxZoom</code> property.
*
* @param {number} maxZoom The maximum zoom level.
*/
MarkerClusterer.prototype.setMaxZoom = function (maxZoom) {
this.maxZoom_ = maxZoom;
};
/**
* Returns the value of the <code>styles</code> property.
*
* @return {Array} The array of styles defining the cluster markers to be used.
*/
MarkerClusterer.prototype.getStyles = function () {
return this.styles_;
};
/**
* Sets the value of the <code>styles</code> property.
*
* @param {Array.<ClusterIconStyle>} styles The array of styles to use.
*/
MarkerClusterer.prototype.setStyles = function (styles) {
this.styles_ = styles;
};
/**
* Returns the value of the <code>title</code> property.
*
* @return {string} The content of the title text.
*/
MarkerClusterer.prototype.getTitle = function () {
return this.title_;
};
/**
* Sets the value of the <code>title</code> property.
*
* @param {string} title The value of the title property.
*/
MarkerClusterer.prototype.setTitle = function (title) {
this.title_ = title;
};
/**
* Returns the value of the <code>zoomOnClick</code> property.
*
* @return {boolean} True if zoomOnClick property is set.
*/
MarkerClusterer.prototype.getZoomOnClick = function () {
return this.zoomOnClick_;
};
/**
* Sets the value of the <code>zoomOnClick</code> property.
*
* @param {boolean} zoomOnClick The value of the zoomOnClick property.
*/
MarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) {
this.zoomOnClick_ = zoomOnClick;
};
/**
* Returns the value of the <code>averageCenter</code> property.
*
* @return {boolean} True if averageCenter property is set.
*/
MarkerClusterer.prototype.getAverageCenter = function () {
return this.averageCenter_;
};
/**
* Sets the value of the <code>averageCenter</code> property.
*
* @param {boolean} averageCenter The value of the averageCenter property.
*/
MarkerClusterer.prototype.setAverageCenter = function (averageCenter) {
this.averageCenter_ = averageCenter;
};
/**
* Returns the value of the <code>ignoreHidden</code> property.
*
* @return {boolean} True if ignoreHidden property is set.
*/
MarkerClusterer.prototype.getIgnoreHidden = function () {
return this.ignoreHidden_;
};
/**
* Sets the value of the <code>ignoreHidden</code> property.
*
* @param {boolean} ignoreHidden The value of the ignoreHidden property.
*/
MarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) {
this.ignoreHidden_ = ignoreHidden;
};
/**
* Returns the value of the <code>enableRetinaIcons</code> property.
*
* @return {boolean} True if enableRetinaIcons property is set.
*/
MarkerClusterer.prototype.getEnableRetinaIcons = function () {
return this.enableRetinaIcons_;
};
/**
* Sets the value of the <code>enableRetinaIcons</code> property.
*
* @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property.
*/
MarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) {
this.enableRetinaIcons_ = enableRetinaIcons;
};
/**
* Returns the value of the <code>imageExtension</code> property.
*
* @return {string} The value of the imageExtension property.
*/
MarkerClusterer.prototype.getImageExtension = function () {
return this.imageExtension_;
};
/**
* Sets the value of the <code>imageExtension</code> property.
*
* @param {string} imageExtension The value of the imageExtension property.
*/
MarkerClusterer.prototype.setImageExtension = function (imageExtension) {
this.imageExtension_ = imageExtension;
};
/**
* Returns the value of the <code>imagePath</code> property.
*
* @return {string} The value of the imagePath property.
*/
MarkerClusterer.prototype.getImagePath = function () {
return this.imagePath_;
};
/**
* Sets the value of the <code>imagePath</code> property.
*
* @param {string} imagePath The value of the imagePath property.
*/
MarkerClusterer.prototype.setImagePath = function (imagePath) {
this.imagePath_ = imagePath;
};
/**
* Returns the value of the <code>imageSizes</code> property.
*
* @return {Array} The value of the imageSizes property.
*/
MarkerClusterer.prototype.getImageSizes = function () {
return this.imageSizes_;
};
/**
* Sets the value of the <code>imageSizes</code> property.
*
* @param {Array} imageSizes The value of the imageSizes property.
*/
MarkerClusterer.prototype.setImageSizes = function (imageSizes) {
this.imageSizes_ = imageSizes;
};
/**
* Returns the value of the <code>calculator</code> property.
*
* @return {function} the value of the calculator property.
*/
MarkerClusterer.prototype.getCalculator = function () {
return this.calculator_;
};
/**
* Sets the value of the <code>calculator</code> property.
*
* @param {function(Array.<google.maps.Marker>, number)} calculator The value
* of the calculator property.
*/
MarkerClusterer.prototype.setCalculator = function (calculator) {
this.calculator_ = calculator;
};
/**
* Returns the value of the <code>batchSizeIE</code> property.
*
* @return {number} the value of the batchSizeIE property.
*/
MarkerClusterer.prototype.getBatchSizeIE = function () {
return this.batchSizeIE_;
};
/**
* Sets the value of the <code>batchSizeIE</code> property.
*
* @param {number} batchSizeIE The value of the batchSizeIE property.
*/
MarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) {
this.batchSizeIE_ = batchSizeIE;
};
/**
* Returns the value of the <code>clusterClass</code> property.
*
* @return {string} the value of the clusterClass property.
*/
MarkerClusterer.prototype.getClusterClass = function () {
return this.clusterClass_;
};
/**
* Sets the value of the <code>clusterClass</code> property.
*
* @param {string} clusterClass The value of the clusterClass property.
*/
MarkerClusterer.prototype.setClusterClass = function (clusterClass) {
this.clusterClass_ = clusterClass;
};
/**
* Returns the array of markers managed by the clusterer.
*
* @return {Array} The array of markers managed by the clusterer.
*/
MarkerClusterer.prototype.getMarkers = function () {
return this.markers_;
};
/**
* Returns the number of markers managed by the clusterer.
*
* @return {number} The number of markers.
*/
MarkerClusterer.prototype.getTotalMarkers = function () {
return this.markers_.length;
};
/**
* Returns the current array of clusters formed by the clusterer.
*
* @return {Array} The array of clusters formed by the clusterer.
*/
MarkerClusterer.prototype.getClusters = function () {
return this.clusters_;
};
/**
* Returns the number of clusters formed by the clusterer.
*
* @return {number} The number of clusters formed by the clusterer.
*/
MarkerClusterer.prototype.getTotalClusters = function () {
return this.clusters_.length;
};
/**
* Adds a marker to the clusterer. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>.
*
* @param {google.maps.Marker} marker The marker to add.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
*/
MarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) {
this.pushMarkerTo_(marker);
if (!opt_nodraw) {
this.redraw_();
}
};
/**
* Adds an array of markers to the clusterer. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>.
*
* @param {Array.<google.maps.Marker>} markers The markers to add.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
*/
MarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) {
var key;
for (key in markers) {
if (markers.hasOwnProperty(key)) {
this.pushMarkerTo_(markers[key]);
}
}
if (!opt_nodraw) {
this.redraw_();
}
};
/**
* Pushes a marker to the clusterer.
*
* @param {google.maps.Marker} marker The marker to add.
*/
MarkerClusterer.prototype.pushMarkerTo_ = function (marker) {
// If the marker is draggable add a listener so we can update the clusters on the dragend:
if (marker.getDraggable()) {
var cMarkerClusterer = this;
google.maps.event.addListener(marker, "dragend", function () {
if (cMarkerClusterer.ready_) {
this.isAdded = false;
cMarkerClusterer.repaint();
}
});
}
marker.isAdded = false;
this.markers_.push(marker);
};
/**
* Removes a marker from the cluster. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the
* marker was removed from the clusterer.
*
* @param {google.maps.Marker} marker The marker to remove.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
* @return {boolean} True if the marker was removed from the clusterer.
*/
MarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) {
var removed = this.removeMarker_(marker);
if (!opt_nodraw && removed) {
this.repaint();
}
return removed;
};
/**
* Removes an array of markers from the cluster. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers
* were removed from the clusterer.
*
* @param {Array.<google.maps.Marker>} markers The markers to remove.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
* @return {boolean} True if markers were removed from the clusterer.
*/
MarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) {
var i, r;
var removed = false;
for (i = 0; i < markers.length; i++) {
r = this.removeMarker_(markers[i]);
removed = removed || r;
}
if (!opt_nodraw && removed) {
this.repaint();
}
return removed;
};
/**
* Removes a marker and returns true if removed, false if not.
*
* @param {google.maps.Marker} marker The marker to remove
* @return {boolean} Whether the marker was removed or not
*/
MarkerClusterer.prototype.removeMarker_ = function (marker) {
var i;
var index = -1;
if (this.markers_.indexOf) {
index = this.markers_.indexOf(marker);
} else {
for (i = 0; i < this.markers_.length; i++) {
if (marker === this.markers_[i]) {
index = i;
break;
}
}
}
if (index === -1) {
// Marker is not in our list of markers, so do nothing:
return false;
}
marker.setMap(null);
this.markers_.splice(index, 1); // Remove the marker from the list of managed markers
return true;
};
/**
* Removes all clusters and markers from the map and also removes all markers
* managed by the clusterer.
*/
MarkerClusterer.prototype.clearMarkers = function () {
this.resetViewport_(true);
this.markers_ = [];
};
/**
* Recalculates and redraws all the marker clusters from scratch.
* Call this after changing any properties.
*/
MarkerClusterer.prototype.repaint = function () {
var oldClusters = this.clusters_.slice();
this.clusters_ = [];
this.resetViewport_(false);
this.redraw_();
// Remove the old clusters.
// Do it in a timeout to prevent blinking effect.
setTimeout(function () {
var i;
for (i = 0; i < oldClusters.length; i++) {
oldClusters[i].remove();
}
}, 0);
};
/**
* Returns the current bounds extended by the grid size.
*
* @param {google.maps.LatLngBounds} bounds The bounds to extend.
* @return {google.maps.LatLngBounds} The extended bounds.
* @ignore
*/
MarkerClusterer.prototype.getExtendedBounds = function (bounds) {
var projection = this.getProjection();
// Turn the bounds into latlng.
var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
bounds.getNorthEast().lng());
var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),
bounds.getSouthWest().lng());
// Convert the points to pixels and the extend out by the grid size.
var trPix = projection.fromLatLngToDivPixel(tr);
trPix.x += this.gridSize_;
trPix.y -= this.gridSize_;
var blPix = projection.fromLatLngToDivPixel(bl);
blPix.x -= this.gridSize_;
blPix.y += this.gridSize_;
// Convert the pixel points back to LatLng
var ne = projection.fromDivPixelToLatLng(trPix);
var sw = projection.fromDivPixelToLatLng(blPix);
// Extend the bounds to contain the new bounds.
bounds.extend(ne);
bounds.extend(sw);
return bounds;
};
/**
* Redraws all the clusters.
*/
MarkerClusterer.prototype.redraw_ = function () {
this.createClusters_(0);
};
/**
* Removes all clusters from the map. The markers are also removed from the map
* if <code>opt_hide</code> is set to <code>true</code>.
*
* @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers
* from the map.
*/
MarkerClusterer.prototype.resetViewport_ = function (opt_hide) {
var i, marker;
// Remove all the clusters
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].remove();
}
this.clusters_ = [];
// Reset the markers to not be added and to be removed from the map.
for (i = 0; i < this.markers_.length; i++) {
marker = this.markers_[i];
marker.isAdded = false;
if (opt_hide) {
marker.setMap(null);
}
}
};
/**
* Calculates the distance between two latlng locations in km.
*
* @param {google.maps.LatLng} p1 The first lat lng point.
* @param {google.maps.LatLng} p2 The second lat lng point.
* @return {number} The distance between the two points in km.
* @see http://www.movable-type.co.uk/scripts/latlong.html
*/
MarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) {
var R = 6371; // Radius of the Earth in km
var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
};
/**
* Determines if a marker is contained in a bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @param {google.maps.LatLngBounds} bounds The bounds to check against.
* @return {boolean} True if the marker is in the bounds.
*/
MarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) {
return bounds.contains(marker.getPosition());
};
/**
* Adds a marker to a cluster, or creates a new cluster.
*
* @param {google.maps.Marker} marker The marker to add.
*/
MarkerClusterer.prototype.addToClosestCluster_ = function (marker) {
var i, d, cluster, center;
var distance = 40000; // Some large number
var clusterToAddTo = null;
for (i = 0; i < this.clusters_.length; i++) {
cluster = this.clusters_[i];
center = cluster.getCenter();
if (center) {
d = this.distanceBetweenPoints_(center, marker.getPosition());
if (d < distance) {
distance = d;
clusterToAddTo = cluster;
}
}
}
if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
clusterToAddTo.addMarker(marker);
} else {
cluster = new Cluster(this);
cluster.addMarker(marker);
this.clusters_.push(cluster);
}
};
/**
* Creates the clusters. This is done in batches to avoid timeout errors
* in some browsers when there is a huge number of markers.
*
* @param {number} iFirst The index of the first marker in the batch of
* markers to be added to clusters.
*/
MarkerClusterer.prototype.createClusters_ = function (iFirst) {
var i, marker;
var mapBounds;
var cMarkerClusterer = this;
if (!this.ready_) {
return;
}
// Cancel previous batch processing if we're working on the first batch:
if (iFirst === 0) {
/**
* This event is fired when the <code>MarkerClusterer</code> begins
* clustering markers.
* @name MarkerClusterer#clusteringbegin
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, "clusteringbegin", this);
if (typeof this.timerRefStatic !== "undefined") {
clearTimeout(this.timerRefStatic);
delete this.timerRefStatic;
}
}
// Get our current map view bounds.
// Create a new bounds object so we don't affect the map.
//
// See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:
if (this.getMap().getZoom() > 3) {
mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),
this.getMap().getBounds().getNorthEast());
} else {
mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));
}
var bounds = this.getExtendedBounds(mapBounds);
var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);
for (i = iFirst; i < iLast; i++) {
marker = this.markers_[i];
if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {
this.addToClosestCluster_(marker);
}
}
}
if (iLast < this.markers_.length) {
this.timerRefStatic = setTimeout(function () {
cMarkerClusterer.createClusters_(iLast);
}, 0);
} else {
delete this.timerRefStatic;
/**
* This event is fired when the <code>MarkerClusterer</code> stops
* clustering markers.
* @name MarkerClusterer#clusteringend
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, "clusteringend", this);
}
};
/**
* Extends an object's prototype by another's.
*
* @param {Object} obj1 The object to be extended.
* @param {Object} obj2 The object to extend with.
* @return {Object} The new extended object.
* @ignore
*/
MarkerClusterer.prototype.extend = function (obj1, obj2) {
return (function (object) {
var property;
for (property in object.prototype) {
this.prototype[property] = object.prototype[property];
}
return this;
}).apply(obj1, [obj2]);
};
/**
* The default function for determining the label text and style
* for a cluster icon.
*
* @param {Array.<google.maps.Marker>} markers The array of markers represented by the cluster.
* @param {number} numStyles The number of marker styles available.
* @return {ClusterIconInfo} The information resource for the cluster.
* @constant
* @ignore
*/
MarkerClusterer.CALCULATOR = function (markers, numStyles) {
var index = 0;
var title = "";
var count = markers.length.toString();
var dv = count;
while (dv !== 0) {
dv = parseInt(dv / 10, 10);
index++;
}
index = Math.min(index, numStyles);
return {
text: count,
index: index,
title: title
};
};
/**
* The number of markers to process in one batch.
*
* @type {number}
* @constant
*/
MarkerClusterer.BATCH_SIZE = 2000;
/**
* The number of markers to process in one batch (IE only).
*
* @type {number}
* @constant
*/
MarkerClusterer.BATCH_SIZE_IE = 500;
/**
* The default root name for the marker cluster images.
*
* @type {string}
* @constant
*/
MarkerClusterer.IMAGE_PATH = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m";
/**
* The default extension name for the marker cluster images.
*
* @type {string}
* @constant
*/
MarkerClusterer.IMAGE_EXTENSION = "png";
/**
* The default array of sizes for the marker cluster images.
*
* @type {Array.<number>}
* @constant
*/
MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90];
/**
* @name MarkerWithLabel for V3
* @version 1.1.10 [April 8, 2014]
* @author Gary Little (inspired by code from Marc Ridey of Google).
* @copyright Copyright 2012 Gary Little [gary at luxcentral.com]
* @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3
* <code>google.maps.Marker</code> class.
* <p>
* MarkerWithLabel allows you to define markers with associated labels. As you would expect,
* if the marker is draggable, so too will be the label. In addition, a marker with a label
* responds to all mouse events in the same manner as a regular marker. It also fires mouse
* events and "property changed" events just as a regular marker would. Version 1.1 adds
* support for the raiseOnDrag feature introduced in API V3.3.
* <p>
* If you drag a marker by its label, you can cancel the drag and return the marker to its
* original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker
* itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class.
*/
/*!
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint browser:true */
/*global document,google */
/**
* @param {Function} childCtor Child class.
* @param {Function} parentCtor Parent class.
* @private
*/
function inherits(childCtor, parentCtor) {
/* @constructor */
function tempCtor() {}
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
/* @override */
childCtor.prototype.constructor = childCtor;
}
/**
* This constructor creates a label and associates it with a marker.
* It is for the private use of the MarkerWithLabel class.
* @constructor
* @param {Marker} marker The marker with which the label is to be associated.
* @param {string} crossURL The URL of the cross image =.
* @param {string} handCursor The URL of the hand cursor.
* @private
*/
function MarkerLabel_(marker, crossURL, handCursorURL) {
this.marker_ = marker;
this.handCursorURL_ = marker.handCursorURL;
this.labelDiv_ = document.createElement("div");
this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;";
// Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil
// in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that
// events can be captured even if the label is in the shadow of a google.maps.InfoWindow.
// Code is included here to ensure the veil is always exactly the same size as the label.
this.eventDiv_ = document.createElement("div");
this.eventDiv_.style.cssText = this.labelDiv_.style.cssText;
// This is needed for proper behavior on MSIE:
this.eventDiv_.setAttribute("onselectstart", "return false;");
this.eventDiv_.setAttribute("ondragstart", "return false;");
// Get the DIV for the "X" to be displayed when the marker is raised.
this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL);
}
inherits(MarkerLabel_, google.maps.OverlayView);
/**
* Returns the DIV for the cross used when dragging a marker when the
* raiseOnDrag parameter set to true. One cross is shared with all markers.
* @param {string} crossURL The URL of the cross image =.
* @private
*/
MarkerLabel_.getSharedCross = function (crossURL) {
var div;
if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") {
div = document.createElement("img");
div.style.cssText = "position: absolute; z-index: 1000002; display: none;";
// Hopefully Google never changes the standard "X" attributes:
div.style.marginLeft = "-8px";
div.style.marginTop = "-9px";
div.src = crossURL;
MarkerLabel_.getSharedCross.crossDiv = div;
}
return MarkerLabel_.getSharedCross.crossDiv;
};
/**
* Adds the DIV representing the label to the DOM. This method is called
* automatically when the marker's <code>setMap</code> method is called.
* @private
*/
MarkerLabel_.prototype.onAdd = function () {
var me = this;
var cMouseIsDown = false;
var cDraggingLabel = false;
var cSavedZIndex;
var cLatOffset, cLngOffset;
var cIgnoreClick;
var cRaiseEnabled;
var cStartPosition;
var cStartCenter;
// Constants:
var cRaiseOffset = 20;
var cDraggingCursor = "url(" + this.handCursorURL_ + ")";
// Stops all processing of an event.
//
var cAbortEvent = function (e) {
if (e.preventDefault) {
e.preventDefault();
}
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
};
var cStopBounce = function () {
me.marker_.setAnimation(null);
};
this.getPanes().overlayImage.appendChild(this.labelDiv_);
this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_);
// One cross is shared with all markers, so only add it once:
if (typeof MarkerLabel_.getSharedCross.processed === "undefined") {
this.getPanes().overlayImage.appendChild(this.crossDiv_);
MarkerLabel_.getSharedCross.processed = true;
}
this.listeners_ = [
google.maps.event.addDomListener(this.eventDiv_, "mouseover", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
this.style.cursor = "pointer";
google.maps.event.trigger(me.marker_, "mouseover", e);
}
}),
google.maps.event.addDomListener(this.eventDiv_, "mouseout", function (e) {
if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) {
this.style.cursor = me.marker_.getCursor();
google.maps.event.trigger(me.marker_, "mouseout", e);
}
}),
google.maps.event.addDomListener(this.eventDiv_, "mousedown", function (e) {
cDraggingLabel = false;
if (me.marker_.getDraggable()) {
cMouseIsDown = true;
this.style.cursor = cDraggingCursor;
}
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
google.maps.event.trigger(me.marker_, "mousedown", e);
cAbortEvent(e); // Prevent map pan when starting a drag on a label
}
}),
google.maps.event.addDomListener(document, "mouseup", function (mEvent) {
var position;
if (cMouseIsDown) {
cMouseIsDown = false;
me.eventDiv_.style.cursor = "pointer";
google.maps.event.trigger(me.marker_, "mouseup", mEvent);
}
if (cDraggingLabel) {
if (cRaiseEnabled) { // Lower the marker & label
position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition());
position.y += cRaiseOffset;
me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position));
// This is not the same bouncing style as when the marker portion is dragged,
// but it will have to do:
try { // Will fail if running Google Maps API earlier than V3.3
me.marker_.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(cStopBounce, 1406);
} catch (e) {}
}
me.crossDiv_.style.display = "none";
me.marker_.setZIndex(cSavedZIndex);
cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag
cDraggingLabel = false;
mEvent.latLng = me.marker_.getPosition();
google.maps.event.trigger(me.marker_, "dragend", mEvent);
}
}),
google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) {
var position;
if (cMouseIsDown) {
if (cDraggingLabel) {
// Change the reported location from the mouse position to the marker position:
mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset);
position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng);
if (cRaiseEnabled) {
me.crossDiv_.style.left = position.x + "px";
me.crossDiv_.style.top = position.y + "px";
me.crossDiv_.style.display = "";
position.y -= cRaiseOffset;
}
me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position));
if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly
me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px";
}
google.maps.event.trigger(me.marker_, "drag", mEvent);
} else {
// Calculate offsets from the click point to the marker position:
cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat();
cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng();
cSavedZIndex = me.marker_.getZIndex();
cStartPosition = me.marker_.getPosition();
cStartCenter = me.marker_.getMap().getCenter();
cRaiseEnabled = me.marker_.get("raiseOnDrag");
cDraggingLabel = true;
me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag
mEvent.latLng = me.marker_.getPosition();
google.maps.event.trigger(me.marker_, "dragstart", mEvent);
}
}
}),
google.maps.event.addDomListener(document, "keydown", function (e) {
if (cDraggingLabel) {
if (e.keyCode === 27) { // Esc key
cRaiseEnabled = false;
me.marker_.setPosition(cStartPosition);
me.marker_.getMap().setCenter(cStartCenter);
google.maps.event.trigger(document, "mouseup", e);
}
}
}),
google.maps.event.addDomListener(this.eventDiv_, "click", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
if (cIgnoreClick) { // Ignore the click reported when a label drag ends
cIgnoreClick = false;
} else {
google.maps.event.trigger(me.marker_, "click", e);
cAbortEvent(e); // Prevent click from being passed on to map
}
}
}),
google.maps.event.addDomListener(this.eventDiv_, "dblclick", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
google.maps.event.trigger(me.marker_, "dblclick", e);
cAbortEvent(e); // Prevent map zoom when double-clicking on a label
}
}),
google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) {
if (!cDraggingLabel) {
cRaiseEnabled = this.get("raiseOnDrag");
}
}),
google.maps.event.addListener(this.marker_, "drag", function (mEvent) {
if (!cDraggingLabel) {
if (cRaiseEnabled) {
me.setPosition(cRaiseOffset);
// During a drag, the marker's z-index is temporarily set to 1000000 to
// ensure it appears above all other markers. Also set the label's z-index
// to 1000000 (plus or minus 1 depending on whether the label is supposed
// to be above or below the marker).
me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1);
}
}
}),
google.maps.event.addListener(this.marker_, "dragend", function (mEvent) {
if (!cDraggingLabel) {
if (cRaiseEnabled) {
me.setPosition(0); // Also restores z-index of label
}
}
}),
google.maps.event.addListener(this.marker_, "position_changed", function () {
me.setPosition();
}),
google.maps.event.addListener(this.marker_, "zindex_changed", function () {
me.setZIndex();
}),
google.maps.event.addListener(this.marker_, "visible_changed", function () {
me.setVisible();
}),
google.maps.event.addListener(this.marker_, "labelvisible_changed", function () {
me.setVisible();
}),
google.maps.event.addListener(this.marker_, "title_changed", function () {
me.setTitle();
}),
google.maps.event.addListener(this.marker_, "labelcontent_changed", function () {
me.setContent();
}),
google.maps.event.addListener(this.marker_, "labelanchor_changed", function () {
me.setAnchor();
}),
google.maps.event.addListener(this.marker_, "labelclass_changed", function () {
me.setStyles();
}),
google.maps.event.addListener(this.marker_, "labelstyle_changed", function () {
me.setStyles();
})
];
};
/**
* Removes the DIV for the label from the DOM. It also removes all event handlers.
* This method is called automatically when the marker's <code>setMap(null)</code>
* method is called.
* @private
*/
MarkerLabel_.prototype.onRemove = function () {
var i;
this.labelDiv_.parentNode.removeChild(this.labelDiv_);
this.eventDiv_.parentNode.removeChild(this.eventDiv_);
// Remove event listeners:
for (i = 0; i < this.listeners_.length; i++) {
google.maps.event.removeListener(this.listeners_[i]);
}
};
/**
* Draws the label on the map.
* @private
*/
MarkerLabel_.prototype.draw = function () {
this.setContent();
this.setTitle();
this.setStyles();
};
/**
* Sets the content of the label.
* The content can be plain text or an HTML DOM node.
* @private
*/
MarkerLabel_.prototype.setContent = function () {
var content = this.marker_.get("labelContent");
if (typeof content.nodeType === "undefined") {
this.labelDiv_.innerHTML = content;
this.eventDiv_.innerHTML = this.labelDiv_.innerHTML;
} else {
this.labelDiv_.innerHTML = ""; // Remove current content
this.labelDiv_.appendChild(content);
content = content.cloneNode(true);
this.eventDiv_.innerHTML = ""; // Remove current content
this.eventDiv_.appendChild(content);
}
};
/**
* Sets the content of the tool tip for the label. It is
* always set to be the same as for the marker itself.
* @private
*/
MarkerLabel_.prototype.setTitle = function () {
this.eventDiv_.title = this.marker_.getTitle() || "";
};
/**
* Sets the style of the label by setting the style sheet and applying
* other specific styles requested.
* @private
*/
MarkerLabel_.prototype.setStyles = function () {
var i, labelStyle;
// Apply style values from the style sheet defined in the labelClass parameter:
this.labelDiv_.className = this.marker_.get("labelClass");
this.eventDiv_.className = this.labelDiv_.className;
// Clear existing inline style values:
this.labelDiv_.style.cssText = "";
this.eventDiv_.style.cssText = "";
// Apply style values defined in the labelStyle parameter:
labelStyle = this.marker_.get("labelStyle");
for (i in labelStyle) {
if (labelStyle.hasOwnProperty(i)) {
this.labelDiv_.style[i] = labelStyle[i];
this.eventDiv_.style[i] = labelStyle[i];
}
}
this.setMandatoryStyles();
};
/**
* Sets the mandatory styles to the DIV representing the label as well as to the
* associated event DIV. This includes setting the DIV position, z-index, and visibility.
* @private
*/
MarkerLabel_.prototype.setMandatoryStyles = function () {
this.labelDiv_.style.position = "absolute";
this.labelDiv_.style.overflow = "hidden";
// Make sure the opacity setting causes the desired effect on MSIE:
if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") {
this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\"";
this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")";
}
this.eventDiv_.style.position = this.labelDiv_.style.position;
this.eventDiv_.style.overflow = this.labelDiv_.style.overflow;
this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE
this.eventDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\"";
this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE
this.setAnchor();
this.setPosition(); // This also updates z-index, if necessary.
this.setVisible();
};
/**
* Sets the anchor point of the label.
* @private
*/
MarkerLabel_.prototype.setAnchor = function () {
var anchor = this.marker_.get("labelAnchor");
this.labelDiv_.style.marginLeft = -anchor.x + "px";
this.labelDiv_.style.marginTop = -anchor.y + "px";
this.eventDiv_.style.marginLeft = -anchor.x + "px";
this.eventDiv_.style.marginTop = -anchor.y + "px";
};
/**
* Sets the position of the label. The z-index is also updated, if necessary.
* @private
*/
MarkerLabel_.prototype.setPosition = function (yOffset) {
var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition());
if (typeof yOffset === "undefined") {
yOffset = 0;
}
this.labelDiv_.style.left = Math.round(position.x) + "px";
this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px";
this.eventDiv_.style.left = this.labelDiv_.style.left;
this.eventDiv_.style.top = this.labelDiv_.style.top;
this.setZIndex();
};
/**
* Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index
* of the label is set to the vertical coordinate of the label. This is in keeping with the default
* stacking order for Google Maps: markers to the south are in front of markers to the north.
* @private
*/
MarkerLabel_.prototype.setZIndex = function () {
var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1);
if (typeof this.marker_.getZIndex() === "undefined") {
this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust;
this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex;
} else {
this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust;
this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex;
}
};
/**
* Sets the visibility of the label. The label is visible only if the marker itself is
* visible (i.e., its visible property is true) and the labelVisible property is true.
* @private
*/
MarkerLabel_.prototype.setVisible = function () {
if (this.marker_.get("labelVisible")) {
this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none";
} else {
this.labelDiv_.style.display = "none";
}
this.eventDiv_.style.display = this.labelDiv_.style.display;
};
/**
* @name MarkerWithLabelOptions
* @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor.
* The properties available are the same as for <code>google.maps.Marker</code> with the addition
* of the properties listed below. To change any of these additional properties after the labeled
* marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>.
* <p>
* When any of these properties changes, a property changed event is fired. The names of these
* events are derived from the name of the property and are of the form <code>propertyname_changed</code>.
* For example, if the content of the label changes, a <code>labelcontent_changed</code> event
* is fired.
* <p>
* @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node).
* @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so
* that its top left corner is positioned at the anchor point of the associated marker. Use this
* property to change the anchor point of the label. For example, to center a 50px-wide label
* beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>.
* (Note: x-values increase to the right and y-values increase to the top.)
* @property {string} [labelClass] The name of the CSS class defining the styles for the label.
* Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>,
* <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and
* <code>marginTop</code> are ignored; these styles are for internal use only.
* @property {Object} [labelStyle] An object literal whose properties define specific CSS
* style values to be applied to the label. Style values defined here override those that may
* be defined in the <code>labelClass</code> style sheet. If this property is changed after the
* label has been created, all previously set styles (except those defined in the style sheet)
* are removed from the label before the new style values are applied.
* Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>,
* <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and
* <code>marginTop</code> are ignored; these styles are for internal use only.
* @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its
* associated marker should appear in the background (i.e., in a plane below the marker).
* The default is <code>false</code>, which causes the label to appear in the foreground.
* @property {boolean} [labelVisible] A flag indicating whether the label is to be visible.
* The default is <code>true</code>. Note that even if <code>labelVisible</code> is
* <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also
* visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>).
* @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be
* raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is
* being created and a version of Google Maps API earlier than V3.3 is being used, this property
* must be set to <code>false</code>.
* @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the
* marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel,
* so the value of this parameter is always forced to <code>false</code>.
* @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"]
* The URL of the cross image to be displayed while dragging a marker.
* @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"]
* The URL of the cursor to be displayed while dragging a marker.
*/
/**
* Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}.
* @constructor
* @param {MarkerWithLabelOptions} [opt_options] The optional parameters.
*/
function MarkerWithLabel(opt_options) {
opt_options = opt_options || {};
opt_options.labelContent = opt_options.labelContent || "";
opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0);
opt_options.labelClass = opt_options.labelClass || "markerLabels";
opt_options.labelStyle = opt_options.labelStyle || {};
opt_options.labelInBackground = opt_options.labelInBackground || false;
if (typeof opt_options.labelVisible === "undefined") {
opt_options.labelVisible = true;
}
if (typeof opt_options.raiseOnDrag === "undefined") {
opt_options.raiseOnDrag = true;
}
if (typeof opt_options.clickable === "undefined") {
opt_options.clickable = true;
}
if (typeof opt_options.draggable === "undefined") {
opt_options.draggable = false;
}
if (typeof opt_options.optimized === "undefined") {
opt_options.optimized = false;
}
opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png";
opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur";
opt_options.optimized = false; // Optimized rendering is not supported
this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker
// Call the parent constructor. It calls Marker.setValues to initialize, so all
// the new parameters are conveniently saved and can be accessed with get/set.
// Marker.set triggers a property changed event (called "propertyname_changed")
// that the marker label listens for in order to react to state changes.
google.maps.Marker.apply(this, arguments);
}
inherits(MarkerWithLabel, google.maps.Marker);
/**
* Overrides the standard Marker setMap function.
* @param {Map} theMap The map to which the marker is to be added.
* @private
*/
MarkerWithLabel.prototype.setMap = function (theMap) {
// Call the inherited function...
google.maps.Marker.prototype.setMap.apply(this, arguments);
// ... then deal with the label:
this.label.setMap(theMap);
};
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @externs_url http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/maps/google_maps_api_v3.js
// @output_wrapper (function() {%output%})();
// ==/ClosureCompiler==
/**
* @license
* Copyright 2013 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A RichMarker that allows any HTML/DOM to be added to a map and be draggable.
*
* @param {Object.<string, *>=} opt_options Optional properties to set.
* @extends {google.maps.OverlayView}
* @constructor
*/
function RichMarker(opt_options) {
var options = opt_options || {};
/**
* @type {boolean}
* @private
*/
this.ready_ = false;
/**
* @type {boolean}
* @private
*/
this.dragging_ = false;
if (opt_options['visible'] == undefined) {
opt_options['visible'] = true;
}
if (opt_options['shadow'] == undefined) {
opt_options['shadow'] = '7px -3px 5px rgba(88,88,88,0.7)';
}
if (opt_options['anchor'] == undefined) {
opt_options['anchor'] = RichMarkerPosition['BOTTOM'];
}
this.setValues(options);
}
RichMarker.prototype = new google.maps.OverlayView();
window['RichMarker'] = RichMarker;
/**
* Returns the current visibility state of the marker.
*
* @return {boolean} The visiblity of the marker.
*/
RichMarker.prototype.getVisible = function() {
return /** @type {boolean} */ (this.get('visible'));
};
RichMarker.prototype['getVisible'] = RichMarker.prototype.getVisible;
/**
* Sets the visiblility state of the marker.
*
* @param {boolean} visible The visiblilty of the marker.
*/
RichMarker.prototype.setVisible = function(visible) {
this.set('visible', visible);
};
RichMarker.prototype['setVisible'] = RichMarker.prototype.setVisible;
/**
* The visible changed event.
*/
RichMarker.prototype.visible_changed = function() {
if (this.ready_) {
this.markerWrapper_.style['display'] = this.getVisible() ? '' : 'none';
this.draw();
}
};
RichMarker.prototype['visible_changed'] = RichMarker.prototype.visible_changed;
/**
* Sets the marker to be flat.
*
* @param {boolean} flat If the marker is to be flat or not.
*/
RichMarker.prototype.setFlat = function(flat) {
this.set('flat', !!flat);
};
RichMarker.prototype['setFlat'] = RichMarker.prototype.setFlat;
/**
* If the makrer is flat or not.
*
* @return {boolean} True the marker is flat.
*/
RichMarker.prototype.getFlat = function() {
return /** @type {boolean} */ (this.get('flat'));
};
RichMarker.prototype['getFlat'] = RichMarker.prototype.getFlat;
/**
* Get the width of the marker.
*
* @return {Number} The width of the marker.
*/
RichMarker.prototype.getWidth = function() {
return /** @type {Number} */ (this.get('width'));
};
RichMarker.prototype['getWidth'] = RichMarker.prototype.getWidth;
/**
* Get the height of the marker.
*
* @return {Number} The height of the marker.
*/
RichMarker.prototype.getHeight = function() {
return /** @type {Number} */ (this.get('height'));
};
RichMarker.prototype['getHeight'] = RichMarker.prototype.getHeight;
/**
* Sets the marker's box shadow.
*
* @param {string} shadow The box shadow to set.
*/
RichMarker.prototype.setShadow = function(shadow) {
this.set('shadow', shadow);
this.flat_changed();
};
RichMarker.prototype['setShadow'] = RichMarker.prototype.setShadow;
/**
* Gets the marker's box shadow.
*
* @return {string} The box shadow.
*/
RichMarker.prototype.getShadow = function() {
return /** @type {string} */ (this.get('shadow'));
};
RichMarker.prototype['getShadow'] = RichMarker.prototype.getShadow;
/**
* Flat changed event.
*/
RichMarker.prototype.flat_changed = function() {
if (!this.ready_) {
return;
}
this.markerWrapper_.style['boxShadow'] =
this.markerWrapper_.style['webkitBoxShadow'] =
this.markerWrapper_.style['MozBoxShadow'] =
this.getFlat() ? '' : this.getShadow();
};
RichMarker.prototype['flat_changed'] = RichMarker.prototype.flat_changed;
/**
* Sets the zIndex of the marker.
*
* @param {Number} index The index to set.
*/
RichMarker.prototype.setZIndex = function(index) {
this.set('zIndex', index);
};
RichMarker.prototype['setZIndex'] = RichMarker.prototype.setZIndex;
/**
* Gets the zIndex of the marker.
*
* @return {Number} The zIndex of the marker.
*/
RichMarker.prototype.getZIndex = function() {
return /** @type {Number} */ (this.get('zIndex'));
};
RichMarker.prototype['getZIndex'] = RichMarker.prototype.getZIndex;
/**
* zIndex changed event.
*/
RichMarker.prototype.zIndex_changed = function() {
if (this.getZIndex() && this.ready_) {
this.markerWrapper_.style.zIndex = this.getZIndex();
}
};
RichMarker.prototype['zIndex_changed'] = RichMarker.prototype.zIndex_changed;
/**
* Whether the marker is draggable or not.
*
* @return {boolean} True if the marker is draggable.
*/
RichMarker.prototype.getDraggable = function() {
return /** @type {boolean} */ (this.get('draggable'));
};
RichMarker.prototype['getDraggable'] = RichMarker.prototype.getDraggable;
/**
* Sets the marker to be draggable or not.
*
* @param {boolean} draggable If the marker is draggable or not.
*/
RichMarker.prototype.setDraggable = function(draggable) {
this.set('draggable', !!draggable);
};
RichMarker.prototype['setDraggable'] = RichMarker.prototype.setDraggable;
/**
* Draggable property changed callback.
*/
RichMarker.prototype.draggable_changed = function() {
if (this.ready_) {
if (this.getDraggable()) {
this.addDragging_(this.markerWrapper_);
} else {
this.removeDragListeners_();
}
}
};
RichMarker.prototype['draggable_changed'] =
RichMarker.prototype.draggable_changed;
/**
* Gets the postiton of the marker.
*
* @return {google.maps.LatLng} The position of the marker.
*/
RichMarker.prototype.getPosition = function() {
return /** @type {google.maps.LatLng} */ (this.get('position'));
};
RichMarker.prototype['getPosition'] = RichMarker.prototype.getPosition;
/**
* Sets the position of the marker.
*
* @param {google.maps.LatLng} position The position to set.
*/
RichMarker.prototype.setPosition = function(position) {
this.set('position', position);
};
RichMarker.prototype['setPosition'] = RichMarker.prototype.setPosition;
/**
* Position changed event.
*/
RichMarker.prototype.position_changed = function() {
this.draw();
};
RichMarker.prototype['position_changed'] =
RichMarker.prototype.position_changed;
/**
* Gets the anchor.
*
* @return {google.maps.Size} The position of the anchor.
*/
RichMarker.prototype.getAnchor = function() {
return /** @type {google.maps.Size} */ (this.get('anchor'));
};
RichMarker.prototype['getAnchor'] = RichMarker.prototype.getAnchor;
/**
* Sets the anchor.
*
* @param {RichMarkerPosition|google.maps.Size} anchor The anchor to set.
*/
RichMarker.prototype.setAnchor = function(anchor) {
this.set('anchor', anchor);
};
RichMarker.prototype['setAnchor'] = RichMarker.prototype.setAnchor;
/**
* Anchor changed event.
*/
RichMarker.prototype.anchor_changed = function() {
this.draw();
};
RichMarker.prototype['anchor_changed'] = RichMarker.prototype.anchor_changed;
/**
* Converts a HTML string to a document fragment.
*
* @param {string} htmlString The HTML string to convert.
* @return {Node} A HTML document fragment.
* @private
*/
RichMarker.prototype.htmlToDocumentFragment_ = function(htmlString) {
var tempDiv = document.createElement('DIV');
tempDiv.innerHTML = htmlString;
if (tempDiv.childNodes.length == 1) {
return /** @type {!Node} */ (tempDiv.removeChild(tempDiv.firstChild));
} else {
var fragment = document.createDocumentFragment();
while (tempDiv.firstChild) {
fragment.appendChild(tempDiv.firstChild);
}
return fragment;
}
};
/**
* Removes all children from the node.
*
* @param {Node} node The node to remove all children from.
* @private
*/
RichMarker.prototype.removeChildren_ = function(node) {
if (!node) {
return;
}
var child;
while (child = node.firstChild) {
node.removeChild(child);
}
};
/**
* Sets the content of the marker.
*
* @param {string|Node} content The content to set.
*/
RichMarker.prototype.setContent = function(content) {
this.set('content', content);
};
RichMarker.prototype['setContent'] = RichMarker.prototype.setContent;
/**
* Get the content of the marker.
*
* @return {string|Node} The marker content.
*/
RichMarker.prototype.getContent = function() {
return /** @type {Node|string} */ (this.get('content'));
};
RichMarker.prototype['getContent'] = RichMarker.prototype.getContent;
/**
* Sets the marker content and adds loading events to images
*/
RichMarker.prototype.content_changed = function() {
if (!this.markerContent_) {
// Marker content area doesnt exist.
return;
}
this.removeChildren_(this.markerContent_);
var content = this.getContent();
if (content) {
if (typeof content == 'string') {
content = content.replace(/^\s*([\S\s]*)\b\s*$/, '$1');
content = this.htmlToDocumentFragment_(content);
}
this.markerContent_.appendChild(content);
var that = this;
var images = this.markerContent_.getElementsByTagName('IMG');
for (var i = 0, image; image = images[i]; i++) {
// By default, a browser lets a image be dragged outside of the browser,
// so by calling preventDefault we stop this behaviour and allow the image
// to be dragged around the map and now out of the browser and onto the
// desktop.
google.maps.event.addDomListener(image, 'mousedown', function(e) {
if (that.getDraggable()) {
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
}
});
// Because we don't know the size of an image till it loads, add a
// listener to the image load so the marker can resize and reposition
// itself to be the correct height.
google.maps.event.addDomListener(image, 'load', function() {
that.draw();
});
}
google.maps.event.trigger(this, 'domready');
}
if (this.ready_) {
this.draw();
}
};
RichMarker.prototype['content_changed'] = RichMarker.prototype.content_changed;
/**
* Sets the cursor.
*
* @param {string} whichCursor What cursor to show.
* @private
*/
RichMarker.prototype.setCursor_ = function(whichCursor) {
if (!this.ready_) {
return;
}
var cursor = '';
if (navigator.userAgent.indexOf('Gecko/') !== -1) {
// Moz has some nice cursors :)
if (whichCursor == 'dragging') {
cursor = '-moz-grabbing';
}
if (whichCursor == 'dragready') {
cursor = '-moz-grab';
}
if (whichCursor == 'draggable') {
cursor = 'pointer';
}
} else {
if (whichCursor == 'dragging' || whichCursor == 'dragready') {
cursor = 'move';
}
if (whichCursor == 'draggable') {
cursor = 'pointer';
}
}
if (this.markerWrapper_.style.cursor != cursor) {
this.markerWrapper_.style.cursor = cursor;
}
};
/**
* Start dragging.
*
* @param {Event} e The event.
*/
RichMarker.prototype.startDrag = function(e) {
if (!this.getDraggable()) {
return;
}
if (!this.dragging_) {
this.dragging_ = true;
var map = this.getMap();
this.mapDraggable_ = map.get('draggable');
map.set('draggable', false);
// Store the current mouse position
this.mouseX_ = e.clientX;
this.mouseY_ = e.clientY;
this.setCursor_('dragready');
// Stop the text from being selectable while being dragged
this.markerWrapper_.style['MozUserSelect'] = 'none';
this.markerWrapper_.style['KhtmlUserSelect'] = 'none';
this.markerWrapper_.style['WebkitUserSelect'] = 'none';
this.markerWrapper_['unselectable'] = 'on';
this.markerWrapper_['onselectstart'] = function() {
return false;
};
this.addDraggingListeners_();
google.maps.event.trigger(this, 'dragstart');
}
};
/**
* Stop dragging.
*/
RichMarker.prototype.stopDrag = function() {
if (!this.getDraggable()) {
return;
}
if (this.dragging_) {
this.dragging_ = false;
this.getMap().set('draggable', this.mapDraggable_);
this.mouseX_ = this.mouseY_ = this.mapDraggable_ = null;
// Allow the text to be selectable again
this.markerWrapper_.style['MozUserSelect'] = '';
this.markerWrapper_.style['KhtmlUserSelect'] = '';
this.markerWrapper_.style['WebkitUserSelect'] = '';
this.markerWrapper_['unselectable'] = 'off';
this.markerWrapper_['onselectstart'] = function() {};
this.removeDraggingListeners_();
this.setCursor_('draggable');
google.maps.event.trigger(this, 'dragend');
this.draw();
}
};
/**
* Handles the drag event.
*
* @param {Event} e The event.
*/
RichMarker.prototype.drag = function(e) {
if (!this.getDraggable() || !this.dragging_) {
// This object isn't draggable or we have stopped dragging
this.stopDrag();
return;
}
var dx = this.mouseX_ - e.clientX;
var dy = this.mouseY_ - e.clientY;
this.mouseX_ = e.clientX;
this.mouseY_ = e.clientY;
var left = parseInt(this.markerWrapper_.style['left'], 10) - dx;
var top = parseInt(this.markerWrapper_.style['top'], 10) - dy;
this.markerWrapper_.style['left'] = left + 'px';
this.markerWrapper_.style['top'] = top + 'px';
var offset = this.getOffset_();
// Set the position property and adjust for the anchor offset
var point = new google.maps.Point(left - offset.width, top - offset.height);
var projection = this.getProjection();
this.setPosition(projection.fromDivPixelToLatLng(point));
this.setCursor_('dragging');
google.maps.event.trigger(this, 'drag');
};
/**
* Removes the drag listeners associated with the marker.
*
* @private
*/
RichMarker.prototype.removeDragListeners_ = function() {
if (this.draggableListener_) {
google.maps.event.removeListener(this.draggableListener_);
delete this.draggableListener_;
}
this.setCursor_('');
};
/**
* Add dragability events to the marker.
*
* @param {Node} node The node to apply dragging to.
* @private
*/
RichMarker.prototype.addDragging_ = function(node) {
if (!node) {
return;
}
var that = this;
this.draggableListener_ =
google.maps.event.addDomListener(node, 'mousedown', function(e) {
that.startDrag(e);
});
this.setCursor_('draggable');
};
/**
* Add dragging listeners.
*
* @private
*/
RichMarker.prototype.addDraggingListeners_ = function() {
var that = this;
if (this.markerWrapper_.setCapture) {
this.markerWrapper_.setCapture(true);
this.draggingListeners_ = [
google.maps.event.addDomListener(this.markerWrapper_, 'mousemove', function(e) {
that.drag(e);
}, true),
google.maps.event.addDomListener(this.markerWrapper_, 'mouseup', function() {
that.stopDrag();
that.markerWrapper_.releaseCapture();
}, true)
];
} else {
this.draggingListeners_ = [
google.maps.event.addDomListener(window, 'mousemove', function(e) {
that.drag(e);
}, true),
google.maps.event.addDomListener(window, 'mouseup', function() {
that.stopDrag();
}, true)
];
}
};
/**
* Remove dragging listeners.
*
* @private
*/
RichMarker.prototype.removeDraggingListeners_ = function() {
if (this.draggingListeners_) {
for (var i = 0, listener; listener = this.draggingListeners_[i]; i++) {
google.maps.event.removeListener(listener);
}
this.draggingListeners_.length = 0;
}
};
/**
* Get the anchor offset.
*
* @return {google.maps.Size} The size offset.
* @private
*/
RichMarker.prototype.getOffset_ = function() {
var anchor = this.getAnchor();
if (typeof anchor == 'object') {
return /** @type {google.maps.Size} */ (anchor);
}
var offset = new google.maps.Size(0, 0);
if (!this.markerContent_) {
return offset;
}
var width = this.markerContent_.offsetWidth;
var height = this.markerContent_.offsetHeight;
switch (anchor) {
case RichMarkerPosition['TOP_LEFT']:
break;
case RichMarkerPosition['TOP']:
offset.width = -width / 2;
break;
case RichMarkerPosition['TOP_RIGHT']:
offset.width = -width;
break;
case RichMarkerPosition['LEFT']:
offset.height = -height / 2;
break;
case RichMarkerPosition['MIDDLE']:
offset.width = -width / 2;
offset.height = -height / 2;
break;
case RichMarkerPosition['RIGHT']:
offset.width = -width;
offset.height = -height / 2;
break;
case RichMarkerPosition['BOTTOM_LEFT']:
offset.height = -height;
break;
case RichMarkerPosition['BOTTOM']:
offset.width = -width / 2;
offset.height = -height;
break;
case RichMarkerPosition['BOTTOM_RIGHT']:
offset.width = -width;
offset.height = -height;
break;
}
return offset;
};
/**
* Adding the marker to a map.
* Implementing the interface.
*/
RichMarker.prototype.onAdd = function() {
if (!this.markerWrapper_) {
this.markerWrapper_ = document.createElement('DIV');
this.markerWrapper_.style['position'] = 'absolute';
}
if (this.getZIndex()) {
this.markerWrapper_.style['zIndex'] = this.getZIndex();
}
this.markerWrapper_.style['display'] = this.getVisible() ? '' : 'none';
if (!this.markerContent_) {
this.markerContent_ = document.createElement('DIV');
this.markerWrapper_.appendChild(this.markerContent_);
var that = this;
google.maps.event.addDomListener(this.markerContent_, 'click', function(e) {
google.maps.event.trigger(that, 'click');
});
google.maps.event.addDomListener(this.markerContent_, 'mouseover', function(e) {
google.maps.event.trigger(that, 'mouseover');
});
google.maps.event.addDomListener(this.markerContent_, 'mouseout', function(e) {
google.maps.event.trigger(that, 'mouseout');
});
}
this.ready_ = true;
this.content_changed();
this.flat_changed();
this.draggable_changed();
var panes = this.getPanes();
if (panes) {
panes.overlayMouseTarget.appendChild(this.markerWrapper_);
}
google.maps.event.trigger(this, 'ready');
};
RichMarker.prototype['onAdd'] = RichMarker.prototype.onAdd;
/**
* Impelementing the interface.
*/
RichMarker.prototype.draw = function() {
if (!this.ready_ || this.dragging_) {
return;
}
var projection = this.getProjection();
if (!projection) {
// The map projection is not ready yet so do nothing
return;
}
var latLng = /** @type {google.maps.LatLng} */ (this.get('position'));
var pos = projection.fromLatLngToDivPixel(latLng);
var offset = this.getOffset_();
this.markerWrapper_.style['top'] = (pos.y + offset.height) + 'px';
this.markerWrapper_.style['left'] = (pos.x + offset.width) + 'px';
var height = this.markerContent_.offsetHeight;
var width = this.markerContent_.offsetWidth;
if (width != this.get('width')) {
this.set('width', width);
}
if (height != this.get('height')) {
this.set('height', height);
}
};
RichMarker.prototype['draw'] = RichMarker.prototype.draw;
/**
* Removing a marker from the map.
* Implementing the interface.
*/
RichMarker.prototype.onRemove = function() {
if (this.markerWrapper_ && this.markerWrapper_.parentNode) {
this.markerWrapper_.parentNode.removeChild(this.markerWrapper_);
}
this.removeDragListeners_();
};
RichMarker.prototype['onRemove'] = RichMarker.prototype.onRemove;
/**
* RichMarker Anchor positions
* @enum {number}
*/
var RichMarkerPosition = {
'TOP_LEFT': 1,
'TOP': 2,
'TOP_RIGHT': 3,
'LEFT': 4,
'MIDDLE': 5,
'RIGHT': 6,
'BOTTOM_LEFT': 7,
'BOTTOM': 8,
'BOTTOM_RIGHT': 9
};
window['RichMarkerPosition'] = RichMarkerPosition;
//END REPLACE
window.InfoBox = InfoBox;
window.Cluster = Cluster;
window.ClusterIcon = ClusterIcon;
window.MarkerClusterer = MarkerClusterer;
window.MarkerLabel_ = MarkerLabel_;
window.MarkerWithLabel = MarkerWithLabel;
window.RichMarker = RichMarker;
})
};
});
;/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapDataStructures', function() {
return {
Graph: __webpack_require__(1).Graph,
Queue: __webpack_require__(1).Queue
};
});
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
(function() {
module.exports = {
Graph: __webpack_require__(2),
Heap: __webpack_require__(3),
LinkedList: __webpack_require__(4),
Map: __webpack_require__(5),
Queue: __webpack_require__(6),
RedBlackTree: __webpack_require__(7),
Trie: __webpack_require__(8)
};
}).call(this);
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/*
Graph implemented as a modified incidence list. O(1) for every typical
operation except `removeNode()` at O(E) where E is the number of edges.
## Overview example:
```js
var graph = new Graph;
graph.addNode('A'); // => a node object. For more info, log the output or check
// the documentation for addNode
graph.addNode('B');
graph.addNode('C');
graph.addEdge('A', 'C'); // => an edge object
graph.addEdge('A', 'B');
graph.getEdge('B', 'A'); // => undefined. Directed edge!
graph.getEdge('A', 'B'); // => the edge object previously added
graph.getEdge('A', 'B').weight = 2 // weight is the only built-in handy property
// of an edge object. Feel free to attach
// other properties
graph.getInEdgesOf('B'); // => array of edge objects, in this case only one;
// connecting A to B
graph.getOutEdgesOf('A'); // => array of edge objects, one to B and one to C
graph.getAllEdgesOf('A'); // => all the in and out edges. Edge directed toward
// the node itself are only counted once
forEachNode(function(nodeObject) {
console.log(node);
});
forEachEdge(function(edgeObject) {
console.log(edgeObject);
});
graph.removeNode('C'); // => 'C'. The edge between A and C also removed
graph.removeEdge('A', 'B'); // => the edge object removed
```
## Properties:
- nodeSize: total number of nodes.
- edgeSize: total number of edges.
*/
(function() {
var Graph,
__hasProp = {}.hasOwnProperty;
Graph = (function() {
function Graph() {
this._nodes = {};
this.nodeSize = 0;
this.edgeSize = 0;
}
Graph.prototype.addNode = function(id) {
/*
The `id` is a unique identifier for the node, and should **not** change
after it's added. It will be used for adding, retrieving and deleting
related edges too.
**Note** that, internally, the ids are kept in an object. JavaScript's
object hashes the id `'2'` and `2` to the same key, so please stick to a
simple id data type such as number or string.
_Returns:_ the node object. Feel free to attach additional custom properties
on it for graph algorithms' needs. **Undefined if node id already exists**,
as to avoid accidental overrides.
*/
if (!this._nodes[id]) {
this.nodeSize++;
return this._nodes[id] = {
_outEdges: {},
_inEdges: {}
};
}
};
Graph.prototype.getNode = function(id) {
/*
_Returns:_ the node object. Feel free to attach additional custom properties
on it for graph algorithms' needs.
*/
return this._nodes[id];
};
Graph.prototype.removeNode = function(id) {
/*
_Returns:_ the node object removed, or undefined if it didn't exist in the
first place.
*/
var inEdgeId, nodeToRemove, outEdgeId, _ref, _ref1;
nodeToRemove = this._nodes[id];
if (!nodeToRemove) {
return;
} else {
_ref = nodeToRemove._outEdges;
for (outEdgeId in _ref) {
if (!__hasProp.call(_ref, outEdgeId)) continue;
this.removeEdge(id, outEdgeId);
}
_ref1 = nodeToRemove._inEdges;
for (inEdgeId in _ref1) {
if (!__hasProp.call(_ref1, inEdgeId)) continue;
this.removeEdge(inEdgeId, id);
}
this.nodeSize--;
delete this._nodes[id];
}
return nodeToRemove;
};
Graph.prototype.addEdge = function(fromId, toId, weight) {
var edgeToAdd, fromNode, toNode;
if (weight == null) {
weight = 1;
}
/*
`fromId` and `toId` are the node id specified when it was created using
`addNode()`. `weight` is optional and defaults to 1. Ignoring it effectively
makes this an unweighted graph. Under the hood, `weight` is just a normal
property of the edge object.
_Returns:_ the edge object created. Feel free to attach additional custom
properties on it for graph algorithms' needs. **Or undefined** if the nodes
of id `fromId` or `toId` aren't found, or if an edge already exists between
the two nodes.
*/
if (this.getEdge(fromId, toId)) {
return;
}
fromNode = this._nodes[fromId];
toNode = this._nodes[toId];
if (!fromNode || !toNode) {
return;
}
edgeToAdd = {
weight: weight
};
fromNode._outEdges[toId] = edgeToAdd;
toNode._inEdges[fromId] = edgeToAdd;
this.edgeSize++;
return edgeToAdd;
};
Graph.prototype.getEdge = function(fromId, toId) {
/*
_Returns:_ the edge object, or undefined if the nodes of id `fromId` or
`toId` aren't found.
*/
var fromNode, toNode;
fromNode = this._nodes[fromId];
toNode = this._nodes[toId];
if (!fromNode || !toNode) {
} else {
return fromNode._outEdges[toId];
}
};
Graph.prototype.removeEdge = function(fromId, toId) {
/*
_Returns:_ the edge object removed, or undefined of edge wasn't found.
*/
var edgeToDelete, fromNode, toNode;
fromNode = this._nodes[fromId];
toNode = this._nodes[toId];
edgeToDelete = this.getEdge(fromId, toId);
if (!edgeToDelete) {
return;
}
delete fromNode._outEdges[toId];
delete toNode._inEdges[fromId];
this.edgeSize--;
return edgeToDelete;
};
Graph.prototype.getInEdgesOf = function(nodeId) {
/*
_Returns:_ an array of edge objects that are directed toward the node, or
empty array if no such edge or node exists.
*/
var fromId, inEdges, toNode, _ref;
toNode = this._nodes[nodeId];
inEdges = [];
_ref = toNode != null ? toNode._inEdges : void 0;
for (fromId in _ref) {
if (!__hasProp.call(_ref, fromId)) continue;
inEdges.push(this.getEdge(fromId, nodeId));
}
return inEdges;
};
Graph.prototype.getOutEdgesOf = function(nodeId) {
/*
_Returns:_ an array of edge objects that go out of the node, or empty array
if no such edge or node exists.
*/
var fromNode, outEdges, toId, _ref;
fromNode = this._nodes[nodeId];
outEdges = [];
_ref = fromNode != null ? fromNode._outEdges : void 0;
for (toId in _ref) {
if (!__hasProp.call(_ref, toId)) continue;
outEdges.push(this.getEdge(nodeId, toId));
}
return outEdges;
};
Graph.prototype.getAllEdgesOf = function(nodeId) {
/*
**Note:** not the same as concatenating `getInEdgesOf()` and
`getOutEdgesOf()`. Some nodes might have an edge pointing toward itself.
This method solves that duplication.
_Returns:_ an array of edge objects linked to the node, no matter if they're
outgoing or coming. Duplicate edge created by self-pointing nodes are
removed. Only one copy stays. Empty array if node has no edge.
*/
var i, inEdges, outEdges, selfEdge, _i, _ref, _ref1;
inEdges = this.getInEdgesOf(nodeId);
outEdges = this.getOutEdgesOf(nodeId);
if (inEdges.length === 0) {
return outEdges;
}
selfEdge = this.getEdge(nodeId, nodeId);
for (i = _i = 0, _ref = inEdges.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
if (inEdges[i] === selfEdge) {
_ref1 = [inEdges[inEdges.length - 1], inEdges[i]], inEdges[i] = _ref1[0], inEdges[inEdges.length - 1] = _ref1[1];
inEdges.pop();
break;
}
}
return inEdges.concat(outEdges);
};
Graph.prototype.forEachNode = function(operation) {
/*
Traverse through the graph in an arbitrary manner, visiting each node once.
Pass a function of the form `fn(nodeObject, nodeId)`.
_Returns:_ undefined.
*/
var nodeId, nodeObject, _ref;
_ref = this._nodes;
for (nodeId in _ref) {
if (!__hasProp.call(_ref, nodeId)) continue;
nodeObject = _ref[nodeId];
operation(nodeObject, nodeId);
}
};
Graph.prototype.forEachEdge = function(operation) {
/*
Traverse through the graph in an arbitrary manner, visiting each edge once.
Pass a function of the form `fn(edgeObject)`.
_Returns:_ undefined.
*/
var edgeObject, nodeId, nodeObject, toId, _ref, _ref1;
_ref = this._nodes;
for (nodeId in _ref) {
if (!__hasProp.call(_ref, nodeId)) continue;
nodeObject = _ref[nodeId];
_ref1 = nodeObject._outEdges;
for (toId in _ref1) {
if (!__hasProp.call(_ref1, toId)) continue;
edgeObject = _ref1[toId];
operation(edgeObject);
}
}
};
return Graph;
})();
module.exports = Graph;
}).call(this);
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
/*
Minimum heap, i.e. smallest node at root.
**Note:** does not accept null or undefined. This is by design. Those values
cause comparison problems and might report false negative during extraction.
## Overview example:
```js
var heap = new Heap([5, 6, 3, 4]);
heap.add(10); // => 10
heap.removeMin(); // => 3
heap.peekMin(); // => 4
```
## Properties:
- size: total number of items.
*/
(function() {
var Heap, _leftChild, _parent, _rightChild;
Heap = (function() {
function Heap(dataToHeapify) {
var i, item, _i, _j, _len, _ref;
if (dataToHeapify == null) {
dataToHeapify = [];
}
/*
Pass an optional array to be heapified. Takes only O(n) time.
*/
this._data = [void 0];
for (_i = 0, _len = dataToHeapify.length; _i < _len; _i++) {
item = dataToHeapify[_i];
if (item != null) {
this._data.push(item);
}
}
if (this._data.length > 1) {
for (i = _j = 2, _ref = this._data.length; 2 <= _ref ? _j < _ref : _j > _ref; i = 2 <= _ref ? ++_j : --_j) {
this._upHeap(i);
}
}
this.size = this._data.length - 1;
}
Heap.prototype.add = function(value) {
/*
**Remember:** rejects null and undefined for mentioned reasons.
_Returns:_ the value added.
*/
if (value == null) {
return;
}
this._data.push(value);
this._upHeap(this._data.length - 1);
this.size++;
return value;
};
Heap.prototype.removeMin = function() {
/*
_Returns:_ the smallest item (the root).
*/
var min;
if (this._data.length === 1) {
return;
}
this.size--;
if (this._data.length === 2) {
return this._data.pop();
}
min = this._data[1];
this._data[1] = this._data.pop();
this._downHeap();
return min;
};
Heap.prototype.peekMin = function() {
/*
Check the smallest item without removing it.
_Returns:_ the smallest item (the root).
*/
return this._data[1];
};
Heap.prototype._upHeap = function(index) {
var valueHolder, _ref;
valueHolder = this._data[index];
while (this._data[index] < this._data[_parent(index)] && index > 1) {
_ref = [this._data[_parent(index)], this._data[index]], this._data[index] = _ref[0], this._data[_parent(index)] = _ref[1];
index = _parent(index);
}
};
Heap.prototype._downHeap = function() {
var currentIndex, smallerChildIndex, _ref;
currentIndex = 1;
while (_leftChild(currentIndex < this._data.length)) {
smallerChildIndex = _leftChild(currentIndex);
if (smallerChildIndex < this._data.length - 1) {
if (this._data[_rightChild(currentIndex)] < this._data[smallerChildIndex]) {
smallerChildIndex = _rightChild(currentIndex);
}
}
if (this._data[smallerChildIndex] < this._data[currentIndex]) {
_ref = [this._data[currentIndex], this._data[smallerChildIndex]], this._data[smallerChildIndex] = _ref[0], this._data[currentIndex] = _ref[1];
currentIndex = smallerChildIndex;
} else {
break;
}
}
};
return Heap;
})();
_parent = function(index) {
return index >> 1;
};
_leftChild = function(index) {
return index << 1;
};
_rightChild = function(index) {
return (index << 1) + 1;
};
module.exports = Heap;
}).call(this);
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/*
Doubly Linked.
## Overview example:
```js
var list = new LinkedList([5, 4, 9]);
list.add(12); // => 12
list.head.next.value; // => 4
list.tail.value; // => 12
list.at(-1); // => 12
list.removeAt(2); // => 9
list.remove(4); // => 4
list.indexOf(5); // => 0
list.add(5, 1); // => 5. Second 5 at position 1.
list.indexOf(5, 1); // => 1
```
## Properties:
- head: first item.
- tail: last item.
- size: total number of items.
- item.value: value passed to the item when calling `add()`.
- item.prev: previous item.
- item.next: next item.
*/
(function() {
var LinkedList;
LinkedList = (function() {
function LinkedList(valuesToAdd) {
var value, _i, _len;
if (valuesToAdd == null) {
valuesToAdd = [];
}
/*
Can pass an array of elements to link together during `new LinkedList()`
initiation.
*/
this.head = {
prev: void 0,
value: void 0,
next: void 0
};
this.tail = {
prev: void 0,
value: void 0,
next: void 0
};
this.size = 0;
for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) {
value = valuesToAdd[_i];
this.add(value);
}
}
LinkedList.prototype.at = function(position) {
/*
Get the item at `position` (optional). Accepts negative index:
```js
myList.at(-1); // Returns the last element.
```
However, passing a negative index that surpasses the boundary will return
undefined:
```js
myList = new LinkedList([2, 6, 8, 3])
myList.at(-5); // Undefined.
myList.at(-4); // 2.
```
_Returns:_ item gotten, or undefined if not found.
*/
var currentNode, i, _i, _j, _ref;
if (!((-this.size <= position && position < this.size))) {
return;
}
position = this._adjust(position);
if (position * 2 < this.size) {
currentNode = this.head;
for (i = _i = 1; _i <= position; i = _i += 1) {
currentNode = currentNode.next;
}
} else {
currentNode = this.tail;
for (i = _j = 1, _ref = this.size - position - 1; _j <= _ref; i = _j += 1) {
currentNode = currentNode.prev;
}
}
return currentNode;
};
LinkedList.prototype.add = function(value, position) {
var currentNode, nodeToAdd, _ref, _ref1, _ref2;
if (position == null) {
position = this.size;
}
/*
Add a new item at `position` (optional). Defaults to adding at the end.
`position`, just like in `at()`, can be negative (within the negative
boundary). Position specifies the place the value's going to be, and the old
node will be pushed higher. `add(-2)` on list of size 7 is the same as
`add(5)`.
_Returns:_ item added.
*/
if (!((-this.size <= position && position <= this.size))) {
return;
}
nodeToAdd = {
value: value
};
position = this._adjust(position);
if (this.size === 0) {
this.head = nodeToAdd;
} else {
if (position === 0) {
_ref = [nodeToAdd, this.head, nodeToAdd], this.head.prev = _ref[0], nodeToAdd.next = _ref[1], this.head = _ref[2];
} else {
currentNode = this.at(position - 1);
_ref1 = [currentNode.next, nodeToAdd, nodeToAdd, currentNode], nodeToAdd.next = _ref1[0], (_ref2 = currentNode.next) != null ? _ref2.prev = _ref1[1] : void 0, currentNode.next = _ref1[2], nodeToAdd.prev = _ref1[3];
}
}
if (position === this.size) {
this.tail = nodeToAdd;
}
this.size++;
return value;
};
LinkedList.prototype.removeAt = function(position) {
var currentNode, valueToReturn, _ref;
if (position == null) {
position = this.size - 1;
}
/*
Remove an item at index `position` (optional). Defaults to the last item.
Index can be negative (within the boundary).
_Returns:_ item removed.
*/
if (!((-this.size <= position && position < this.size))) {
return;
}
if (this.size === 0) {
return;
}
position = this._adjust(position);
if (this.size === 1) {
valueToReturn = this.head.value;
this.head.value = this.tail.value = void 0;
} else {
if (position === 0) {
valueToReturn = this.head.value;
this.head = this.head.next;
this.head.prev = void 0;
} else {
currentNode = this.at(position);
valueToReturn = currentNode.value;
currentNode.prev.next = currentNode.next;
if ((_ref = currentNode.next) != null) {
_ref.prev = currentNode.prev;
}
if (position === this.size - 1) {
this.tail = currentNode.prev;
}
}
}
this.size--;
return valueToReturn;
};
LinkedList.prototype.remove = function(value) {
/*
Remove the item using its value instead of position. **Will remove the fist
occurrence of `value`.**
_Returns:_ the value, or undefined if value's not found.
*/
var currentNode;
if (value == null) {
return;
}
currentNode = this.head;
while (currentNode && currentNode.value !== value) {
currentNode = currentNode.next;
}
if (!currentNode) {
return;
}
if (this.size === 1) {
this.head.value = this.tail.value = void 0;
} else if (currentNode === this.head) {
this.head = this.head.next;
this.head.prev = void 0;
} else if (currentNode === this.tail) {
this.tail = this.tail.prev;
this.tail.next = void 0;
} else {
currentNode.prev.next = currentNode.next;
currentNode.next.prev = currentNode.prev;
}
this.size--;
return value;
};
LinkedList.prototype.indexOf = function(value, startingPosition) {
var currentNode, position;
if (startingPosition == null) {
startingPosition = 0;
}
/*
Find the index of an item, similarly to `array.indexOf()`. Defaults to start
searching from the beginning, by can start at another position by passing
`startingPosition`. This parameter can also be negative; but unlike the
other methods of this class, `startingPosition` (optional) can be as small
as desired; a value of -999 for a list of size 5 will start searching
normally, at the beginning.
**Note:** searches forwardly, **not** backwardly, i.e:
```js
var myList = new LinkedList([2, 3, 1, 4, 3, 5])
myList.indexOf(3, -3); // Returns 4, not 1
```
_Returns:_ index of item found, or -1 if not found.
*/
if (((this.head.value == null) && !this.head.next) || startingPosition >= this.size) {
return -1;
}
startingPosition = Math.max(0, this._adjust(startingPosition));
currentNode = this.at(startingPosition);
position = startingPosition;
while (currentNode) {
if (currentNode.value === value) {
break;
}
currentNode = currentNode.next;
position++;
}
if (position === this.size) {
return -1;
} else {
return position;
}
};
LinkedList.prototype._adjust = function(position) {
if (position < 0) {
return this.size + position;
} else {
return position;
}
};
return LinkedList;
})();
module.exports = LinkedList;
}).call(this);
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
/*
Kind of a stopgap measure for the upcoming [JavaScript
Map](http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets)
**Note:** due to JavaScript's limitations, hashing something other than Boolean,
Number, String, Undefined, Null, RegExp, Function requires a hack that inserts a
hidden unique property into the object. This means `set`, `get`, `has` and
`delete` must employ the same object, and not a mere identical copy as in the
case of, say, a string.
## Overview example:
```js
var map = new Map({'alice': 'wonderland', 20: 'ok'});
map.set('20', 5); // => 5
map.get('20'); // => 5
map.has('alice'); // => true
map.delete(20) // => true
var arr = [1, 2];
map.add(arr, 'goody'); // => 'goody'
map.has(arr); // => true
map.has([1, 2]); // => false. Needs to compare by reference
map.forEach(function(key, value) {
console.log(key, value);
});
```
## Properties:
- size: The total number of `(key, value)` pairs.
*/
(function() {
var Map, SPECIAL_TYPE_KEY_PREFIX, _extractDataType, _isSpecialType,
__hasProp = {}.hasOwnProperty;
SPECIAL_TYPE_KEY_PREFIX = '_mapId_';
Map = (function() {
Map._mapIdTracker = 0;
Map._newMapId = function() {
return this._mapIdTracker++;
};
function Map(objectToMap) {
/*
Pass an optional object whose (key, value) pair will be hashed. **Careful**
not to pass something like {5: 'hi', '5': 'hello'}, since JavaScript's
native object behavior will crush the first 5 property before it gets to
constructor.
*/
var key, value;
this._content = {};
this._itemId = 0;
this._id = Map._newMapId();
this.size = 0;
for (key in objectToMap) {
if (!__hasProp.call(objectToMap, key)) continue;
value = objectToMap[key];
this.set(key, value);
}
}
Map.prototype.hash = function(key, makeHash) {
var propertyForMap, type;
if (makeHash == null) {
makeHash = false;
}
/*
The hash function for hashing keys is public. Feel free to replace it with
your own. The `makeHash` parameter is optional and accepts a boolean
(defaults to `false`) indicating whether or not to produce a new hash (for
the first use, naturally).
_Returns:_ the hash.
*/
type = _extractDataType(key);
if (_isSpecialType(key)) {
propertyForMap = SPECIAL_TYPE_KEY_PREFIX + this._id;
if (makeHash && !key[propertyForMap]) {
key[propertyForMap] = this._itemId++;
}
return propertyForMap + '_' + key[propertyForMap];
} else {
return type + '_' + key;
}
};
Map.prototype.set = function(key, value) {
/*
_Returns:_ value.
*/
if (!this.has(key)) {
this.size++;
}
this._content[this.hash(key, true)] = [value, key];
return value;
};
Map.prototype.get = function(key) {
/*
_Returns:_ value corresponding to the key, or undefined if not found.
*/
var _ref;
return (_ref = this._content[this.hash(key)]) != null ? _ref[0] : void 0;
};
Map.prototype.has = function(key) {
/*
Check whether a value exists for the key.
_Returns:_ true or false.
*/
return this.hash(key) in this._content;
};
Map.prototype["delete"] = function(key) {
/*
Remove the (key, value) pair.
_Returns:_ **true or false**. Unlike most of this library, this method
doesn't return the deleted value. This is so that it conforms to the future
JavaScript `map.delete()`'s behavior.
*/
var hashedKey;
hashedKey = this.hash(key);
if (hashedKey in this._content) {
delete this._content[hashedKey];
if (_isSpecialType(key)) {
delete key[SPECIAL_TYPE_KEY_PREFIX + this._id];
}
this.size--;
return true;
}
return false;
};
Map.prototype.forEach = function(operation) {
/*
Traverse through the map. Pass a function of the form `fn(key, value)`.
_Returns:_ undefined.
*/
var key, value, _ref;
_ref = this._content;
for (key in _ref) {
if (!__hasProp.call(_ref, key)) continue;
value = _ref[key];
operation(value[1], value[0]);
}
};
return Map;
})();
_isSpecialType = function(key) {
var simpleHashableTypes, simpleType, type, _i, _len;
simpleHashableTypes = ['Boolean', 'Number', 'String', 'Undefined', 'Null', 'RegExp', 'Function'];
type = _extractDataType(key);
for (_i = 0, _len = simpleHashableTypes.length; _i < _len; _i++) {
simpleType = simpleHashableTypes[_i];
if (type === simpleType) {
return false;
}
}
return true;
};
_extractDataType = function(type) {
return Object.prototype.toString.apply(type).match(/\[object (.+)\]/)[1];
};
module.exports = Map;
}).call(this);
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/*
Amortized O(1) dequeue!
## Overview example:
```js
var queue = new Queue([1, 6, 4]);
queue.enqueue(10); // => 10
queue.dequeue(); // => 1
queue.dequeue(); // => 6
queue.dequeue(); // => 4
queue.peek(); // => 10
queue.dequeue(); // => 10
queue.peek(); // => undefined
```
## Properties:
- size: The total number of items.
*/
(function() {
var Queue;
Queue = (function() {
function Queue(initialArray) {
if (initialArray == null) {
initialArray = [];
}
/*
Pass an optional array to be transformed into a queue. The item at index 0
is the first to be dequeued.
*/
this._content = initialArray;
this._dequeueIndex = 0;
this.size = this._content.length;
}
Queue.prototype.enqueue = function(item) {
/*
_Returns:_ the item.
*/
this.size++;
this._content.push(item);
return item;
};
Queue.prototype.dequeue = function() {
/*
_Returns:_ the dequeued item.
*/
var itemToDequeue;
if (this.size === 0) {
return;
}
this.size--;
itemToDequeue = this._content[this._dequeueIndex];
this._dequeueIndex++;
if (this._dequeueIndex * 2 > this._content.length) {
this._content = this._content.slice(this._dequeueIndex);
this._dequeueIndex = 0;
}
return itemToDequeue;
};
Queue.prototype.peek = function() {
/*
Check the next item to be dequeued, without removing it.
_Returns:_ the item.
*/
return this._content[this._dequeueIndex];
};
return Queue;
})();
module.exports = Queue;
}).call(this);
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
/*
Credit to Wikipedia's article on [Red-black
tree](http://en.wikipedia.org/wiki/Red–black_tree)
**Note:** doesn't handle duplicate entries, undefined and null. This is by
design.
## Overview example:
```js
var rbt = new RedBlackTree([7, 5, 1, 8]);
rbt.add(2); // => 2
rbt.add(10); // => 10
rbt.has(5); // => true
rbt.peekMin(); // => 1
rbt.peekMax(); // => 10
rbt.removeMin(); // => 1
rbt.removeMax(); // => 10
rbt.remove(8); // => 8
```
## Properties:
- size: The total number of items.
*/
(function() {
var BLACK, NODE_FOUND, NODE_TOO_BIG, NODE_TOO_SMALL, RED, RedBlackTree, STOP_SEARCHING, _findNode, _grandParentOf, _isLeft, _leftOrRight, _peekMaxNode, _peekMinNode, _siblingOf, _uncleOf;
NODE_FOUND = 0;
NODE_TOO_BIG = 1;
NODE_TOO_SMALL = 2;
STOP_SEARCHING = 3;
RED = 1;
BLACK = 2;
RedBlackTree = (function() {
function RedBlackTree(valuesToAdd) {
var value, _i, _len;
if (valuesToAdd == null) {
valuesToAdd = [];
}
/*
Pass an optional array to be turned into binary tree. **Note:** does not
accept duplicate, undefined and null.
*/
this._root;
this.size = 0;
for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) {
value = valuesToAdd[_i];
if (value != null) {
this.add(value);
}
}
}
RedBlackTree.prototype.add = function(value) {
/*
Again, make sure to not pass a value already in the tree, or undefined, or
null.
_Returns:_ value added.
*/
var currentNode, foundNode, nodeToInsert, _ref;
if (value == null) {
return;
}
this.size++;
nodeToInsert = {
value: value,
_color: RED
};
if (!this._root) {
this._root = nodeToInsert;
} else {
foundNode = _findNode(this._root, function(node) {
if (value === node.value) {
return NODE_FOUND;
} else {
if (value < node.value) {
if (node._left) {
return NODE_TOO_BIG;
} else {
nodeToInsert._parent = node;
node._left = nodeToInsert;
return STOP_SEARCHING;
}
} else {
if (node._right) {
return NODE_TOO_SMALL;
} else {
nodeToInsert._parent = node;
node._right = nodeToInsert;
return STOP_SEARCHING;
}
}
}
});
if (foundNode != null) {
return;
}
}
currentNode = nodeToInsert;
while (true) {
if (currentNode === this._root) {
currentNode._color = BLACK;
break;
}
if (currentNode._parent._color === BLACK) {
break;
}
if (((_ref = _uncleOf(currentNode)) != null ? _ref._color : void 0) === RED) {
currentNode._parent._color = BLACK;
_uncleOf(currentNode)._color = BLACK;
_grandParentOf(currentNode)._color = RED;
currentNode = _grandParentOf(currentNode);
continue;
}
if (!_isLeft(currentNode) && _isLeft(currentNode._parent)) {
this._rotateLeft(currentNode._parent);
currentNode = currentNode._left;
} else if (_isLeft(currentNode) && !_isLeft(currentNode._parent)) {
this._rotateRight(currentNode._parent);
currentNode = currentNode._right;
}
currentNode._parent._color = BLACK;
_grandParentOf(currentNode)._color = RED;
if (_isLeft(currentNode)) {
this._rotateRight(_grandParentOf(currentNode));
} else {
this._rotateLeft(_grandParentOf(currentNode));
}
break;
}
return value;
};
RedBlackTree.prototype.has = function(value) {
/*
_Returns:_ true or false.
*/
var foundNode;
foundNode = _findNode(this._root, function(node) {
if (value === node.value) {
return NODE_FOUND;
} else if (value < node.value) {
return NODE_TOO_BIG;
} else {
return NODE_TOO_SMALL;
}
});
if (foundNode) {
return true;
} else {
return false;
}
};
RedBlackTree.prototype.peekMin = function() {
/*
Check the minimum value without removing it.
_Returns:_ the minimum value.
*/
var _ref;
return (_ref = _peekMinNode(this._root)) != null ? _ref.value : void 0;
};
RedBlackTree.prototype.peekMax = function() {
/*
Check the maximum value without removing it.
_Returns:_ the maximum value.
*/
var _ref;
return (_ref = _peekMaxNode(this._root)) != null ? _ref.value : void 0;
};
RedBlackTree.prototype.remove = function(value) {
/*
_Returns:_ the value removed, or undefined if the value's not found.
*/
var foundNode;
foundNode = _findNode(this._root, function(node) {
if (value === node.value) {
return NODE_FOUND;
} else if (value < node.value) {
return NODE_TOO_BIG;
} else {
return NODE_TOO_SMALL;
}
});
if (!foundNode) {
return;
}
this._removeNode(this._root, foundNode);
this.size--;
return value;
};
RedBlackTree.prototype.removeMin = function() {
/*
_Returns:_ smallest item removed, or undefined if tree's empty.
*/
var nodeToRemove, valueToReturn;
nodeToRemove = _peekMinNode(this._root);
if (!nodeToRemove) {
return;
}
valueToReturn = nodeToRemove.value;
this._removeNode(this._root, nodeToRemove);
return valueToReturn;
};
RedBlackTree.prototype.removeMax = function() {
/*
_Returns:_ biggest item removed, or undefined if tree's empty.
*/
var nodeToRemove, valueToReturn;
nodeToRemove = _peekMaxNode(this._root);
if (!nodeToRemove) {
return;
}
valueToReturn = nodeToRemove.value;
this._removeNode(this._root, nodeToRemove);
return valueToReturn;
};
RedBlackTree.prototype._removeNode = function(root, node) {
var sibling, successor, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
if (node._left && node._right) {
successor = _peekMinNode(node._right);
node.value = successor.value;
node = successor;
}
successor = node._left || node._right;
if (!successor) {
successor = {
color: BLACK,
_right: void 0,
_left: void 0,
isLeaf: true
};
}
successor._parent = node._parent;
if ((_ref = node._parent) != null) {
_ref[_leftOrRight(node)] = successor;
}
if (node._color === BLACK) {
if (successor._color === RED) {
successor._color = BLACK;
if (!successor._parent) {
this._root = successor;
}
} else {
while (true) {
if (!successor._parent) {
if (!successor.isLeaf) {
this._root = successor;
} else {
this._root = void 0;
}
break;
}
sibling = _siblingOf(successor);
if ((sibling != null ? sibling._color : void 0) === RED) {
successor._parent._color = RED;
sibling._color = BLACK;
if (_isLeft(successor)) {
this._rotateLeft(successor._parent);
} else {
this._rotateRight(successor._parent);
}
}
sibling = _siblingOf(successor);
if (successor._parent._color === BLACK && (!sibling || (sibling._color === BLACK && (!sibling._left || sibling._left._color === BLACK) && (!sibling._right || sibling._right._color === BLACK)))) {
if (sibling != null) {
sibling._color = RED;
}
if (successor.isLeaf) {
successor._parent[_leftOrRight(successor)] = void 0;
}
successor = successor._parent;
continue;
}
if (successor._parent._color === RED && (!sibling || (sibling._color === BLACK && (!sibling._left || ((_ref1 = sibling._left) != null ? _ref1._color : void 0) === BLACK) && (!sibling._right || ((_ref2 = sibling._right) != null ? _ref2._color : void 0) === BLACK)))) {
if (sibling != null) {
sibling._color = RED;
}
successor._parent._color = BLACK;
break;
}
if ((sibling != null ? sibling._color : void 0) === BLACK) {
if (_isLeft(successor) && (!sibling._right || sibling._right._color === BLACK) && ((_ref3 = sibling._left) != null ? _ref3._color : void 0) === RED) {
sibling._color = RED;
if ((_ref4 = sibling._left) != null) {
_ref4._color = BLACK;
}
this._rotateRight(sibling);
} else if (!_isLeft(successor) && (!sibling._left || sibling._left._color === BLACK) && ((_ref5 = sibling._right) != null ? _ref5._color : void 0) === RED) {
sibling._color = RED;
if ((_ref6 = sibling._right) != null) {
_ref6._color = BLACK;
}
this._rotateLeft(sibling);
}
break;
}
sibling = _siblingOf(successor);
sibling._color = successor._parent._color;
if (_isLeft(successor)) {
sibling._right._color = BLACK;
this._rotateRight(successor._parent);
} else {
sibling._left._color = BLACK;
this._rotateLeft(successor._parent);
}
}
}
}
if (successor.isLeaf) {
return (_ref7 = successor._parent) != null ? _ref7[_leftOrRight(successor)] = void 0 : void 0;
}
};
RedBlackTree.prototype._rotateLeft = function(node) {
var _ref, _ref1;
if ((_ref = node._parent) != null) {
_ref[_leftOrRight(node)] = node._right;
}
node._right._parent = node._parent;
node._parent = node._right;
node._right = node._right._left;
node._parent._left = node;
if ((_ref1 = node._right) != null) {
_ref1._parent = node;
}
if (node._parent._parent == null) {
return this._root = node._parent;
}
};
RedBlackTree.prototype._rotateRight = function(node) {
var _ref, _ref1;
if ((_ref = node._parent) != null) {
_ref[_leftOrRight(node)] = node._left;
}
node._left._parent = node._parent;
node._parent = node._left;
node._left = node._left._right;
node._parent._right = node;
if ((_ref1 = node._left) != null) {
_ref1._parent = node;
}
if (node._parent._parent == null) {
return this._root = node._parent;
}
};
return RedBlackTree;
})();
_isLeft = function(node) {
return node === node._parent._left;
};
_leftOrRight = function(node) {
if (_isLeft(node)) {
return '_left';
} else {
return '_right';
}
};
_findNode = function(startingNode, comparator) {
var comparisonResult, currentNode, foundNode;
currentNode = startingNode;
foundNode = void 0;
while (currentNode) {
comparisonResult = comparator(currentNode);
if (comparisonResult === NODE_FOUND) {
foundNode = currentNode;
break;
}
if (comparisonResult === NODE_TOO_BIG) {
currentNode = currentNode._left;
} else if (comparisonResult === NODE_TOO_SMALL) {
currentNode = currentNode._right;
} else if (comparisonResult === STOP_SEARCHING) {
break;
}
}
return foundNode;
};
_peekMinNode = function(startingNode) {
return _findNode(startingNode, function(node) {
if (node._left) {
return NODE_TOO_BIG;
} else {
return NODE_FOUND;
}
});
};
_peekMaxNode = function(startingNode) {
return _findNode(startingNode, function(node) {
if (node._right) {
return NODE_TOO_SMALL;
} else {
return NODE_FOUND;
}
});
};
_grandParentOf = function(node) {
var _ref;
return (_ref = node._parent) != null ? _ref._parent : void 0;
};
_uncleOf = function(node) {
if (!_grandParentOf(node)) {
return;
}
if (_isLeft(node._parent)) {
return _grandParentOf(node)._right;
} else {
return _grandParentOf(node)._left;
}
};
_siblingOf = function(node) {
if (_isLeft(node)) {
return node._parent._right;
} else {
return node._parent._left;
}
};
module.exports = RedBlackTree;
}).call(this);
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
/*
Good for fast insertion/removal/lookup of strings.
## Overview example:
```js
var trie = new Trie(['bear', 'beer']);
trie.add('hello'); // => 'hello'
trie.add('helloha!'); // => 'helloha!'
trie.has('bears'); // => false
trie.longestPrefixOf('beatrice'); // => 'bea'
trie.wordsWithPrefix('hel'); // => ['hello', 'helloha!']
trie.remove('beers'); // => undefined. 'beer' still exists
trie.remove('Beer') // => undefined. Case-sensitive
trie.remove('beer') // => 'beer'. Removed
```
## Properties:
- size: The total number of words.
*/
(function() {
var Queue, Trie, WORD_END, _hasAtLeastNChildren,
__hasProp = {}.hasOwnProperty;
Queue = __webpack_require__(6);
WORD_END = 'end';
Trie = (function() {
function Trie(words) {
var word, _i, _len;
if (words == null) {
words = [];
}
/*
Pass an optional array of strings to be inserted initially.
*/
this._root = {};
this.size = 0;
for (_i = 0, _len = words.length; _i < _len; _i++) {
word = words[_i];
this.add(word);
}
}
Trie.prototype.add = function(word) {
/*
Add a whole string to the trie.
_Returns:_ the word added. Will return undefined (without adding the value)
if the word passed is null or undefined.
*/
var currentNode, letter, _i, _len;
if (word == null) {
return;
}
this.size++;
currentNode = this._root;
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
currentNode[letter] = {};
}
currentNode = currentNode[letter];
}
currentNode[WORD_END] = true;
return word;
};
Trie.prototype.has = function(word) {
/*
__Returns:_ true or false.
*/
var currentNode, letter, _i, _len;
if (word == null) {
return false;
}
currentNode = this._root;
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
return false;
}
currentNode = currentNode[letter];
}
if (currentNode[WORD_END]) {
return true;
} else {
return false;
}
};
Trie.prototype.longestPrefixOf = function(word) {
/*
Find all words containing the prefix. The word itself counts as a prefix.
```js
var trie = new Trie;
trie.add('hello');
trie.longestPrefixOf('he'); // 'he'
trie.longestPrefixOf('hello'); // 'hello'
trie.longestPrefixOf('helloha!'); // 'hello'
```
_Returns:_ the prefix string, or empty string if no prefix found.
*/
var currentNode, letter, prefix, _i, _len;
if (word == null) {
return '';
}
currentNode = this._root;
prefix = '';
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
break;
}
prefix += letter;
currentNode = currentNode[letter];
}
return prefix;
};
Trie.prototype.wordsWithPrefix = function(prefix) {
/*
Find all words containing the prefix. The word itself counts as a prefix.
**Watch out for edge cases.**
```js
var trie = new Trie;
trie.wordsWithPrefix(''); // []. Check later case below.
trie.add('');
trie.wordsWithPrefix(''); // ['']
trie.add('he');
trie.add('hello');
trie.add('hell');
trie.add('bear');
trie.add('z');
trie.add('zebra');
trie.wordsWithPrefix('hel'); // ['hell', 'hello']
```
_Returns:_ an array of strings, or empty array if no word found.
*/
var accumulatedLetters, currentNode, letter, node, queue, subNode, words, _i, _len, _ref;
if (prefix == null) {
return [];
}
(prefix != null) || (prefix = '');
words = [];
currentNode = this._root;
for (_i = 0, _len = prefix.length; _i < _len; _i++) {
letter = prefix[_i];
currentNode = currentNode[letter];
if (currentNode == null) {
return [];
}
}
queue = new Queue();
queue.enqueue([currentNode, '']);
while (queue.size !== 0) {
_ref = queue.dequeue(), node = _ref[0], accumulatedLetters = _ref[1];
if (node[WORD_END]) {
words.push(prefix + accumulatedLetters);
}
for (letter in node) {
if (!__hasProp.call(node, letter)) continue;
subNode = node[letter];
queue.enqueue([subNode, accumulatedLetters + letter]);
}
}
return words;
};
Trie.prototype.remove = function(word) {
/*
_Returns:_ the string removed, or undefined if the word in its whole doesn't
exist. **Note:** this means removing `beers` when only `beer` exists will
return undefined and conserve `beer`.
*/
var currentNode, i, letter, prefix, _i, _j, _len, _ref;
if (word == null) {
return;
}
currentNode = this._root;
prefix = [];
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
return;
}
currentNode = currentNode[letter];
prefix.push([letter, currentNode]);
}
if (!currentNode[WORD_END]) {
return;
}
this.size--;
delete currentNode[WORD_END];
if (_hasAtLeastNChildren(currentNode, 1)) {
return word;
}
for (i = _j = _ref = prefix.length - 1; _ref <= 1 ? _j <= 1 : _j >= 1; i = _ref <= 1 ? ++_j : --_j) {
if (!_hasAtLeastNChildren(prefix[i][1], 1)) {
delete prefix[i - 1][1][prefix[i][0]];
} else {
break;
}
}
if (!_hasAtLeastNChildren(this._root[prefix[0][0]], 1)) {
delete this._root[prefix[0][0]];
}
return word;
};
return Trie;
})();
_hasAtLeastNChildren = function(node, n) {
var child, childCount;
if (n === 0) {
return true;
}
childCount = 0;
for (child in node) {
if (!__hasProp.call(node, child)) continue;
childCount++;
if (childCount >= n) {
return true;
}
}
return false;
};
module.exports = Trie;
}).call(this);
/***/ }
/******/ ]);;/**
* Performance overrides on MarkerClusterer custom to Angular Google Maps
*
* Created by Petr Bruna ccg1415 and Nick McCready on 7/13/14.
*/
angular.module('uiGmapgoogle-maps.extensions')
.service('uiGmapExtendMarkerClusterer',['uiGmapLodash', 'uiGmapPropMap', function (uiGmapLodash, PropMap) {
return {
init: _.once(function () {
(function () {
var __hasProp = {}.hasOwnProperty,
__extends = function (child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
window.NgMapCluster = (function (_super) {
__extends(NgMapCluster, _super);
function NgMapCluster(opts) {
NgMapCluster.__super__.constructor.call(this, opts);
this.markers_ = new PropMap();
}
/**
* Adds a marker to the cluster.
*
* @param {google.maps.Marker} marker The marker to be added.
* @return {boolean} True if the marker was added.
* @ignore
*/
NgMapCluster.prototype.addMarker = function (marker) {
var i;
var mCount;
var mz;
if (this.isMarkerAlreadyAdded_(marker)) {
var oldMarker = this.markers_.get(marker.key);
if (oldMarker.getPosition().lat() == marker.getPosition().lat() && oldMarker.getPosition().lon() == marker.getPosition().lon()) //if nothing has changed
return false;
}
if (!this.center_) {
this.center_ = marker.getPosition();
this.calculateBounds_();
} else {
if (this.averageCenter_) {
var l = this.markers_.length + 1;
var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;
var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;
this.center_ = new google.maps.LatLng(lat, lng);
this.calculateBounds_();
}
}
marker.isAdded = true;
this.markers_.push(marker);
mCount = this.markers_.length;
mz = this.markerClusterer_.getMaxZoom();
if (mz !== null && this.map_.getZoom() > mz) {
// Zoomed in past max zoom, so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount < this.minClusterSize_) {
// Min cluster size not reached so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount === this.minClusterSize_) {
// Hide the markers that were showing.
this.markers_.each(function (m) {
m.setMap(null);
});
} else {
marker.setMap(null);
}
//this.updateIcon_();
return true;
};
/**
* Determines if a marker has already been added to the cluster.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker has already been added.
*/
NgMapCluster.prototype.isMarkerAlreadyAdded_ = function (marker) {
return uiGmapLodash.isNullOrUndefined(this.markers_.get(marker.key));
};
/**
* Returns the bounds of the cluster.
*
* @return {google.maps.LatLngBounds} the cluster bounds.
* @ignore
*/
NgMapCluster.prototype.getBounds = function () {
var i;
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
this.getMarkers().each(function(m){
bounds.extend(m.getPosition());
});
return bounds;
};
/**
* Removes the cluster from the map.
*
* @ignore
*/
NgMapCluster.prototype.remove = function () {
this.clusterIcon_.setMap(null);
this.markers_ = new PropMap();
delete this.markers_;
};
return NgMapCluster;
})(Cluster);
window.NgMapMarkerClusterer = (function (_super) {
__extends(NgMapMarkerClusterer, _super);
function NgMapMarkerClusterer(map, opt_markers, opt_options) {
NgMapMarkerClusterer.__super__.constructor.call(this, map, opt_markers, opt_options);
this.markers_ = new PropMap();
}
/**
* Removes all clusters and markers from the map and also removes all markers
* managed by the clusterer.
*/
NgMapMarkerClusterer.prototype.clearMarkers = function () {
this.resetViewport_(true);
this.markers_ = new PropMap();
};
/**
* Removes a marker and returns true if removed, false if not.
*
* @param {google.maps.Marker} marker The marker to remove
* @return {boolean} Whether the marker was removed or not
*/
NgMapMarkerClusterer.prototype.removeMarker_ = function (marker) {
if (!this.markers_.get(marker.key)) {
return false;
}
marker.setMap(null);
this.markers_.remove(marker.key); // Remove the marker from the list of managed markers
return true;
};
/**
* Creates the clusters. This is done in batches to avoid timeout errors
* in some browsers when there is a huge number of markers.
*
* @param {number} iFirst The index of the first marker in the batch of
* markers to be added to clusters.
*/
NgMapMarkerClusterer.prototype.createClusters_ = function (iFirst) {
var i, marker;
var mapBounds;
var cMarkerClusterer = this;
if (!this.ready_) {
return;
}
// Cancel previous batch processing if we're working on the first batch:
if (iFirst === 0) {
/**
* This event is fired when the <code>MarkerClusterer</code> begins
* clustering markers.
* @name MarkerClusterer#clusteringbegin
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, 'clusteringbegin', this);
if (typeof this.timerRefStatic !== 'undefined') {
clearTimeout(this.timerRefStatic);
delete this.timerRefStatic;
}
}
// Get our current map view bounds.
// Create a new bounds object so we don't affect the map.
//
// See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:
if (this.getMap().getZoom() > 3) {
mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),
this.getMap().getBounds().getNorthEast());
} else {
mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));
}
var bounds = this.getExtendedBounds(mapBounds);
var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);
var _ms = this.markers_.values();
for (i = iFirst; i < iLast; i++) {
marker = _ms[i];
if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {
this.addToClosestCluster_(marker);
}
}
}
if (iLast < this.markers_.length) {
this.timerRefStatic = setTimeout(function () {
cMarkerClusterer.createClusters_(iLast);
}, 0);
} else {
// custom addition by ui-gmap
// update icon for all clusters
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].updateIcon_();
}
delete this.timerRefStatic;
/**
* This event is fired when the <code>MarkerClusterer</code> stops
* clustering markers.
* @name MarkerClusterer#clusteringend
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, 'clusteringend', this);
}
};
/**
* Adds a marker to a cluster, or creates a new cluster.
*
* @param {google.maps.Marker} marker The marker to add.
*/
NgMapMarkerClusterer.prototype.addToClosestCluster_ = function (marker) {
var i, d, cluster, center;
var distance = 40000; // Some large number
var clusterToAddTo = null;
for (i = 0; i < this.clusters_.length; i++) {
cluster = this.clusters_[i];
center = cluster.getCenter();
if (center) {
d = this.distanceBetweenPoints_(center, marker.getPosition());
if (d < distance) {
distance = d;
clusterToAddTo = cluster;
}
}
}
if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
clusterToAddTo.addMarker(marker);
} else {
cluster = new NgMapCluster(this);
cluster.addMarker(marker);
this.clusters_.push(cluster);
}
};
/**
* Redraws all the clusters.
*/
NgMapMarkerClusterer.prototype.redraw_ = function () {
this.createClusters_(0);
};
/**
* Removes all clusters from the map. The markers are also removed from the map
* if <code>opt_hide</code> is set to <code>true</code>.
*
* @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers
* from the map.
*/
NgMapMarkerClusterer.prototype.resetViewport_ = function (opt_hide) {
var i, marker;
// Remove all the clusters
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].remove();
}
this.clusters_ = [];
// Reset the markers to not be added and to be removed from the map.
this.markers_.each(function (marker) {
marker.isAdded = false;
if (opt_hide) {
marker.setMap(null);
}
});
};
/**
* Extends an object's prototype by another's.
*
* @param {Object} obj1 The object to be extended.
* @param {Object} obj2 The object to extend with.
* @return {Object} The new extended object.
* @ignore
*/
NgMapMarkerClusterer.prototype.extend = function (obj1, obj2) {
return (function (object) {
var property;
for (property in object.prototype) {
if (property !== 'constructor')
this.prototype[property] = object.prototype[property];
}
return this;
}).apply(obj1, [obj2]);
};
////////////////////////////////////////////////////////////////////////////////
/*
Other overrides relevant to MarkerClusterPlus
*/
////////////////////////////////////////////////////////////////////////////////
/**
* Positions and shows the icon.
*/
ClusterIcon.prototype.show = function () {
if (this.div_) {
var img = "";
// NOTE: values must be specified in px units
var bp = this.backgroundPosition_.split(" ");
var spriteH = parseInt(bp[0].trim(), 10);
var spriteV = parseInt(bp[1].trim(), 10);
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.cssText = this.createCss(pos);
img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; ";
if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) {
img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " +
((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);";
}
// ADDED FOR RETINA SUPPORT
else {
img += "width: " + this.width_ + "px;" + "height: " + this.height_ + "px;";
}
// END ADD
img += "'>";
this.div_.innerHTML = img + "<div style='" +
"position: absolute;" +
"top: " + this.anchorText_[0] + "px;" +
"left: " + this.anchorText_[1] + "px;" +
"color: " + this.textColor_ + ";" +
"font-size: " + this.textSize_ + "px;" +
"font-family: " + this.fontFamily_ + ";" +
"font-weight: " + this.fontWeight_ + ";" +
"font-style: " + this.fontStyle_ + ";" +
"text-decoration: " + this.textDecoration_ + ";" +
"text-align: center;" +
"width: " + this.width_ + "px;" +
"line-height:" + this.height_ + "px;" +
"'>" + this.sums_.text + "</div>";
if (typeof this.sums_.title === "undefined" || this.sums_.title === "") {
this.div_.title = this.cluster_.getMarkerClusterer().getTitle();
} else {
this.div_.title = this.sums_.title;
}
this.div_.style.display = "";
}
this.visible_ = true;
};
//END OTHER OVERRIDES
////////////////////////////////////////////////////////////////////////////////
return NgMapMarkerClusterer;
})(MarkerClusterer);
}).call(this);
})
};
}]);
}( window,angular)); |
app/components/Accounts/CustomJSON.js | aaroncox/vessel | // @flow
import React, { Component } from 'react';
import { Grid, Header, Message, Segment, Select, Table } from 'semantic-ui-react';
import { Form, Input } from 'formsy-semantic-ui-react';
import AccountName from '../global/AccountName';
export default class AccountsCustomJSON extends Component {
constructor(props) {
super(props)
this.state = {
account: props.keys.names[0],
id: '',
json: '',
message: false,
permission: 'posting',
}
}
resetState(extraState) {
this.setState(Object.assign({}, {
id: '',
json: ''
}, extraState))
}
handleIdChange = (e: SyntheticEvent, { value }: { value: any }) => {
this.setState({
id: value
})
}
handleJsonChange = (e: SyntheticEvent, { value }: { value: any }) => {
this.setState({
json: value.trim()
})
}
handleAccountChange = (e: SyntheticEvent, { value }: { value: any }) => {
this.setState({
account: value
})
}
handlePermissionChange = (e: SyntheticEvent, { value }: { value: any }) => {
this.setState({
permission: value
})
}
onValidSubmit = (
e: SyntheticEvent
) => {
const { account, id, json, permission } = this.state
this.setState({message: false})
this.props.actions.useKey('customJson', { account, id, json, permission }, this.props.keys.permissions[account]);
}
componentWillReceiveProps = (nextProps) => {
if (nextProps.processing.account_custom_json_resolved) {
nextProps.actions.customJsonCompleted();
this.resetState({
'message': 'Your transaction was successfully broadcast.'
});
}
}
render() {
const {
account_custom_json_error,
account_custom_json_pending,
account_custom_json_resolved
} = this.props.processing;
const keys = this.props.keys;
const availableFrom = keys.names.map((name) => {
const hasPermission = (keys.permissions[name].type === 'active' || keys.permissions[name].type === 'owner');
return hasPermission ? {
key: name,
text: name,
value: name
} : {
key: name,
disabled: true,
text: name + ' (unavailable - active/owner key not loaded)'
};
});
const availablePermissions = ['active', 'posting'].map((permission) => ({
key: permission,
text: permission,
value: permission
}))
let message = false
if(this.state.message) {
message = (
<Message
success
header="Operation Complete"
content={this.state.message}
/>
)
}
console.log(this.state)
return (
<Segment basic padded>
<Header>
<Header.Subheader>
Broadcast a Custom JSON operation to the Hive blockchain.
</Header.Subheader>
</Header>
{message}
<Form
onValidSubmit={this.onValidSubmit}
error={account_custom_json_error}
loading={account_custom_json_pending}
>
<Form.Field
control={Select}
value={this.state.account}
name="from"
label="Select an account to broadcast with"
options={availableFrom}
placeholder="Sending Account..."
onChange={this.handleAccountChange}
/>
<Form.Field
control={Select}
value={this.state.permission}
name="permission"
label="Select a permission to use"
options={availablePermissions}
placeholder="Permission"
onChange={this.handlePermissionChange}
/>
<Form.Input
label="ID"
name="id"
value={this.state.id}
onChange={this.handleIdChange}
placeholder=""
/>
<Form.TextArea
label="JSON"
name="json"
value={this.state.json}
onChange={this.handleJsonChange}
placeholder=""
/>
<Message
error
header="Operation Error"
content={account_custom_json_error}
/>
<Form.Button
color='blue'
content='Broadcast'
disabled={account_custom_json_pending}
/>
</Form>
</Segment>
);
}
}
|
static/js/src/components/presentations/equipTraitsText.js | jpludens/quartrmastr | import React from 'react';
import Trait from '../../classes/Trait.js';
import TraitsArray from '../../classes/TraitsArray.js';
const EquipTraitsText = ({ traits }) => {
return (
<p>
{traits.map((trait, index) => {
let text = "Um...";
const data = trait.data;
switch (trait.type) {
// Imbue
case "Imbue":
text = `Imbued with ${data.element}. `;
break;
// Boost
case "Boost":
text = data.element == null
? `Boosts the power of ${data.property}.`
: `Boosts the power of ${data.element} Skills.`;
break;
// Sapper stuff
case "Inflict":
text = `May inflict ${data.status || data.property} on targets. `;
break;
case "ReplaceInflict":
text = `Replaces weapon effect with ${data.status}. `;
break;
case "Debuff":
text = `May debuff targets' ${data.stat}. `;
break;
case "Drain":
text = `Drains ${data.stat} from foes with certain Skills. `;
break;
// Offensive stuff
case "Combo":
text = `May cast ${data.skillName} with certain Skills. `;
break;
case "Chrono":
text = `Randomly casts ${data.skillName} between turns. `;
break;
case "Counter":
text = `Counter attacks with ${data.skillName}. `;
break;
// Defensive stuff
case "Bestow":
text = `Randomly gives the player ${data.status} status. `;
break;
case "Rally":
text = `Boosts ${data.stat} when hit with a powerful attack. `;
break;
}
return <span key={index}>{text} </span>
})}
</p>
);
}
EquipTraitsText.propTypes = {
traits: React.PropTypes.arrayOf(
React.PropTypes.instanceOf(Trait)).isRequired,
};
export default EquipTraitsText;
|
src/react/LogMonitorEntryAction.js | taylorhakes/redux-devtools | import React from 'react';
import JSONTree from './JSONTree';
const styles = {
actionBar: {
paddingTop: 8,
paddingBottom: 7,
paddingLeft: 16
},
payload: {
margin: 0,
overflow: 'auto'
}
};
export default class LogMonitorAction extends React.Component {
renderPayload(payload) {
return (
<div style={{
...styles.payload,
backgroundColor: this.props.theme.base00
}}>
{ Object.keys(payload).length > 0 ? <JSONTree theme={this.props.theme} keyName={'action'} data={payload}/> : '' }
</div>
);
}
render() {
const { type, ...payload } = this.props.action;
return (
<div style={{
backgroundColor: this.props.theme.base02,
color: this.props.theme.base06,
...this.props.style
}}>
<div style={styles.actionBar}
onClick={this.props.onClick}>
{type}
</div>
{!this.props.collapsed ? this.renderPayload(payload) : ''}
</div>
);
}
}
|
js/jquery-1.11.0.js | dmleong/wedding-website | /*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f
}}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)
},a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n}); |
ajax/libs/6to5/2.12.6/browser.js | sympmarc/cdnjs | !function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.to5=t()}}(function(){var e,t,r;return function n(e,t,r){function n(i,u){if(!t[i]){if(!e[i]){var o=typeof require=="function"&&require;if(!u&&o)return o(i,!0);if(a)return a(i,!0);var l=new Error("Cannot find module '"+i+"'");throw l.code="MODULE_NOT_FOUND",l}var s=t[i]={exports:{}};e[i][0].call(s.exports,function(t){var r=e[i][1][t];return n(r?r:t)},s,s.exports,n,e,t,r)}return t[i].exports}var a=typeof require=="function"&&require;for(var i=0;i<r.length;i++)n(r[i]);return n}({1:[function(n,r,t){(function(i,n){if(typeof t=="object"&&typeof r=="object")return n(t);if(typeof e=="function"&&e.amd)return e(["exports"],n);n(i.acorn||(i.acorn={}))})(this,function(B){"use strict";B.version="0.11.1";var n,a,U,yr;B.parse=function(e,r){a=String(e);U=a.length;gr(r);mr();var i=n.locations?[t,dt()]:t;en();return ua(n.program||k(i))};var fn=B.defaultOptions={playground:false,ecmaVersion:5,strictSemicolons:false,allowTrailingCommas:true,forbidReserved:false,allowReturnOutsideFunction:false,allowImportExportEverywhere:false,allowHashBang:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false};B.parseExpressionAt=function(e,t,r){a=String(e);U=a.length;gr(r);mr(t);en();return v()};var nn=function(e){return Object.prototype.toString.call(e)==="[object Array]"};function gr(t){n={};for(var e in fn)n[e]=t&&cr(t,e)?t[e]:fn[e];yr=n.sourceFile||null;if(nn(n.onToken)){var r=n.onToken;n.onToken=function(e){r.push(e)}}if(nn(n.onComment)){var i=n.onComment;n.onComment=function(a,s,t,r,o,l){var e={type:a?"Block":"Line",value:s,start:t,end:r};if(n.locations){e.loc=new rr;e.loc.start=o;e.loc.end=l}if(n.ranges)e.range=[t,r];i.push(e)}}if(n.strictMode){O=true}if(n.ecmaVersion>=6){ir=xi}else{ir=Qr}}var Ri=B.getLineInfo=function(i,r){for(var n=1,t=0;;){Et.lastIndex=t;var e=Et.exec(i);if(e&&e.index<r){++n;t=e.index+e[0].length}else break}return{line:n,column:r-t}};function Sr(){this.type=e;this.value=c;this.start=m;this.end=R;if(n.locations){this.loc=new rr;this.loc.end=Rt;this.startLoc=it;this.endLoc=Rt}if(n.ranges)this.range=[m,R]}B.Token=Sr;B.tokenize=function(r,i){a=String(r);U=a.length;gr(i);mr();st();function e(e){L=R;lt(e);return new Sr}e.jumpTo=function(r,i){t=r;if(n.locations){V=1;j=Et.lastIndex=0;var e;while((e=Et.exec(a))&&e.index<r){++V;j=e.index+e[0].length}}Y=i;st()};e.noRegexp=function(){Y=false};e.options=n;return e};var t;var m,R;var it,Rt;var e,c;var Y;var V,j;var jt,L,nt;var Gt,Ct,Ut,I,O,P,C,ot;var Vt;var et;function en(){jt=L=t;if(n.locations)nt=new Kt;Gt=Ct=Ut=O=false;I=[];st();lt()}function u(n,i){var r=Ri(a,n);i+=" ("+r.line+":"+r.column+")";var e=new SyntaxError(i);e.pos=n;e.loc=r;e.raisedAt=t;throw e}var mn=[];var yt={type:"num"},kr={type:"regexp"},W={type:"string"};var p={type:"name"},gt={type:"eof"};var br={type:"xjsName"},Mt={type:"xjsText"};var hn={keyword:"break"},hr={keyword:"case",beforeExpr:true},zn={keyword:"catch"};var zr={keyword:"continue"},Wn={keyword:"debugger"},zt={keyword:"default"};var Jn={keyword:"do",isLoop:true},Un={keyword:"else",beforeExpr:true};var Vn={keyword:"finally"},Nt={keyword:"for",isLoop:true},pt={keyword:"function"};var Pr={keyword:"if"},Nn={keyword:"return",beforeExpr:true},ur={keyword:"switch"};var Mn={keyword:"throw",beforeExpr:true},jn={keyword:"try"},kt={keyword:"var"};var Tt={keyword:"let"},Ht={keyword:"const"};var fr={keyword:"while",isLoop:true},Ln={keyword:"with"},Pn={keyword:"new",beforeExpr:true};var Cn={keyword:"this"};var xt={keyword:"class"},Ar={keyword:"extends",beforeExpr:true};var wn={keyword:"export"},Lr={keyword:"import"};var Sn={keyword:"yield",beforeExpr:true};var xn={keyword:"null",atomValue:null},En={keyword:"true",atomValue:true};var bn={keyword:"false",atomValue:false};var Ot={keyword:"in",binop:7,beforeExpr:true};var Xt={"break":hn,"case":hr,"catch":zn,"continue":zr,"debugger":Wn,"default":zt,"do":Jn,"else":Un,"finally":Vn,"for":Nt,"function":pt,"if":Pr,"return":Nn,"switch":ur,"throw":Mn,"try":jn,"var":kt,let:Tt,"const":Ht,"while":fr,"with":Ln,"null":xn,"true":En,"false":bn,"new":Pn,"in":Ot,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:true},"this":Cn,"typeof":{keyword:"typeof",prefix:true,beforeExpr:true},"void":{keyword:"void",prefix:true,beforeExpr:true},"delete":{keyword:"delete",prefix:true,beforeExpr:true},"class":xt,"extends":Ar,"export":wn,"import":Lr,"yield":Sn};var q={type:"[",beforeExpr:true},N={type:"]"},A={type:"{",beforeExpr:true};var E={type:"}"},g={type:"(",beforeExpr:true},h={type:")"};var b={type:",",beforeExpr:true},_={type:";",beforeExpr:true};var w={type:":",beforeExpr:true},qt={type:"."},Z={type:"?",beforeExpr:true};var Q={type:"=>",beforeExpr:true},dn={type:"`"},pn={type:"${",beforeExpr:true};var or={type:"</"};var Q={type:"=>",beforeExpr:true},Zt={type:"template"},Qt={type:"templateContinued"};var $={type:"...",prefix:true,beforeExpr:true};var pr={type:"::",beforeExpr:true};var dr={type:"@"};var Yt={type:"#"};var Ft={binop:10,beforeExpr:true},rt={isAssign:true,beforeExpr:true};var tt={isAssign:true,beforeExpr:true};var Si={postfix:true,prefix:true,isUpdate:true},cn={prefix:true,beforeExpr:true};var on={binop:1,beforeExpr:true};var sn={binop:2,beforeExpr:true};var an={binop:3,beforeExpr:true};var Gi={binop:4,beforeExpr:true};var rn={binop:5,beforeExpr:true};var sa={binop:6,beforeExpr:true};var ui={binop:7,beforeExpr:true};var ci={binop:8,beforeExpr:true};var hi={binop:9,prefix:true,beforeExpr:true};var vi={binop:10,beforeExpr:true};var z={binop:10,beforeExpr:true};var tn={binop:11,beforeExpr:true};var S={binop:7,beforeExpr:true},H={binop:7,beforeExpr:true};B.tokTypes={bracketL:q,bracketR:N,braceL:A,braceR:E,parenL:g,parenR:h,comma:b,semi:_,colon:w,dot:qt,ellipsis:$,question:Z,slash:Ft,eq:rt,name:p,eof:gt,num:yt,regexp:kr,string:W,arrow:Q,bquote:dn,dollarBraceL:pn,star:z,assign:tt,xjsName:br,xjsText:Mt,paamayimNekudotayim:pr,exponent:tn,at:dr,hash:Yt,template:Zt,templateContinued:Qt};for(var Zr in Xt)B.tokTypes["_"+Zr]=Xt[Zr];var ai=function Ra(e){switch(e.length){case 6:switch(e){case"double":case"export":case"import":case"native":case"public":case"static":case"throws":return true}return false;case 4:switch(e){case"byte":case"char":case"enum":case"goto":case"long":return true}return false;case 5:switch(e){case"class":case"final":case"float":case"short":case"super":return true}return false;case 7:switch(e){case"boolean":case"extends":case"package":case"private":return true}return false;case 9:switch(e){case"interface":case"protected":case"transient":return true}return false;case 8:switch(e){case"abstract":case"volatile":return true}return false;case 10:return e==="implements";case 3:return e==="int";case 12:return e==="synchronized"}};var si=function Na(e){switch(e.length){case 5:switch(e){case"class":case"super":case"const":return true}return false;case 6:switch(e){case"export":case"import":return true}return false;case 4:return e==="enum";case 7:return e==="extends"}};var Mr=function Fa(e){switch(e.length){case 9:switch(e){case"interface":case"protected":return true}return false;case 7:switch(e){case"package":case"private":return true}return false;case 6:switch(e){case"public":case"static":return true}return false;case 10:return e==="implements";case 3:return e==="let";case 5:return e==="yield"}};var Or=function Ba(e){switch(e){case"eval":case"arguments":return true}return false};var mi="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var Qr=function Va(e){switch(e.length){case 4:switch(e){case"case":case"else":case"with":case"null":case"true":case"void":case"this":return true}return false;case 5:switch(e){case"break":case"catch":case"throw":case"while":case"false":return true}return false;case 3:switch(e){case"for":case"try":case"var":case"new":return true}return false;case 6:switch(e){case"return":case"switch":case"typeof":case"delete":return true}return false;case 8:switch(e){case"continue":case"debugger":case"function":return true}return false;case 2:switch(e){case"do":case"if":case"in":return true}return false;case 7:switch(e){case"default":case"finally":return true}return false;case 10:return e==="instanceof"}};var Da=mi+" let const class extends export import yield";var xi=function Ua(e){switch(e.length){case 5:switch(e){case"break":case"catch":case"throw":case"while":case"false":case"const":case"class":case"yield":return true}return false;case 4:switch(e){case"case":case"else":case"with":case"null":case"true":case"void":case"this":return true}return false;case 6:switch(e){case"return":case"switch":case"typeof":case"delete":case"export":case"import":return true}return false;case 3:switch(e){case"for":case"try":case"var":case"new":case"let":return true}return false;case 8:switch(e){case"continue":case"debugger":case"function":return true}return false;case 7:switch(e){case"default":case"finally":case"extends":return true}return false;case 2:switch(e){case"do":case"if":case"in":return true}return false;case 10:return e==="instanceof"}};var ir=Qr;var _i=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var Kr="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var Xi="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧙ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_";var $r=new RegExp("["+Kr+"]");var Ji=new RegExp("["+Kr+Xi+"]");var Wi=/^\d+$/;var zi=/^[\da-fA-F]+$/;var ct=/[\n\r\u2028\u2029]/;function Oa(e){return e===10||e===13||e===8232||e==8233}var Et=/\r\n|[\n\r\u2028\u2029]/g;var Wt=B.isIdentifierStart=function(e){if(e<65)return e===36;if(e<91)return true;if(e<97)return e===95;if(e<123)return true;return e>=170&&$r.test(String.fromCharCode(e))};var Yr=B.isIdentifierChar=function(e){if(e<48)return e===36;if(e<58)return true;if(e<65)return false;if(e<91)return true;if(e<97)return e===95;if(e<123)return true;return e>=170&&Ji.test(String.fromCharCode(e))};function Kt(e,t){this.line=e;this.column=t}Kt.prototype.offset=function(e){return new Kt(this.line,this.column+e)};function dt(){return new Kt(V,t-j)}function mr(e){if(e){t=e;j=Math.max(0,a.lastIndexOf("\n",e));V=a.slice(0,j).split(ct).length}else{V=1;t=j=0}Y=true;Vt=0;ot=P=C=false;et=[];if(t===0&&n.allowHashBang&&a.slice(0,2)==="#!"){Jt(2)}}function y(r,i,a){R=t;if(n.locations)Rt=dt();e=r;if(a!==false)st();c=i;Y=r.beforeExpr;if(n.onToken){n.onToken(new Sr)}}function gi(){var s=n.onComment&&n.locations&&dt();var r=t,i=a.indexOf("*/",t+=2);if(i===-1)u(t-2,"Unterminated comment");t=i+2;if(n.locations){Et.lastIndex=r;var e;while((e=Et.exec(a))&&e.index<t){++V;j=e.index+e[0].length}}if(n.onComment)n.onComment(true,a.slice(r+2,i),r,t,s,n.locations&&dt())}function Jt(r){var i=t;var s=n.onComment&&n.locations&&dt();var e=a.charCodeAt(t+=r);while(t<U&&e!==10&&e!==13&&e!==8232&&e!==8233){++t;e=a.charCodeAt(t)}if(n.onComment)n.onComment(false,a.slice(i+r,t),i,t,s,n.locations&&dt())}function st(){while(t<U){var e=a.charCodeAt(t);if(e===32){++t}else if(e===13){++t;var r=a.charCodeAt(t);if(r===10){++t}if(n.locations){++V;j=t}}else if(e===10||e===8232||e===8233){++t;if(n.locations){++V;j=t}}else if(e>8&&e<14){++t}else if(e===47){var r=a.charCodeAt(t+1);if(r===42){gi()}else if(r===47){Jt(2)}else break}else if(e===160){++t}else if(e>=5760&&_i.test(String.fromCharCode(e))){++t}else{break}}}function wi(){var e=a.charCodeAt(t+1);if(e>=48&&e<=57)return Gr(true);var r=a.charCodeAt(t+2);if(n.playground&&e===63){t+=2;return y(_dotQuestion)}else if(n.ecmaVersion>=6&&e===46&&r===46){t+=3;return y($)}else{++t;return y(qt)}}function ki(){var e=a.charCodeAt(t+1);if(Y){++t;return Jr()}if(e===61)return x(tt,2);return x(Ft,1)}function Ii(){var e=a.charCodeAt(t+1);if(e===61)return x(tt,2);return x(vi,1)}function Ci(){var e=z;var r=1;var i=a.charCodeAt(t+1);if(n.ecmaVersion>=7&&i===42){r++;i=a.charCodeAt(t+2);e=tn}if(i===61){r++;e=tt}return x(e,r)}function Ai(e){var r=a.charCodeAt(t+1);if(r===e)return x(e===124?on:sn,2);if(r===61)return x(tt,2);return x(e===124?an:rn,1)}function Pi(){var e=a.charCodeAt(t+1);if(e===61)return x(tt,2);return x(Gi,1)}function Li(r){var e=a.charCodeAt(t+1);if(e===r){if(e==45&&a.charCodeAt(t+2)==62&&ct.test(a.slice(L,t))){Jt(3);st();return lt()}return x(Si,2)}if(e===61)return x(tt,2);return x(hi,1)}function _a(r){var n=a.charCodeAt(t+1);var e=1;if(!ot&&n===r){e=r===62&&a.charCodeAt(t+2)===62?3:2;if(a.charCodeAt(t+e)===61)return x(tt,e+1);return x(ci,e)}if(n==33&&r==60&&a.charCodeAt(t+2)==45&&a.charCodeAt(t+3)==45){Jt(4);st();return lt()}if(n===61){e=a.charCodeAt(t+2)===61?3:2;return x(ui,e)}if(r===60&&n===47){e=2;return x(or,e)}return r===60?x(S,e):x(H,e,!C)}function ji(e){var r=a.charCodeAt(t+1);if(r===61)return x(sa,a.charCodeAt(t+2)===61?3:2);if(e===61&&r===62&&n.ecmaVersion>=6){t+=2;return y(Q)}return x(e===61?rt:cn,1)}function Ma(r){if(e===W){if(r===96){++t;return y(dn)}else if(r===36&&a.charCodeAt(t+1)===123){t+=2;return y(pn)}}return readTmplString()}function Di(r){switch(r){case 46:return wi();case 40:++t;return y(g);case 41:++t;return y(h);case 59:++t;return y(_);case 44:++t;return y(b);case 91:++t;return y(q);case 93:++t;return y(N);case 123:++t;if(et.length)++et[et.length-1];return y(A);case 125:++t;if(et.length&&--et[et.length-1]===0)return Xr(Qt);else return y(E);case 63:++t;return y(Z);case 64:if(n.playground){++t;return y(dr)}case 35:if(n.playground){++t;return y(Yt)}case 58:++t;if(n.ecmaVersion>=7){var e=a.charCodeAt(t);if(e===58){++t;return y(pr)}}return y(w);case 96:if(n.ecmaVersion>=6){++t;return Xr(Zt)}case 48:var e=a.charCodeAt(t+1);if(e===120||e===88)return Ir(16);if(n.ecmaVersion>=6){if(e===111||e===79)return Ir(8);if(e===98||e===66)return Ir(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return Gr(false);case 34:case 39:return C?fi():ha(r);case 47:return ki();case 37:return Ii();case 42:return Ci();case 124:case 38:return Ai(r);case 94:return Pi();case 43:case 45:return Li(r);case 60:case 62:return _a(r);case 61:case 33:return ji(r);case 126:return x(cn,1)}return false}function lt(s){if(!s)m=t;else t=m+1;if(n.locations)it=dt();if(s)return Jr();if(t>=U)return y(gt);var r=a.charCodeAt(t);if(P&&e!==A&&r!==60&&r!==123&&r!==125){return Ur(["<","{"])}if(Wt(r)||r===92)return Vr();var o=Di(r);if(o===false){var i=String.fromCharCode(r);if(i==="\\"||$r.test(i))return Vr();u(t,"Unexpected character '"+i+"'")}return o}function x(r,e,n){var i=a.slice(t,t+e);t+=e;y(r,i,n)}var Hr=false;try{new RegExp("","u");Hr=true}catch(ja){}function Jr(){var o="",l,s,r=t;for(;;){if(t>=U)u(r,"Unterminated regular expression");var i=at();if(ct.test(i))u(r,"Unterminated regular expression");if(!l){if(i==="[")s=true;else if(i==="]"&&s)s=false;else if(i==="/"&&!s)break;l=i==="\\"}else l=false;++t}var o=a.slice(r,t);++t;var e=vn();var f=o;if(e){var p=/^[gmsiy]*$/;if(n.ecmaVersion>=6)p=/^[gmsiyu]*$/;if(!p.test(e))u(r,"Invalid regular expression flag");if(e.indexOf("u")>=0&&!Hr){f=f.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}}try{new RegExp(f)}catch(c){if(c instanceof SyntaxError)u(r,"Error parsing regular expression: "+c.message);u(c)}try{var d=new RegExp(o,e)}catch(m){d=null}return y(kr,{pattern:o,flags:e,value:d})}function At(s,n){var o=t,i=0;for(var l=0,u=n==null?Infinity:n;l<u;++l){var e=a.charCodeAt(t),r;if(e>=97)r=e-97+10;else if(e>=65)r=e-65+10;else if(e>=48&&e<=57)r=e-48;else r=Infinity;if(r>=s)break;++t;i=i*s+r}if(t===o||n!=null&&t-o!==n)return null;return i}function Ir(e){t+=2;var r=At(e);if(r==null)u(m+2,"Expected number in radix "+e);if(Wt(a.charCodeAt(t)))u(t,"Identifier directly after number");return y(yt,r)}function Gr(o){var n=t,s=false,l=a.charCodeAt(t)===48;if(!o&&At(10)===null)u(n,"Invalid number");if(a.charCodeAt(t)===46){++t;At(10);s=true}var e=a.charCodeAt(t);if(e===69||e===101){e=a.charCodeAt(++t);if(e===43||e===45)++t;if(At(10)===null)u(n,"Invalid number");s=true}if(Wt(a.charCodeAt(t)))u(t,"Identifier directly after number");var r=a.slice(n,t),i;if(s)i=parseFloat(r);else if(!l||r.length===1)i=parseInt(r,10);else if(/[89]/.test(r)||O)u(n,"Invalid number");else i=parseInt(r,8);return y(yt,i)}function da(){var r=a.charCodeAt(t),e;if(r===123){if(n.ecmaVersion<6)f();++t;e=nr(a.indexOf("}",t)-t);++t;if(e>1114111)f()}else{e=nr(4)}if(e<=65535){return String.fromCharCode(e)}var i=(e-65536>>10)+55296;var s=(e-65536&1023)+56320;return String.fromCharCode(i,s)}function ha(n){++t;var r="";for(;;){if(t>=U)u(m,"Unterminated string constant");var e=a.charCodeAt(t);if(e===n){++t;return y(W,r)}if(e===92){r+=qr()}else{++t;if(ct.test(String.fromCharCode(e))){u(m,"Unterminated string constant")}r+=String.fromCharCode(e)}}}function Xr(i){if(i==Qt)et.pop();var r="",s=t;for(;;){if(t>=U)u(m,"Unterminated template");var e=a.charAt(t);if(e==="`"||e==="$"&&a.charCodeAt(t+1)===123){var o=a.slice(s,t);++t;if(e=="$"){++t;et.push(1)}return y(i,{cooked:r,raw:o})}if(e==="\\"){r+=qr()}else{++t;if(ct.test(e)){if(e==="\r"&&a.charCodeAt(t)===10){++t;e="\n"}if(n.locations){++V;j=t}}r+=e}}}function qr(){var r=a.charCodeAt(++t);var e=/^[0-7]+/.exec(a.slice(t,t+3));if(e)e=e[0];while(e&&parseInt(e,8)>255)e=e.slice(0,-1);if(e==="0")e=null;++t;if(e){if(O)u(t-2,"Octal literal in strict mode");t+=e.length-1;return String.fromCharCode(parseInt(e,8))}else{switch(r){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(nr(2));case 117:return da();case 116:return" ";case 98:return"\b";case 118:return"";case 102:return"\f";case 48:return"\x00";case 13:if(a.charCodeAt(t)===10)++t;case 10:if(n.locations){j=t;++V}return"";default:return String.fromCharCode(r)}}}var oi={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"",zwj:"",lrm:"",rlm:"",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function li(){var e="",i=0,r;var n=at();if(n!=="&")u(t,"Entity must start with an ampersand");var a=++t;while(t<U&&i++<10){n=at();t++;if(n===";"){if(e[0]==="#"){if(e[1]==="x"){e=e.substr(2);if(zi.test(e)){r=String.fromCharCode(parseInt(e,16))}}else{e=e.substr(1);if(Wi.test(e)){r=String.fromCharCode(parseInt(e,10))}}}else{r=oi[e]}break}e+=n}if(!r){t=a;return"&"}return r}function Ur(i){var r="";while(t<U){var e=at();if(i.indexOf(e)!==-1){break}if(e==="&"){r+=li()}else{++t;if(e==="\r"&&at()==="\n"){r+=e;++t;e="\n"}if(e==="\n"&&n.locations){j=t;++V}r+=e}}return y(Mt,r)}function fi(){var r=a.charCodeAt(t);if(r!==34&&r!==39){u("String literal must starts with a quote")}++t;Ur([String.fromCharCode(r)]);if(r!==a.charCodeAt(t)){f()}++t;return y(e,c)}function nr(t){var e=At(16,t);if(e===null)u(m,"Bad character escape sequence");return e}var bt;function vn(){bt=false;var e,i=true,s=t;for(;;){var r=a.charCodeAt(t);if(Yr(r)||C&&r===45){if(bt)e+=at();++t}else if(r===92&&!C){if(!bt)e=a.slice(s,t);bt=true;if(a.charCodeAt(++t)!=117)u(t,"Expecting Unicode escape sequence \\uXXXX");++t;var n=nr(4);var o=String.fromCharCode(n);if(!o)u(t-1,"Invalid Unicode escape");if(!(i?Wt(n):Yr(n)))u(t-4,"Invalid Unicode escape");e+=o}else{break}i=false}return bt?e:a.slice(s,t)}function Vr(){var e=vn();var t=C?br:p;if(!bt&&ir(e))t=Xt[e];return y(t,e)}function o(){jt=m;L=R;nt=Rt;lt()}function Dr(e){O=e;t=m;if(n.locations){while(t<j){j=a.lastIndexOf("\n",j-2)+1;--V}}st();lt()}function Rr(){this.type=null;this.start=m;this.end=null}B.Node=Rr;function rr(){this.start=it;this.end=null;if(yr!==null)this.source=yr}function l(){var e=new Rr;if(n.locations)e.loc=new rr;if(n.directSourceFile)e.sourceFile=n.directSourceFile;if(n.ranges)e.range=[m,0];return e}function T(){return n.locations?[m,it]:m}function k(r){var e=new Rr,t=r;if(n.locations){e.loc=new rr;e.loc.start=t[1];t=r[0]}e.start=t;if(n.directSourceFile)e.sourceFile=n.directSourceFile;if(n.ranges)e.range=[t,0];return e}function r(e,t){e.type=t;e.end=L;if(n.locations)e.loc.end=nt;if(n.ranges)e.range[1]=L;return e}function Ti(e,r,t){if(n.locations){e.loc.end=t[1];t=t[0]}e.type=r;e.end=t;if(n.ranges)e.range[1]=t;return e}function Tr(e){return n.ecmaVersion>=5&&e.type==="ExpressionStatement"&&e.expression.type==="Literal"&&e.expression.value==="use strict"}function s(t){if(e===t){o();return true}else{return false}}function ut(){return!n.strictSemicolons&&(e===gt||e===E||ct.test(a.slice(L,m)))}function M(){if(!s(_)&&!ut())f()}function i(e){s(e)||f()}function at(){return a.charAt(t)}function f(e){u(e!=null?e:m,"Unexpected token")}function cr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function St(e,s,r){if(n.ecmaVersion>=6&&e){switch(e.type){case"Identifier":case"MemberExpression":break;case"ObjectExpression":e.type="ObjectPattern";for(var t=0;t<e.properties.length;t++){var i=e.properties[t];if(i.type==="Property"&&i.kind!=="init")f(i.key.start);St(i.value,false,r)}break;case"ArrayExpression":e.type="ArrayPattern";for(var t=0,a=e.elements.length-1;t<=a;t++){St(e.elements[t],t===a,r)}break;case"SpreadElement":if(s){St(e.argument,false,r);jr(e.argument)}else{f(e.start)}break;case"AssignmentExpression":if(e.operator==="="){e.type="AssignmentPattern"}else{f(e.left.end)}break;default:if(r)f(e.start)}}return e}function vt(){if(n.ecmaVersion<6)return d();switch(e){case p:return d();case q:var a=l();o();var u=a.elements=[],c=true;while(!s(N)){c?c=false:i(b);if(e===$){var t=l();o();t.argument=vt();jr(t.argument);u.push(r(t,"SpreadElement"));i(N);break}u.push(e===b?null:Nr())}return r(a,"ArrayPattern");case A:return gn(true);default:f()}}function Nr(n,e){e=e||vt();if(!s(rt))return e;var t=n?k(n):l();t.operator="=";t.left=e;t.right=ft();return r(t,"AssignmentPattern")}function jr(e){if(e.type!=="Identifier"&&e.type!=="ArrayPattern")f(e.start)}function Pt(e,r){switch(e.type){case"Identifier":if(Mr(e.name)||Or(e.name))u(e.start,"Defining '"+e.name+"' in strict mode");if(cr(r,e.name))u(e.start,"Argument name clash in strict mode");r[e.name]=true;break;case"ObjectPattern":for(var t=0;t<e.properties.length;t++)Pt(e.properties[t].value,r);break;case"ArrayPattern":for(var t=0;t<e.elements.length;t++){var n=e.elements[t];if(n)Pt(n,r)}break}}function na(s,i){if(n.ecmaVersion>=6)return;var r=s.key,e;switch(r.type){case"Identifier":e=r.name;break;case"Literal":e=String(r.value);break;default:return}var a=s.kind||"init",t;if(cr(i,e)){t=i[e];var o=a!=="init";if((O||o)&&t[a]||!(o^t.init))u(r.start,"Redefinition of property")}else{t=i[e]={init:false,get:false,set:false}}t[a]=true}function G(e,r){switch(e.type){case"Identifier":if(O&&(Or(e.name)||Mr(e.name)))u(e.start,(r?"Binding ":"Assigning to ")+e.name+" in strict mode");break;case"MemberExpression":if(r)u(e.start,"Binding to member expression");break;case"ObjectPattern":for(var t=0;t<e.properties.length;t++){var n=e.properties[t];if(n.type==="Property")n=n.value;G(n,r)}break;case"ArrayPattern":for(var t=0;t<e.elements.length;t++){var i=e.elements[t];if(i)G(i,r)}break;case"SpreadProperty":case"AssignmentPattern":case"SpreadElement":case"VirtualPropertyExpression":break;default:u(e.start,"Assigning to rvalue")}}function ua(t){var n=true;if(!t.body)t.body=[];while(e!==gt){var i=F(true);t.body.push(i);if(n&&Tr(i))Dr(true);n=false}jt=m;L=R;nt=Rt;return r(t,"Program")}var Cr={kind:"loop"},ma={kind:"switch"};function F(a){if(e===Ft||e===tt&&c=="/=")lt(true);var i=e,t=l(),f=T();switch(i){case hn:case zr:return va(t,i.keyword);case Wn:return Ea(t);case Jn:return Ia(t);case Nt:return Ca(t);case pt:return Ta(t);case xt:return Tn(t,true);case Pr:return La(t);case Nn:return Yn(t);case ur:return $n(t);case Mn:return Kn(t);case jn:return Qn(t);case kt:case Tt:case Ht:return Zn(t,i.keyword);case fr:return ei(t);case Ln:return ti(t);case A:return It();case _:return ri(t);case wn:case Lr:if(!a&&!n.allowImportExportEverywhere)u(m,"'import' and 'export' may only appear at the top level");return i===Lr?Bi(t):Ni(t);default:var o=c,r=v(false,false,true);if(r.type==="FunctionDeclaration")return r;if(i===p&&r.type==="Identifier"){if(s(w)){return ni(t,o,r)}if(n.ecmaVersion>=7&&r.name==="private"&&e===p){return An(t)}else if(r.name==="declare"){if(e===xt||e===p||e===pt||e===kt){return Fn(t)}}else if(e===p){if(r.name==="interface"){return ca(t)}else if(r.name==="type"){return pa(t)}}}return ii(t,r)}}function va(t,l){var i=l=="break";o();if(s(_)||ut())t.label=null;else if(e!==p)f();else{t.label=d();M()}for(var n=0;n<I.length;++n){var a=I[n];if(t.label==null||a.name===t.label.name){if(a.kind!=null&&(i||a.kind==="loop"))break;if(t.label&&i)break}}if(n===I.length)u(t.start,"Unsyntactic "+l);return r(t,i?"BreakStatement":"ContinueStatement")}function Ea(e){o();M();return r(e,"DebuggerStatement")}function Ia(e){o();I.push(Cr);e.body=F();I.pop();i(fr);e.test=ht();if(n.ecmaVersion>=6)s(_);else M();return r(e,"DoWhileStatement")}function Ca(a){o();I.push(Cr);i(g);if(e===_)return xr(a,null);if(e===kt||e===Tt){var t=l(),s=e.keyword,u=e===Tt;o();un(t,true,s);r(t,"VariableDeclaration");if((e===Ot||n.ecmaVersion>=6&&e===p&&c==="of")&&t.declarations.length===1&&!(u&&t.declarations[0].init))return ln(a,t);return xr(a,t)}var t=v(false,true);if(e===Ot||n.ecmaVersion>=6&&e===p&&c==="of"){G(t);return ln(a,t)}return xr(a,t)}function Ta(e){o();return Fr(e,true,false)}function La(e){o();e.test=ht();e.consequent=F();e.alternate=s(Un)?F():null;return r(e,"IfStatement")}function Yn(e){if(!Gt&&!n.allowReturnOutsideFunction)u(m,"'return' outside of function");o();if(s(_)||ut())e.argument=null;else{e.argument=v();M()}return r(e,"ReturnStatement")}function $n(n){o();n.discriminant=ht();n.cases=[];i(A);I.push(ma);for(var t,a;e!=E;){if(e===hr||e===zt){var s=e===hr;if(t)r(t,"SwitchCase");n.cases.push(t=l());t.consequent=[];o();if(s)t.test=v();else{if(a)u(jt,"Multiple default clauses");a=true;t.test=null}i(w)}else{if(!t)f();t.consequent.push(F())}}if(t)r(t,"SwitchCase");o();I.pop();return r(n,"SwitchStatement")}function Kn(e){o();if(ct.test(a.slice(L,m)))u(L,"Illegal newline after throw");e.argument=v();M();return r(e,"ThrowStatement")}function Qn(t){o();t.block=It();t.handler=null;if(e===zn){var n=l();o();i(g);n.param=d();if(O&&Or(n.param.name))u(n.param.start,"Binding "+n.param.name+" in strict mode");i(h);n.guard=null;n.body=It();t.handler=r(n,"CatchClause")}t.guardedHandlers=mn;t.finalizer=s(Vn)?It():null;if(!t.handler&&!t.finalizer)u(t.start,"Missing catch or finally clause");return r(t,"TryStatement")}function Zn(e,t){o();un(e,false,t);M();return r(e,"VariableDeclaration")}function ei(e){o();e.test=ht();I.push(Cr);e.body=F();I.pop();return r(e,"WhileStatement")}function ti(e){if(O)u(m,"'with' in strict mode");o();e.object=ht();e.body=F();return r(e,"WithStatement")}function ri(e){o();return r(e,"EmptyStatement")}function ni(t,n,a){for(var i=0;i<I.length;++i)if(I[i].name===n)u(a.start,"Label '"+n+"' is already declared");var s=e.isLoop?"loop":e===ur?"switch":null;I.push({name:n,kind:s});t.body=F();I.pop();t.label=a;return r(t,"LabeledStatement")}function ii(e,t){e.expression=t;M();return r(e,"ExpressionStatement")}function ht(){i(g);var e=v();i(h);return e}function It(o){var e=l(),t=true,n;e.body=[];i(A);while(!s(E)){var a=F();e.body.push(a);if(t&&o&&Tr(a)){n=O;Dr(O=true)}t=false}if(n===false)Dr(false);return r(e,"BlockStatement")}function xr(t,n){t.init=n;i(_);t.test=e===_?null:v();i(_);t.update=e===h?null:v();i(h);t.body=F();I.pop();return r(t,"ForStatement")}function ln(t,n){var a=e===Ot?"ForInStatement":"ForOfStatement";o();t.left=n;t.right=v();i(h);t.body=F();I.pop();return r(t,a)}function un(n,a,i){n.declarations=[];n.kind=i;for(;;){var t=l();t.id=vt();G(t.id,true);if(e===w){t.id.typeAnnotation=_t();r(t.id,t.id.type)}t.init=s(rt)?v(true,a):i===Ht.keyword?f():null;n.declarations.push(r(t,"VariableDeclarator"));if(!s(b))break}return n}function v(a,n,o){var l=T();var i=ft(n,false,o);if(!a&&e===b){var t=k(l);t.expressions=[i];while(s(b))t.expressions.push(ft(n));return r(t,"SequenceExpression")}return i}function ft(i,a,s){var l=T();var t=pi(i,a,s);if(e.isAssign){var n=k(l);n.operator=c;n.left=e===rt?St(t):t;G(t);o();n.right=ft(i);return r(n,"AssignmentExpression")}return t}function pi(t,o,l){var f=T();var n=di(t,o,l);if(s(Z)){var e=k(f);if(s(rt)){var a=e.left=St(n);if(a.type!=="MemberExpression")u(a.start,"You can only use member expressions in memoization assignment");e.right=ft(t);e.operator="?=";
return r(e,"AssignmentExpression")}e.test=n;e.consequent=v(true);i(w);e.alternate=v(true,t);return r(e,"ConditionalExpression")}return n}function di(e,t,r){var n=T();return sr(Lt(r),n,-1,e,t)}function sr(a,s,l,n,f){var i=e.binop;if(i!=null&&(!n||e!==Ot)&&(!f||e!==S)){if(i>l){var t=k(s);t.left=a;t.operator=c;var u=e;o();var p=T();t.right=sr(Lt(),p,i,n);r(t,u===on||u===sn?"LogicalExpression":"BinaryExpression");return sr(t,s,l,n)}}return a}function Lt(s){if(e.prefix){var t=l(),a=e.isUpdate,i;if(e===$){i="SpreadElement"}else{i=a?"UpdateExpression":"UnaryExpression";t.operator=c;t.prefix=true}Y=true;o();t.argument=Lt();if(a)G(t.argument);else if(O&&t.operator==="delete"&&t.argument.type==="Identifier")u(t.start,"Deleting local variable in strict mode");return r(t,i)}var f=T();var n=yi(s);while(e.postfix&&!ut()){var t=k(f);t.operator=c;t.prefix=false;t.argument=n;G(n);o();n=r(t,"UpdateExpression")}return n}function yi(e){var t=T();return J(X(e),t)}function J(o,a,l){if(n.playground&&s(Yt)){var t=k(a);t.object=o;t.property=d(true);if(s(g)){t.arguments=Bt(h,false)}else{t.arguments=[]}return J(r(t,"BindMemberExpression"),a,l)}else if(s(pr)){var t=k(a);t.object=o;t.property=d(true);return J(r(t,"VirtualPropertyExpression"),a,l)}else if(s(qt)){var t=k(a);t.object=o;t.property=d(true);t.computed=false;return J(r(t,"MemberExpression"),a,l)}else if(s(q)){var t=k(a);t.object=o;t.property=v();t.computed=true;i(N);return J(r(t,"MemberExpression"),a,l)}else if(!l&&s(g)){var t=k(a);t.callee=o;t.arguments=Bt(h,false);return J(r(t,"CallExpression"),a,l)}else if(e===Zt){var t=k(a);t.tag=o;t.quasi=Br();return J(r(t,"TaggedTemplateExpression"),a,l)}return o}function X(C){switch(e){case Cn:var t=l();o();return r(t,"ThisExpression");case dr:var E=T();var t=l();var P=l();o();t.object=r(P,"ThisExpression");t.property=J(d(),E);t.computed=false;return r(t,"MemberExpression");case Sn:if(Ct)return Ui();case p:var E=T();var t=l();var y=d(e!==p);if(n.ecmaVersion>=7){if(y.name==="async"){if(e===g){o();var w=++Vt;if(e!==h){u=v();b=u.type==="SequenceExpression"?u.expressions:[u]}else{b=[]}i(h);if(Vt===w&&s(Q)){return tr(t,b,true)}else{t.callee=y;t.arguments=b;return J(r(t,"CallExpression"),E)}}else if(e===p){y=d();if(s(Q)){return tr(t,[y],true)}return y}if(e===pt){if(ut())return y;o();return Fr(t,C,true)}}else if(y.name==="await"){if(Ut)return qi(t)}}if(s(Q)){return tr(t,[y])}return y;case kr:var t=l();t.regex={pattern:c.pattern,flags:c.flags};t.value=c.value;t.raw=a.slice(m,R);o();return r(t,"Literal");case yt:case W:case Mt:var t=l();t.value=c;t.raw=a.slice(m,R);o();return r(t,"Literal");case xn:case En:case bn:var t=l();t.value=e.atomValue;t.raw=e.keyword;o();return r(t,"Literal");case g:var E=T();var u,b;o();if(n.ecmaVersion>=7&&e===Nt){u=_n(k(E),true)}else{var w=++Vt;if(e!==h){u=v();b=u.type==="SequenceExpression"?u.expressions:[u]}else{b=[]}i(h);if(Vt===w&&s(Q)){u=tr(k(E),b)}else{if(!u)f(jt);if(n.ecmaVersion>=6){for(var x=0;x<b.length;x++){if(b[x].type==="SpreadElement")f()}}if(n.preserveParens){var I=k(E);I.expression=u;u=r(I,"ParenthesizedExpression")}}}return u;case q:var t=l();o();if(n.ecmaVersion>=7&&e===Nt){return _n(t,false)}t.elements=Bt(N,true,true);return r(t,"ArrayExpression");case A:return gn();case pt:var t=l();o();return Fr(t,false,false);case xt:return Tn(l(),false);case Pn:return Ei();case Zt:return Br();case S:return lr();case Yt:return bi();default:f()}}function bi(){var e=l();o();var t=T();e.callee=J(X(),t,true);if(s(g)){e.arguments=Bt(h,false)}else{e.arguments=[]}return r(e,"BindFunctionExpression")}function Ei(){var e=l();o();var t=T();e.callee=J(X(),t,true);if(s(g))e.arguments=Bt(h,false);else e.arguments=mn;return r(e,"NewExpression")}function yn(){var e=k(n.locations?[m+1,it.offset(1)]:m+1);e.value=c;e.tail=a.charCodeAt(R-1)!==123;o();var t=e.tail?1:2;return Ti(e,"TemplateElement",n.locations?[L-t,nt.offset(-t)]:L-t)}function Br(){var t=l();t.expressions=[];var n=yn();t.quasis=[n];while(!n.tail){t.expressions.push(v());if(e!==Qt)f();t.quasis.push(n=yn())}return r(t,"TemplateLiteral")}function gn(a){var u=l(),v=true,k={};u.properties=[];o();while(!s(E)){if(!v){i(b);if(n.allowTrailingCommas&&s(E))break}else v=false;var t=l(),m,h=false,y=false;if(n.ecmaVersion>=7&&e===$){t=Lt();t.type="SpreadProperty";u.properties.push(t);continue}if(n.ecmaVersion>=6){t.method=false;t.shorthand=false;if(a){m=T()}else{h=s(z)}}if(n.ecmaVersion>=7&&e===p&&c==="async"){var I=d();if(e===w||e===g){t.key=I}else{y=true;mt(t)}}else{mt(t)}var x;if(e===S){x=K();if(e!==g)f()}if(s(w)){t.value=a?Nr(m):ft();t.kind="init"}else if(n.ecmaVersion>=6&&e===g){if(a)f();t.kind="init";t.method=true;t.value=_r(h,y)}else if(n.ecmaVersion>=5&&!t.computed&&t.key.type==="Identifier"&&(t.key.name==="get"||t.key.name==="set"||n.playground&&t.key.name==="memo")&&(e!=b&&e!=E)){if(h||y||a)f();t.kind=t.key.name;mt(t);t.value=_r(false,false)}else if(n.ecmaVersion>=6&&!t.computed&&t.key.type==="Identifier"){t.kind="init";t.value=a?Nr(m,t.key):t.key;t.shorthand=true}else f();t.value.typeParameters=x;na(t,k);u.properties.push(r(t,"Property"))}return r(u,a?"ObjectPattern":"ObjectExpression")}function mt(t){if(n.ecmaVersion>=6){if(s(q)){t.computed=true;t.key=v();i(N);return}else{t.computed=false}}t.key=e===yt||e===W?X():d(true)}function ar(e,t){e.id=null;e.params=[];if(n.ecmaVersion>=6){e.defaults=[];e.rest=null;e.generator=false}if(n.ecmaVersion>=7){e.async=t}}function Fr(t,i,a,o){ar(t,a);if(n.ecmaVersion>=6){t.generator=s(z)}if(i||e===p){t.id=d()}if(e===S){t.typeParameters=K()}kn(t);Er(t,o);return r(t,i?"FunctionDeclaration":"FunctionExpression")}function _r(i,a){var e=l();ar(e,a);kn(e);var t;if(n.ecmaVersion>=6){e.generator=i;t=true}else{t=false}Er(e,t);return r(e,"FunctionExpression")}function tr(e,n,l){ar(e,l);var a=e.defaults,s=false;for(var i=0,o=n.length-1;i<=o;i++){var t=n[i];if(t.type==="AssignmentExpression"&&t.operator==="="){s=true;n[i]=t.left;a.push(t.right)}else{St(t,i===o,true);a.push(null);if(t.type==="SpreadElement"){n.length--;e.rest=t.argument;break}}}e.params=n;if(!s)e.defaults=[];Er(e,true);return r(e,"ArrowFunctionExpression")}function kn(t){var r=[],a=false;i(g);for(;;){if(s(h)){break}else if(n.ecmaVersion>=6&&s($)){t.rest=vt();jr(t.rest);In(t.rest);i(h);r.push(null);break}else{var o=vt();In(o);t.params.push(o);if(n.ecmaVersion>=6){if(s(rt)){a=true;r.push(v(true))}else{r.push(null)}}if(!s(b)){i(h);break}}}if(a)t.defaults=r;if(e===w){t.returnType=_t()}}function In(t){if(e===w){t.typeAnnotation=_t()}else if(s(Z)){t.optional=true}r(t,t.type)}function Er(t,a){var n=a&&e!==A;var s=Ut;Ut=t.async;if(n){t.body=v(true);t.expression=true}else{var o=Gt,l=Ct,u=I;Gt=true;Ct=t.generator;I=[];t.body=It(true);t.expression=false;Gt=o;Ct=l;I=u}Ut=s;if(O||!n&&t.body.body.length&&Tr(t.body.body[0])){var i={};if(t.id)Pt(t.id,{});for(var r=0;r<t.params.length;r++)Pt(t.params[r],i);if(t.rest)Pt(t.rest,i)}}function An(e){e.declarations=[];do{e.declarations.push(d())}while(s(b));M();return r(e,"PrivateDeclaration")}function Tn(a,y){o();a.id=e===p?d():y?f():null;if(e===S){a.typeParameters=K()}a.superClass=s(Ar)?ft(false,true):null;if(a.superClass&&e===S){a.superTypeParameters=$t()}if(e===p&&c==="implements"){o();a.implements=Oi()}var u=l();u.body=[];i(A);while(!s(E)){while(s(_));if(e===E)continue;var t=l();if(n.ecmaVersion>=7&&e===p&&c==="private"){o();u.body.push(An(t));continue}if(e===p&&c==="static"){o();t["static"]=true}else{t["static"]=false}var m=false;var h=s(z);if(n.ecmaVersion>=7&&!h&&e===p&&c==="async"){var b=d();if(e===w||e===g){t.key=b}else{m=true;mt(t)}}else{mt(t)}if(e!==g&&!t.computed&&t.key.type==="Identifier"&&(t.key.name==="get"||t.key.name==="set"||n.playground&&t.key.name==="memo")){if(h||m)f();t.kind=t.key.name;mt(t)}else{t.kind=""}if(e===w){if(h||m)f();t.typeAnnotation=_t();M();u.body.push(r(t,"ClassProperty"))}else{var v;if(e===S){v=K()}t.value=_r(h,m);t.value.typeParameters=v;u.body.push(r(t,"MethodDefinition"))}}a.body=r(u,"ClassBody");return r(a,y?"ClassDeclaration":"ClassExpression")}function Oi(){var n=[];do{var t=l();t.id=d();if(e===S){t.typeParameters=$t()}else{t.typeParameters=null}n.push(r(t,"ClassImplements"))}while(s(b));return n}function Bt(r,o,l){var t=[],a=true;while(!s(r)){if(!a){i(b);if(o&&n.allowTrailingCommas&&s(r))break}else a=false;if(l&&e===b)t.push(null);else t.push(v(true))}return t}function d(t){var i=l();if(t&&n.forbidReserved=="everywhere")t=false;if(e===p){if(!t&&(n.forbidReserved&&(n.ecmaVersion===3?ai:si)(c)||O&&Mr(c))&&a.slice(m,R).indexOf("\\")==-1)u(m,"The keyword '"+c+"' is reserved");i.name=c}else if(t&&e.keyword){i.name=e.keyword}else{f()}Y=false;o();return r(i,"Identifier")}function Ni(t){o();if(e===kt||e===Ht||e===Tt||e===pt||e===xt||e===p&&c==="async"){t.declaration=F();t["default"]=false;t.specifiers=null;t.source=null}else if(s(zt)){var n=t.declaration=v(true);if(n.id){if(n.type==="FunctionExpression"){n.type="FunctionDeclaration"}else if(n.type==="ClassExpression"){n.type="ClassDeclaration"}}t["default"]=true;t.specifiers=null;t.source=null;M()}else{var i=e===z;t.declaration=null;t["default"]=false;t.specifiers=Fi();if(e===p&&c==="from"){o();t.source=e===W?X():f()}else{if(i)f();t.source=null}M()}return r(t,"ExportDeclaration")}function Fi(){var a=[],u=true;if(e===z){var t=l();o();a.push(r(t,"ExportBatchSpecifier"))}else{i(A);while(!s(E)){if(!u){i(b);if(n.allowTrailingCommas&&s(E))break}else u=false;var t=l();t.id=d(e===zt);if(e===p&&c==="as"){o();t.name=d(true)}else{t.name=null}a.push(r(t,"ExportSpecifier"))}}return a}function Bi(t){o();if(e===W){t.specifiers=[];t.source=X()}else{t.specifiers=Vi();if(e!==p||c!=="from")f();o();t.source=e===W?X():f()}M();return r(t,"ImportDeclaration")}function Vi(){var a=[],u=true;if(e===p){var t=l();t.id=l();t.name=d();G(t.name,true);t.id.name="default";r(t.id,"Identifier");a.push(r(t,"ImportSpecifier"));if(!s(b))return a}if(e===z){var t=l();o();if(e!==p||c!=="as")f();o();t.name=d();G(t.name,true);a.push(r(t,"ImportBatchSpecifier"));return a}i(A);while(!s(E)){if(!u){i(b);if(n.allowTrailingCommas&&s(E))break}else u=false;var t=l();t.id=d(true);if(e===p&&c==="as"){o();t.name=d()}else{t.name=null}G(t.name||t.id,true);t["default"]=false;a.push(r(t,"ImportSpecifier"))}return a}function Ui(){var e=l();o();if(s(_)||ut()){e.delegate=false;e.argument=null}else{e.delegate=s(z);e.argument=v(true)}return r(e,"YieldExpression")}function qi(e){if(s(_)||ut()){f()}e.delegate=s(z);e.argument=v(true);return r(e,"AwaitExpression")}function _n(t,a){t.blocks=[];while(e===Nt){var n=l();o();i(g);n.left=vt();G(n.left,true);if(e!==p||c!=="of")f();o();n.of=true;n.right=v();i(h);t.blocks.push(r(n,"ComprehensionBlock"))}t.filter=s(Pr)?ht():null;t.body=v();i(a?h:N);t.generator=a;return r(t,"ComprehensionExpression")}function Dt(e){if(e.type==="XJSIdentifier"){return e.name}if(e.type==="XJSNamespacedName"){return e.namespace.name+":"+e.name.name}if(e.type==="XJSMemberExpression"){return Dt(e.object)+"."+Dt(e.property)}}function wt(){var t=l();if(e===br){t.name=c}else if(e.keyword){t.name=e.keyword}else{f()}Y=false;o();return r(t,"XJSIdentifier")}function On(){var e=l();e.namespace=wt();i(w);e.name=wt();return r(e,"XJSNamespacedName")}function Hi(){var n=T();var e=wt();while(s(qt)){var t=k(n);t.object=e;t.property=wt();e=r(t,"XJSMemberExpression")}return e}function Dn(){switch(at()){case":":return On();case".":return Hi();default:return wt()}}function Yi(){if(at()===":"){return On()}return wt()}function $i(){switch(e){case A:var t=Rn();if(t.expression.type==="XJSEmptyExpression"){u(t.start,"XJS attributes must only be assigned a non-empty "+"expression")}return t;case S:return lr();case Mt:return X();default:u(m,"XJS value should be either an expression or a quoted XJS text")}}function Ki(){if(e!==E){f()}var t;t=m;m=L;L=t;t=it;it=nt;nt=t;return r(l(),"XJSEmptyExpression")}function Rn(){var n=l();var a=C,s=P;C=false;P=false;o();n.expression=e===E?Ki():v();C=a;P=s;if(P){t=R}i(E);return r(n,"XJSExpressionContainer")}function Zi(){if(e===A){var a=m,s=it;var u=C;C=false;o();if(e!==$)f();var t=Lt();C=u;i(E);t.type="XJSSpreadAttribute";t.start=a;t.end=L;if(n.locations){t.loc.start=s;t.loc.end=nt}if(n.ranges){t.range=[a,L]}return t}var t=l();t.name=Yi();if(e===rt){o();t.value=$i()}else{t.value=null}return r(t,"XJSAttribute")}function ea(){switch(e){case A:return Rn();case Mt:return X();default:return lr()}}function ta(){var t=l(),n=t.attributes=[];var a=P;var u=C;P=false;C=true;o();t.name=Dn();while(e!==gt&&e!==Ft&&e!==H){n.push(Zi())}C=false;if(t.selfClosing=!!s(Ft)){C=u;P=a}else{P=true}i(H);return r(t,"XJSOpeningElement")}function ra(){var e=l();var n=P;var a=C;P=false;C=true;Y=false;i(or);e.name=Dn();st();P=n;C=a;Y=false;if(P){t=R}i(H);return r(e,"XJSClosingElement")}function lr(){var t=l();var a=[];var s=P;var n=ta();var i=null;if(!n.selfClosing){while(e!==gt&&e!==or){P=true;a.push(ea())}P=s;i=ra();if(Dt(i.name)!==Dt(n.name)){u(i.start,"Expected corresponding XJS closing tag for '"+Dt(n.name)+"'")}}if(!s&&e===S){u(m,"Adjacent XJS elements must be wrapped in an enclosing tag")}t.openingElement=n;t.closingElement=i;t.children=a;return r(t,"XJSElement")}function ia(e){o();Bn(e,true);return r(e,"DeclareClass")}function aa(a){o();var n=a.id=d();var t=l();var s=l();if(e===S){t.typeParameters=K()}else{t.typeParameters=null}i(g);var u=wr();t.params=u.params;t.rest=u.rest;i(h);i(w);t.returnType=D();s.typeAnnotation=r(t,"FunctionTypeAnnotation");n.typeAnnotation=r(s,"TypeAnnotation");r(n,n.type);M();return r(a,"DeclareFunction")}function Fn(t){if(e===xt){return ia(t)}else if(e===pt){return aa(t)}else if(e===kt){return oa(t)}else if(e===p&&c==="module"){return la(t)}else{f()}}function oa(e){o();e.id=Qi();M();return r(e,"DeclareVariable")}function la(t){o();if(e===W){t.id=X()}else{t.id=d()}var n=t.body=l();var a=n.body=[];i(A);while(e!==E){var s=l();o();a.push(Fn(s))}i(E);r(n,"BlockStatement");return r(t,"DeclareModule")}function Bn(t,r){t.id=d();if(e===S){t.typeParameters=K()}else{t.typeParameters=null}t.extends=[];if(s(Ar)){do{t.extends.push(fa())}while(s(b))}t.body=Gn(r)}function fa(){var t=l();t.id=d();if(e===S){t.typeParameters=$t()}else{t.typeParameters=null}return r(t,"InterfaceExtends")}function ca(e){Bn(e,false);return r(e,"InterfaceDeclaration")}function pa(t){t.id=d();if(e===S){t.typeParameters=K()}else{t.typeParameters=null}i(rt);t.right=D();M();return r(t,"TypeAlias")}function K(){var t=l();t.params=[];i(S);while(e!==H){t.params.push(d());if(e!==H){i(b)}}i(H);return r(t,"TypeParameterDeclaration")}function $t(){var t=l(),n=ot;t.params=[];ot=true;i(S);while(e!==H){t.params.push(D());if(e!==H){i(b)}}i(H);ot=n;return r(t,"TypeParameterInstantiation")}function qn(){return e===yt||e===W?X():d(true)}function ya(e,t){e.static=t;i(q);e.id=qn();i(w);e.key=D();i(N);i(w);e.value=D();return r(e,"ObjectTypeIndexer")}function Xn(t){t.params=[];t.rest=null;t.typeParameters=null;if(e===S){t.typeParameters=K()}i(g);while(e===p){t.params.push(er());if(e!==h){i(b)}}if(s($)){t.rest=er()}i(h);i(w);t.returnType=D();return r(t,"FunctionTypeAnnotation")}function ga(t,n,i){var e=k(t);e.value=Xn(k(t));e.static=n;e.key=i;e.optional=false;return r(e,"ObjectTypeProperty")}function ba(e,t){var n=l();e.static=t;e.value=Xn(n);return r(e,"ObjectTypeCallProperty")}function Gn(m){var t=l();var n;var h=false;var v;var u;var b;var x;var a;t.callProperties=[];t.properties=[];t.indexers=[];i(A);while(e!==E){var y=T();n=l();if(m&&e===p&&c==="static"){o();a=true}if(e===q){t.indexers.push(ya(n,a))}else if(e===g||e===S){t.callProperties.push(ba(n,m))}else{if(a&&e===w){u=d()}else{u=qn()}if(e===S||e===g){t.properties.push(ga(y,a,u))}else{if(s(Z)){h=true}i(w);n.key=u;n.value=D();n.optional=h;n.static=a;t.properties.push(r(n,"ObjectTypeProperty"))}}if(!s(_)&&e!==E){f()}}i(E);return r(t,"ObjectTypeAnnotation")}function xa(i,a){var t=k(i);t.typeParameters=null;t.id=a;while(s(qt)){var n=k(i);n.qualification=t.id;n.id=d();t.id=r(n,"QualifiedTypeIdentifier")}if(e===S){t.typeParameters=$t()}return r(t,"GenericTypeAnnotation")}function Sa(){var e=l();i(Xt["void"]);return r(e,"VoidTypeAnnotation")}function wa(){var e=l();i(Xt["typeof"]);e.argument=Hn();return r(e,"TypeofTypeAnnotation")}function ka(){var n=l();n.types=[];i(q);while(t<U&&e!==N){n.types.push(D());if(e===N)break;i(b)}i(N);return r(n,"TupleTypeAnnotation")}function er(){var t=false;var e=l();e.name=d();if(s(Z)){t=true}i(w);e.optional=t;e.typeAnnotation=D();return r(e,"FunctionTypeParam")}function wr(){var t={params:[],rest:null};while(e===p){t.params.push(er());if(e!==h){i(b)}}if(s($)){t.rest=er()}return t}function Aa(n,e,t){switch(t.name){case"any":return r(e,"AnyTypeAnnotation");case"bool":case"boolean":return r(e,"BooleanTypeAnnotation");case"number":return r(e,"NumberTypeAnnotation");case"string":return r(e,"StringTypeAnnotation");default:return xa(n,t)}}function Hn(){var P=null;var w=null;var C=null;var E=T();var t=l();var x=null;var n;var k;var I;var y;var b=false;switch(e){case p:return Aa(E,t,d());case A:return Gn();case q:return ka();case S:t.typeParameters=K();i(g);n=wr();t.params=n.params;t.rest=n.rest;i(h);i(Q);t.returnType=D();return r(t,"FunctionTypeAnnotation");case g:o();var v;if(e!==h&&e!==$){if(e===p){}else{b=true}}if(b){if(v&&h){y=v}else{y=D();i(h)}if(s(Q)){u(t,"Unexpected token =>. It looks like "+"you are trying to write a function type, but you ended up "+"writing a grouped type followed by an =>, which is a syntax "+"error. Remember, function type parameters are named so function "+"types look like (name1: type1, name2: type2) => returnType. You "+"probably wrote (type1) => returnType")}return y}n=wr();t.params=n.params;t.rest=n.rest;i(h);i(Q);t.returnType=D();t.typeParameters=null;return r(t,"FunctionTypeAnnotation");case W:t.value=c;t.raw=a.slice(m,R);o();return r(t,"StringLiteralTypeAnnotation");default:if(e.keyword){switch(e.keyword){case"void":return Sa();case"typeof":return wa()}}}f()}function Pa(){var t=l();var n=t.elementType=Hn();if(e===q){i(q);i(N);return r(t,"ArrayTypeAnnotation")}return n}function vr(){var e=l();if(s(Z)){e.typeAnnotation=vr();return r(e,"NullableTypeAnnotation")}return Pa()}function Wr(){var e=l();var t=vr();e.types=[t];while(s(rn)){e.types.push(vr())}return e.types.length===1?t:r(e,"IntersectionTypeAnnotation")}function Mi(){var e=l();var t=Wr();e.types=[t];while(s(an)){e.types.push(Wr())}return e.types.length===1?t:r(e,"UnionTypeAnnotation")}function D(){var e=ot;ot=true;var t=Mi();ot=e;return t}function _t(){var e=l();i(w);e.typeAnnotation=D();return r(e,"TypeAnnotation")}function Qi(a,o){var u=l();var t=d();var n=false;if(o&&s(Z)){i(Z);n=true}if(a||e===w){t.typeAnnotation=_t();r(t,t.type)}if(n){t.optional=true;r(t,t.type)}return t}})},{}],2:[function(e,t,r){(function(n){var r=t.exports=e("./transformation/transform");r.version=e("../../package").version;r.transform=r;r.run=function(t,e){e=e||{};e.sourceMap="inline";return new Function(r(t,e).code)()};r.load=function(i,a,t,s){t=t||{};t.filename=t.filename||i;var e=n.ActiveXObject?new n.ActiveXObject("Microsoft.XMLHTTP"):new n.XMLHttpRequest;e.open("GET",i,true);if("overrideMimeType"in e)e.overrideMimeType("text/plain");e.onreadystatechange=function(){if(e.readyState!==4)return;var n=e.status;if(n===0||n===200){var o=[e.responseText,t];if(!s)r.run.apply(r,o);if(a)a(o)}else{throw new Error("Could not load "+i)}};e.send(null)};var i=function(){var e=[];var l=["text/ecmascript-6","text/6to5","module"];var a=0;var i=function(){var t=e[a];if(t instanceof Array){r.run.apply(r,t);a++;i()}};var u=function(t,a){var n={};if(t.src){r.load(t.src,function(t){e[a]=t;i()},n,true)}else{n.filename="embedded";e[a]=[t.innerHTML,n]}};var s=n.document.getElementsByTagName("script");for(var t=0;t<s.length;++t){var o=s[t];if(l.indexOf(o.type)>=0)e.push(o)}for(t in e){u(e[t],t)}i()};if(n.addEventListener){n.addEventListener("DOMContentLoaded",i,false)}else if(n.attachEvent){n.attachEvent("onload",i)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../package":188,"./transformation/transform":39}],3:[function(i,o,f){o.exports=e;var s=/^\#\!.*/;var a=i("./transformation/transform");var u=i("./generation/generator");var l=i("./traverse/scope");var n=i("./util");var t=i("./types");var r=i("lodash");function e(t){this.dynamicImports=[];this.dynamicImportIds={};this.opts=e.normaliseOptions(t);this.transformers=this.getTransformers();this.uids={};this.ast={}}e.helpers=["inherits","defaults","prototype-properties","apply-constructor","tagged-template-literal","tagged-template-literal-loose","interop-require","to-array","sliced-to-array","object-without-properties","has-own","slice","bind","define-property","async-to-generator","interop-require-wildcard","typeof","extends","get"];e.excludeHelpersFromRuntime=["async-to-generator","typeof","tagged-template-literal-loose"];e.normaliseOptions=function(e){e=r.cloneDeep(e||{});r.defaults(e,{keepModuleIdExtensions:false,includeRegenerator:false,experimental:false,reactCompat:false,playground:false,whitespace:true,moduleIds:e.amdModuleIds||false,blacklist:[],whitelist:[],sourceMap:false,optional:[],comments:true,filename:"unknown",modules:"common",runtime:false,loose:[],code:true,ast:true});e.filename=e.filename.replace(/\\/g,"/");e.blacklist=n.arrayify(e.blacklist);e.whitelist=n.arrayify(e.whitelist);e.optional=n.arrayify(e.optional);e.loose=n.arrayify(e.loose);r.each({fastForOf:"forOf",classesFastSuper:"classes"},function(n,t){if(r.contains(e.optional,t)){r.pull(e.optional,t);e.loose.push(n)}});r.defaults(e,{moduleRoot:e.sourceRoot});r.defaults(e,{sourceRoot:e.moduleRoot});r.defaults(e,{filenameRelative:e.filename});r.defaults(e,{sourceFileName:e.filenameRelative,sourceMapName:e.filenameRelative});if(e.runtime===true){e.runtime="to5Runtime"}if(e.playground){e.experimental=true}a._ensureTransformerNames("blacklist",e.blacklist);a._ensureTransformerNames("whitelist",e.whitelist);a._ensureTransformerNames("optional",e.optional);a._ensureTransformerNames("loose",e.loose);return e};e.prototype.isLoose=function(e){return r.contains(this.opts.loose,e)};e.prototype.getTransformers=function(){var e=this;var t=[];var n=[];r.each(a.transformers,function(r){if(r.canRun(e)){t.push(r);if(r.secondPass){n.push(r)}if(r.manipulateOptions){r.manipulateOptions(e.opts,e)}}});return t.concat(n)};e.prototype.toArray=function(e,r){if(t.isArrayExpression(e)){return e}else if(t.isIdentifier(e)&&e.name==="arguments"){return t.callExpression(t.memberExpression(this.addHelper("slice"),t.identifier("call")),[e])}else{var n="to-array";var i=[e];if(r){i.push(t.literal(r));n="sliced-to-array"}return t.callExpression(this.addHelper(n),i)}};e.prototype.getModuleFormatter=function(e){var t=r.isFunction(e)?e:a.moduleFormatters[e];if(!t){var s=n.resolve(e);if(s)t=i(s)}if(!t){throw new ReferenceError("Unknown module formatter type "+JSON.stringify(e))}return new t(this)};e.prototype.parseShebang=function(e){var t=e.match(s);if(t){this.shebang=t[0];e=e.replace(s,"")}return e};e.prototype.addImport=function(n,e){e=e||n;var r=this.dynamicImportIds[e];if(!r){r=this.dynamicImportIds[e]=this.generateUidIdentifier(e);var a=[t.importSpecifier(t.identifier("default"),r)];var i=t.importDeclaration(a,t.literal(n));i._blockHoist=3;this.dynamicImports.push(i)}return r};e.prototype.addHelper=function(i){if(!r.contains(e.helpers,i)){throw new ReferenceError("unknown declaration "+i)}var a=this.ast.program;var s=a._declarations&&a._declarations[i];if(s)return s.id;var o;var l=this.opts.runtime;if(l&&!r.contains(e.excludeHelpersFromRuntime,i)){i=t.identifier(t.toIdentifier(i));return t.memberExpression(t.identifier(l),i)}else{o=n.template(i)}var u=this.generateUidIdentifier(i);this.scope.push({key:i,id:u,init:o});return u};e.prototype.errorWithNode=function(n,i,e){e=e||SyntaxError;var t=n.loc.start;var r=new e("Line "+t.line+": "+i);r.loc=t;return r};e.prototype.addCode=function(e){e=(e||"")+"";this.code=e;return this.parseShebang(e)};e.prototype.parse=function(e){var t=this;e=this.addCode(e);return n.parse(this.opts,e,function(e){t.transform(e);return t.generate()})};e.prototype.transform=function(t){var e=this;this.ast=t;this.scope=new l(t.program);this.moduleFormatter=this.getModuleFormatter(this.opts.modules);var n=function(t){r.each(e.transformers,function(r){r.astRun(e,t)})};n("enter");r.each(this.transformers,function(t){t.transform(e)});n("exit")};e.prototype.generate=function(){var t=this.opts;var r=this.ast;var e={code:"",map:null,ast:null};if(t.ast)e.ast=r;if(!t.code)return e;var i=u(r,t,this.code);e.code=i.code;e.map=i.map;if(this.shebang){e.code=this.shebang+"\n"+e.code}if(t.sourceMap==="inline"){e.code+="\n"+n.sourceMapToComment(e.map)}return e};e.prototype.generateUid=function(e,r){e=t.toIdentifier(e).replace(/^_+/,"");r=r||this.scope;var n;do{n=this._generateUid(e)}while(r.has(n));return n};e.prototype.generateUidIdentifier=function(e,r){return t.identifier(this.generateUid(e,r))};e.prototype._generateUid=function(e){var r=this.uids;var t=r[e]||1;var n=e;if(t>1)n+=t;r[e]=t+1;return"_"+n}},{"./generation/generator":5,"./transformation/transform":39,"./traverse/scope":82,"./types":85,"./util":87,lodash:135}],4:[function(n,i,a){i.exports=e;var t=n("../util");var r=n("lodash");function e(t,e){this.position=t;this._indent=e.indent.base;this.format=e;this.buf=""}e.prototype.get=function(){return t.trimRight(this.buf)};e.prototype.getIndent=function(){if(this.format.compact){return""}else{return t.repeat(this._indent,this.format.indent.style)}};e.prototype.indentSize=function(){return this.getIndent().length};e.prototype.indent=function(){this._indent++};e.prototype.dedent=function(){this._indent--};e.prototype.semicolon=function(){this.push(";")};e.prototype.ensureSemicolon=function(){if(!this.isLast(";"))this.semicolon()};e.prototype.rightBrace=function(){this.newline(true);this.push("}")};e.prototype.keyword=function(e){this.push(e);this.push(" ")};e.prototype.space=function(){if(this.buf&&!this.isLast([" ","\n"])){this.push(" ")}};e.prototype.removeLast=function(e){if(!this.isLast(e))return;this.buf=this.buf.substr(0,this.buf.length-1);this.position.unshift(e)};e.prototype.newline=function(e,n){if(this.format.compact)return;n=n||false;if(r.isNumber(e)){if(this.endsWith("{\n"))e--;if(this.endsWith(t.repeat(e,"\n")))return;while(e--){this._newline(n)}return}if(r.isBoolean(e)){n=e}this._newline(n)};e.prototype._newline=function(e){if(e&&this.isLast("\n"))this.removeLast("\n");this.removeLast(" ");this._removeSpacesAfterLastNewline();this._push("\n")};e.prototype._removeSpacesAfterLastNewline=function(){var t=this.buf.lastIndexOf("\n");if(t===-1)return;var e=this.buf.length-1;while(e>t){if(this.buf[e]!==" "){break}e--}if(e===t){this.buf=this.buf.substring(0,e+1)}};e.prototype.push=function(e,r){if(this._indent&&!r&&e!=="\n"){var t=this.getIndent();e=e.replace(/\n/g,"\n"+t);if(this.isLast("\n"))e=t+e}this._push(e)};e.prototype._push=function(e){this.position.push(e);this.buf+=e};e.prototype.endsWith=function(e){var t=this.buf.length-e.length;return t>=0&&this.buf.lastIndexOf(e)===t};e.prototype.isLast=function(n,a){var e=this.buf;if(a)e=t.trimRight(e);var i=e[e.length-1];if(Array.isArray(n)){return r.contains(n,i)}else{return n===i}}},{"../util":87,lodash:135}],5:[function(e,a,c){a.exports=function(e,r,n){var i=new t(e,r,n);return i.generate()};a.exports.CodeGenerator=t;var o=e("./whitespace");var l=e("./source-map");var u=e("./position");var s=e("./buffer");var f=e("../util");var n=e("./node");var i=e("../types");var r=e("lodash");function t(r,e,n){e=e||{};this.comments=r.comments||[];this.tokens=r.tokens||[];this.format=t.normaliseOptions(e);this.ast=r;this.whitespace=new o(this.tokens,this.comments);this.position=new u;this.map=new l(this.position,e,n);this.buffer=new s(this.position,this.format)}r.each(s.prototype,function(e,r){t.prototype[r]=function(){return e.apply(this.buffer,arguments)}});t.normaliseOptions=function(e){return r.merge({parentheses:true,comments:e.comments==null||e.comments,compact:false,indent:{adjustMultilineComment:true,style:" ",base:0}},e.format||{})};t.generators={templateLiterals:e("./generators/template-literals"),comprehensions:e("./generators/comprehensions"),expressions:e("./generators/expressions"),statements:e("./generators/statements"),playground:e("./generators/playground"),classes:e("./generators/classes"),methods:e("./generators/methods"),modules:e("./generators/modules"),types:e("./generators/types"),flow:e("./generators/flow"),base:e("./generators/base"),jsx:e("./generators/jsx")};r.each(t.generators,function(e){r.extend(t.prototype,e)});t.prototype.generate=function(){var e=this.ast;this.print(e);var t=[];r.each(e.comments,function(e){if(!e._displayed)t.push(e)});this._printComments(t);return{map:this.map.get(),code:this.buffer.get()}};t.prototype.buildPrint=function(r){var t=this;var e=function(e,n){return t.print(e,r,n)};e.sequence=function(n,r){r=r||{};r.statement=true;return t.printJoin(e,n,r)};e.join=function(r,n){return t.printJoin(e,r,n)};e.block=function(r){return t.printBlock(e,r)};e.indentOnComments=function(r){return t.printAndIndentOnComments(e,r)};return e};t.prototype.print=function(e,t,r){if(!e)return"";var i=this;r=r||{};var s=function(s){if(!r.statement&&!n.isUserWhitespacable(e,t)){return}var a=0;if(e.start!=null&&!e._ignoreUserWhitespace){if(s){a=i.whitespace.getNewlinesBefore(e)}else{a=i.whitespace.getNewlinesAfter(e)}}else{if(!s)a++;var o=n.needsWhitespaceAfter;if(s)o=n.needsWhitespaceBefore;a+=o(e,t);if(!i.buffer.get())a=0}i.newline(a)};if(this[e.type]){var a=n.needsParensNoLineTerminator(e,t);var o=a||n.needsParens(e,t);if(o)this.push("(");if(a)this.indent();this.printLeadingComments(e,t);s(true);if(r.before)r.before();this.map.mark(e,"start");this[e.type](e,this.buildPrint(e),t);if(a){this.newline();this.dedent()}if(o)this.push(")");this.map.mark(e,"end");if(r.after)r.after();s(false);this.printTrailingComments(e,t)}else{throw new ReferenceError("unknown node of type "+JSON.stringify(e.type)+" with constructor "+JSON.stringify(e&&e.constructor.name))}};t.prototype.printJoin=function(i,t,e){if(!t||!t.length)return;e=e||{};var n=this;var a=t.length;if(e.indent)n.indent();r.each(t,function(t,r){i(t,{statement:e.statement,after:function(){if(e.iterator){e.iterator(t,r)}if(e.separator&&r<a-1){n.push(e.separator)}}})});if(e.indent)n.dedent()};t.prototype.printAndIndentOnComments=function(r,e){var t=!!e.leadingComments;if(t)this.indent();r(e);if(t)this.dedent()};t.prototype.printBlock=function(t,e){if(i.isEmptyStatement(e)){this.semicolon()}else{this.push(" ");t(e)}};t.prototype.generateComment=function(t){var e=t.value;if(t.type==="Line"){e="//"+e}else{e="/*"+e+"*/"}return e};t.prototype.printTrailingComments=function(e,t){this._printComments(this.getComments("trailingComments",e,t))};t.prototype.printLeadingComments=function(e,t){this._printComments(this.getComments("leadingComments",e,t))};t.prototype.getComments=function(a,e,s){if(i.isExpressionStatement(s)){return[]}var t=[];var n=[e];var o=this;if(i.isExpressionStatement(e)){n.push(e.argument)}r.each(n,function(e){t=t.concat(o._getComments(a,e))});return t};t.prototype._getComments=function(t,e){return e&&e[t]||[]};t.prototype._printComments=function(t){if(this.format.compact)return;if(!this.format.comments)return;if(!t||!t.length)return;var e=this;r.each(t,function(n){var a=false;r.each(e.ast.comments,function(e){if(e.start===n.start){if(e._displayed)a=true;e._displayed=true;return false}});if(a)return;e.newline(e.whitespace.getNewlinesBefore(n));var i=e.position.column;var t=e.generateComment(n);if(i&&!e.isLast(["\n"," ","[","{"])){e._push(" ");i++}if(n.type==="Block"&&e.format.indent.adjustMultilineComment){var s=n.loc.start.column;if(s){var o=new RegExp("\\n\\s{1,"+s+"}","g");t=t.replace(o,"\n")}var l=Math.max(e.indentSize(),i);t=t.replace(/\n/g,"\n"+f.repeat(l))}if(i===0){t=e.getIndent()+t}e._push(t);e.newline(e.whitespace.getNewlinesAfter(n))})}},{"../types":85,"../util":87,"./buffer":4,"./generators/base":6,"./generators/classes":7,"./generators/comprehensions":8,"./generators/expressions":9,"./generators/flow":10,"./generators/jsx":11,"./generators/methods":12,"./generators/modules":13,"./generators/playground":14,"./generators/statements":15,"./generators/template-literals":16,"./generators/types":17,"./node":18,"./position":21,"./source-map":22,"./whitespace":23,lodash:135}],6:[function(t,r,e){e.File=function(e,t){t(e.program)
};e.Program=function(e,t){t.sequence(e.body)};e.BlockStatement=function(e,t){if(e.body.length===0){this.push("{}")}else{this.push("{");this.newline();t.sequence(e.body,{indent:true});this.removeLast("\n");this.rightBrace()}}},{}],7:[function(t,r,e){e.ClassExpression=e.ClassDeclaration=function(e,t){this.push("class");if(e.id){this.space();t(e.id)}if(e.superClass){this.push(" extends ");t(e.superClass)}this.space();t(e.body)};e.ClassBody=function(e,t){if(e.body.length===0){this.push("{}")}else{this.push("{");this.newline();this.indent();t.sequence(e.body);this.dedent();this.rightBrace()}};e.MethodDefinition=function(e,t){if(e.static){this.push("static ")}this._method(e,t)}},{}],8:[function(t,r,e){e.ComprehensionBlock=function(e,t){this.keyword("for");this.push("(");t(e.left);this.push(" of ");t(e.right);this.push(")")};e.ComprehensionExpression=function(e,t){this.push(e.generator?"(":"[");t.join(e.blocks,{separator:" "});this.space();if(e.filter){this.keyword("if");this.push("(");t(e.filter);this.push(")");this.space()}t(e.body);this.push(e.generator?")":"]")}},{}],9:[function(r,o,e){var i=r("../../util");var t=r("../../types");var a=r("lodash");e.UnaryExpression=function(e,i){var n=/[a-z]$/.test(e.operator);var r=e.argument;if(t.isUpdateExpression(r)||t.isUnaryExpression(r)){n=true}if(t.isUnaryExpression(r)&&r.operator==="!"){n=false}this.push(e.operator);if(n)this.space();i(e.argument)};e.UpdateExpression=function(e,t){if(e.prefix){this.push(e.operator);t(e.argument)}else{t(e.argument);this.push(e.operator)}};e.ConditionalExpression=function(e,t){t(e.test);this.push(" ? ");t(e.consequent);this.push(" : ");t(e.alternate)};e.NewExpression=function(e,t){this.push("new ");t(e.callee);if(e.arguments.length||this.format.parentheses){this.push("(");t.join(e.arguments,{separator:", "});this.push(")")}};e.SequenceExpression=function(e,t){t.join(e.expressions,{separator:", "})};e.ThisExpression=function(){this.push("this")};e.CallExpression=function(e,r){r(e.callee);this.push("(");var t=",";if(e._prettyCall){t+="\n";this.newline();this.indent()}else{t+=" "}r.join(e.arguments,{separator:t});if(e._prettyCall){this.newline();this.dedent()}this.push(")")};var n=function(e){return function(t,r){this.push(e);if(t.delegate)this.push("*");if(t.argument){this.space();r(t.argument)}}};e.YieldExpression=n("yield");e.AwaitExpression=n("await");e.EmptyStatement=function(){this.semicolon()};e.ExpressionStatement=function(e,t){t(e.expression);this.semicolon()};e.BinaryExpression=e.LogicalExpression=e.AssignmentPattern=e.AssignmentExpression=function(e,t){t(e.left);this.push(" "+e.operator+" ");t(e.right)};var s=/e/i;e.MemberExpression=function(e,n){var r=e.object;n(r);if(!e.computed&&t.isMemberExpression(e.property)){throw new TypeError("Got a MemberExpression for MemberExpression property")}var o=e.computed;if(t.isLiteral(e.property)&&a.isNumber(e.property.value)){o=true}if(o){this.push("[");n(e.property);this.push("]")}else{if(t.isLiteral(r)&&i.isInteger(r.value)&&!s.test(r.value.toString())){this.push(".")}this.push(".");n(e.property)}}},{"../../types":85,"../../util":87,lodash:135}],10:[function(t,r,e){e.AnyTypeAnnotation=e.ArrayTypeAnnotation=e.BooleanTypeAnnotation=e.ClassProperty=e.DeclareClass=e.DeclareFunction=e.DeclareModule=e.DeclareVariable=e.FunctionTypeAnnotation=e.FunctionTypeParam=e.GenericTypeAnnotation=e.InterfaceExtends=e.InterfaceDeclaration=e.IntersectionTypeAnnotation=e.NullableTypeAnnotation=e.NumberTypeAnnotation=e.StringLiteralTypeAnnotation=e.StringTypeAnnotation=e.TupleTypeAnnotation=e.TypeofTypeAnnotation=e.TypeAlias=e.TypeAnnotation=e.TypeParameterDeclaration=e.TypeParameterInstantiation=e.ObjectTypeAnnotation=e.ObjectTypeCallProperty=e.ObjectTypeIndexer=e.ObjectTypeProperty=e.QualifiedTypeIdentifier=e.UnionTypeAnnotation=e.VoidTypeAnnotation=function(){}},{}],11:[function(t,i,e){var r=t("../../types");var n=t("lodash");e.XJSAttribute=function(e,t){t(e.name);if(e.value){this.push("=");t(e.value)}};e.XJSIdentifier=function(e){this.push(e.name)};e.XJSNamespacedName=function(e,t){t(e.namespace);this.push(":");t(e.name)};e.XJSMemberExpression=function(e,t){t(e.object);this.push(".");t(e.property)};e.XJSSpreadAttribute=function(e,t){this.push("{...");t(e.argument);this.push("}")};e.XJSExpressionContainer=function(e,t){this.push("{");t(e.expression);this.push("}")};e.XJSElement=function(e,t){var a=this;var i=e.openingElement;t(i);if(i.selfClosing)return;this.indent();n.each(e.children,function(e){if(r.isLiteral(e)){a.push(e.value)}else{t(e)}});this.dedent();t(e.closingElement)};e.XJSOpeningElement=function(e,t){this.push("<");t(e.name);if(e.attributes.length>0){this.space();t.join(e.attributes,{separator:" "})}this.push(e.selfClosing?" />":">")};e.XJSClosingElement=function(e,t){this.push("</");t(e.name);this.push(">")};e.XJSEmptyExpression=function(){}},{"../../types":85,lodash:135}],12:[function(t,n,e){var r=t("../../types");e._params=function(e,t){var r=this;this.push("(");t.join(e.params,{separator:", ",iterator:function(a,i){var n=e.defaults&&e.defaults[i];if(n){r.push(" = ");t(n)}}});if(e.rest){if(e.params.length){this.push(", ")}this.push("...");t(e.rest)}this.push(")")};e._method=function(e,t){var r=e.value;var n=e.kind;var i=e.key;if(!n||n==="init"){if(r.generator){this.push("*")}}else{this.push(n+" ")}if(r.async)this.push("async ");if(e.computed){this.push("[");t(i);this.push("]")}else{t(i)}this._params(r,t);this.space();t(r.body)};e.FunctionDeclaration=e.FunctionExpression=function(e,t){if(e.async)this.push("async ");this.push("function");if(e.generator)this.push("*");this.space();if(e.id)t(e.id);this._params(e,t);this.space();t(e.body)};e.ArrowFunctionExpression=function(e,t){if(e.async)this.push("async ");if(e.params.length===1&&!e.defaults.length&&!e.rest&&r.isIdentifier(e.params[0])){t(e.params[0])}else{this._params(e,t)}this.push(" => ");t(e.body)}},{"../../types":85}],13:[function(t,i,e){var r=t("../../types");var n=t("lodash");e.ImportSpecifier=function(t,r){if(t.id&&t.id.name==="default"){r(t.name)}else{return e.ExportSpecifier.apply(this,arguments)}};e.ExportSpecifier=function(e,t){t(e.id);if(e.name){this.push(" as ");t(e.name)}};e.ExportBatchSpecifier=function(){this.push("*")};e.ExportDeclaration=function(e,n){this.push("export ");var t=e.specifiers;if(e.default){this.push("default ")}if(e.declaration){n(e.declaration);if(r.isStatement(e.declaration))return}else{if(t.length===1&&r.isExportBatchSpecifier(t[0])){n(t[0])}else{this.push("{");if(t.length){this.space();n.join(t,{separator:", "});this.space()}this.push("}")}if(e.source){this.push(" from ");n(e.source)}}this.ensureSemicolon()};e.ImportDeclaration=function(e,r){var i=this;this.push("import ");var a=e.specifiers;if(a&&a.length){var t=false;n.each(e.specifiers,function(e,n){if(+n>0){i.push(", ")}var a=e.id&&e.id.name==="default";if(!a&&e.type!=="ImportBatchSpecifier"&&!t){t=true;i.push("{ ")}r(e)});if(t){this.push(" }")}this.push(" from ")}r(e.source);this.semicolon()};e.ImportBatchSpecifier=function(e,t){this.push("* as ");t(e.name)}},{"../../types":85,lodash:135}],14:[function(e,n,t){var r=e("lodash");r.each(["BindMemberExpression","BindFunctionExpression"],function(e){t[e]=function(){throw new ReferenceError("Trying to render non-standard playground node "+JSON.stringify(e))}})},{lodash:135}],15:[function(r,s,e){var i=r("../../util");var a=r("../../types");e.WithStatement=function(e,t){this.keyword("with");this.push("(");t(e.object);this.push(")");t.block(e.body)};e.IfStatement=function(e,t){this.keyword("if");this.push("(");t(e.test);this.push(") ");t.indentOnComments(e.consequent);if(e.alternate){if(this.isLast("}"))this.space();this.keyword("else");t.indentOnComments(e.alternate)}};e.ForStatement=function(e,t){this.keyword("for");this.push("(");t(e.init);this.push(";");if(e.test){this.space();t(e.test)}this.push(";");if(e.update){this.space();t(e.update)}this.push(")");t.block(e.body)};e.WhileStatement=function(e,t){this.keyword("while");this.push("(");t(e.test);this.push(")");t.block(e.body)};var n=function(e){return function(t,r){this.keyword("for");this.push("(");r(t.left);this.push(" "+e+" ");r(t.right);this.push(")");r.block(t.body)}};e.ForInStatement=n("in");e.ForOfStatement=n("of");e.DoWhileStatement=function(e,t){this.keyword("do");t(e.body);this.space();this.keyword("while");this.push("(");t(e.test);this.push(");")};var t=function(e,t){return function(n,i){this.push(e);var r=n[t||"label"];if(r){this.space();i(r)}this.semicolon()}};e.ContinueStatement=t("continue");e.ReturnStatement=t("return","argument");e.BreakStatement=t("break");e.LabeledStatement=function(e,t){t(e.label);this.push(": ");t(e.body)};e.TryStatement=function(e,t){this.keyword("try");t(e.block);this.space();if(e.handlers){t(e.handlers[0])}else{t(e.handler)}if(e.finalizer){this.space();this.push("finally ");t(e.finalizer)}};e.CatchClause=function(e,t){this.keyword("catch");this.push("(");t(e.param);this.push(") ");t(e.body)};e.ThrowStatement=function(e,t){this.push("throw ");t(e.argument);this.semicolon()};e.SwitchStatement=function(e,t){this.keyword("switch");this.push("(");t(e.discriminant);this.push(") {");t.sequence(e.cases,{indent:true});this.push("}")};e.SwitchCase=function(e,t){if(e.test){this.push("case ");t(e.test);this.push(":")}else{this.push("default:")}this.newline();t.sequence(e.consequent,{indent:true})};e.DebuggerStatement=function(){this.push("debugger;")};e.VariableDeclaration=function(e,o,l){this.push(e.kind+" ");var n=0;var s=0;for(var t=0;t<e.declarations.length;t++){if(e.declarations[t].init){n++}else{s++}}var r=",";if(n>s){r+="\n"+i.repeat(e.kind.length+1)}else{r+=" "}o.join(e.declarations,{separator:r});if(!a.isFor(l)){this.semicolon()}};e.PrivateDeclaration=function(e,t){this.push("private ");t.join(e.declarations,{separator:", "});this.semicolon()};e.VariableDeclarator=function(e,t){if(e.init){t(e.id);this.push(" = ");t(e.init)}else{t(e.id)}}},{"../../types":85,"../../util":87}],16:[function(t,n,e){var r=t("lodash");e.TaggedTemplateExpression=function(e,t){t(e.tag);t(e.quasi)};e.TemplateElement=function(e){this._push(e.value.raw)};e.TemplateLiteral=function(e,t){this.push("`");var n=e.quasis;var i=this;var a=n.length;r.each(n,function(n,r){t(n);if(r+1<a){i.push("${ ");t(e.expressions[r]);i.push(" }")}});this._push("`")}},{lodash:135}],17:[function(t,n,e){var r=t("lodash");e.Identifier=function(e){this.push(e.name)};e.SpreadElement=e.SpreadProperty=function(e,t){this.push("...");t(e.argument)};e.VirtualPropertyExpression=function(e,t){t(e.object);this.push("::");t(e.property)};e.ObjectExpression=e.ObjectPattern=function(t,r){var e=t.properties;if(e.length){this.push("{");this.space();r.join(e,{separator:", ",indent:true});this.space();this.push("}")}else{this.push("{}")}};e.Property=function(e,t){if(e.method||e.kind==="get"||e.kind==="set"){this._method(e,t)}else{if(e.computed){this.push("[");t(e.key);this.push("]")}else{t(e.key);if(e.shorthand)return}this.push(": ");t(e.value)}};e.ArrayExpression=e.ArrayPattern=function(n,i){var t=n.elements;var e=this;var a=t.length;this.push("[");r.each(t,function(t,r){if(!t){e.push(",")}else{if(r>0)e.push(" ");i(t);if(r<a-1)e.push(",")}});this.push("]")};e.Literal=function(t){var e=t.value;var r=typeof e;if(r==="string"){e=JSON.stringify(e);e=e.replace(/[\u000A\u000D\u2028\u2029]/g,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)});this.push(e)}else if(r==="boolean"||r==="number"){this.push(JSON.stringify(e))}else if(t.regex){this.push("/"+t.regex.pattern+"/"+t.regex.flags)}else if(e===null){this.push("null")}}},{lodash:135}],18:[function(r,s,l){s.exports=e;var a=r("./whitespace");var o=r("./parentheses");var t=r("../../types");var n=r("lodash");var i=function(e,i,o){if(!e)return;var r;var a=Object.keys(e);for(var n=0;n<a.length;n++){var s=a[n];if(t.is(s,i)){var l=e[s];r=l(i,o);if(r!=null)break}}return r};function e(e,t){this.parent=t;this.node=e}e.isUserWhitespacable=function(e){return t.isUserWhitespacable(e)};e.needsWhitespace=function(r,l,o){if(!r)return 0;if(t.isExpressionStatement(r)){r=r.expression}var s=i(a[o].nodes,r,l);if(s)return s;n.each(i(a[o].list,r,l),function(t){s=e.needsWhitespace(t,r,o);if(s)return false});return s||0};e.needsWhitespaceBefore=function(t,r){return e.needsWhitespace(t,r,"before")};e.needsWhitespaceAfter=function(t,r){return e.needsWhitespace(t,r,"after")};e.needsParens=function(e,r){if(!r)return false;if(t.isNewExpression(r)&&r.callee===e){if(t.isCallExpression(e))return true;var a=n.some(e,function(e){return t.isCallExpression(e)});if(a)return true}return i(o,e,r)};e.needsParensNoLineTerminator=function(r,e){if(!e)return false;if(!r.leadingComments||!r.leadingComments.length){return false}if(t.isYieldExpression(e)||t.isAwaitExpression(e)){return true}if(t.isContinueStatement(e)||t.isBreakStatement(e)||t.isReturnStatement(e)||t.isThrowStatement(e)){return true}return false};n.each(e,function(r,t){e.prototype[t]=function(){var r=new Array(arguments.length+2);r[0]=this.node;r[1]=this.parent;for(var n=0;n<r.length;n++){r[n+2]=arguments[n]}return e[t].apply(null,r)}})},{"../../types":85,"./parentheses":19,"./whitespace":20,lodash:135}],19:[function(n,a,t){var e=n("../../types");var i=n("lodash");var r={};i.each([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],function(e,t){i.each(e,function(e){r[e]=t})});t.UpdateExpression=function(r,t){if(e.isMemberExpression(t)&&t.object===r){return true}};t.ObjectExpression=function(r,t){if(e.isExpressionStatement(t)){return true}if(e.isMemberExpression(t)&&t.object===r){return true}return false};t.Binary=function(n,t){if((e.isCallExpression(t)||e.isNewExpression(t))&&t.callee===n){return true}if(e.isUnaryLike(t)){return true}if(e.isMemberExpression(t)&&t.object===n){return true}if(e.isBinary(t)){var s=t.operator;var i=r[s];var o=n.operator;var a=r[o];if(i>a){return true}if(i===a&&t.right===n){return true}}};t.BinaryExpression=function(r,t){if(r.operator==="in"){if(e.isVariableDeclarator(t)){return true}if(e.isFor(t)){return true}}};t.SequenceExpression=function(r,t){if(e.isForStatement(t)){return false}if(e.isExpressionStatement(t)&&t.expression===r){return false}return true};t.YieldExpression=function(r,t){return e.isBinary(t)||e.isUnaryLike(t)||e.isCallExpression(t)||e.isMemberExpression(t)||e.isNewExpression(t)||e.isConditionalExpression(t)||e.isYieldExpression(t)};t.ClassExpression=function(r,t){return e.isExpressionStatement(t)};t.UnaryLike=function(r,t){return e.isMemberExpression(t)&&t.object===r};t.FunctionExpression=function(r,t){if(e.isExpressionStatement(t)){return true}if(e.isMemberExpression(t)&&t.object===r){return true}if(e.isCallExpression(t)&&t.callee===r){return true}};t.AssignmentExpression=t.ConditionalExpression=function(r,t){if(e.isUnaryLike(t)){return true}if(e.isBinary(t)){return true}if(e.isCallExpression(t)&&t.callee===r){return true}if(e.isConditionalExpression(t)&&t.test===r){return true}if(e.isMemberExpression(t)&&t.object===r){return true}return false}},{"../../types":85,lodash:135}],20:[function(n,i,t){var e=n("lodash");var r=n("../../types");t.before={nodes:{Property:function(e,t){if(t.properties[0]===e){return 1}},SpreadProperty:function(e,r){return t.before.nodes.Property(e,r)},SwitchCase:function(e,t){if(t.cases[0]===e){return 1}},CallExpression:function(e){if(r.isFunction(e.callee)){return 1}}}};t.after={nodes:{AssignmentExpression:function(e){if(r.isFunction(e.right)){return 1}}},list:{VariableDeclaration:function(t){return e.map(t.declarations,"init")},ArrayExpression:function(e){return e.elements},ObjectExpression:function(e){return e.properties}}};e.each({Function:1,Class:1,For:1,ArrayExpression:{after:1},ObjectExpression:{after:1},SwitchStatement:1,IfStatement:{before:1},CallExpression:{after:1},Literal:{after:1}},function(n,i){if(e.isNumber(n)){n={after:n,before:n}}e.each([i].concat(r.FLIPPED_ALIAS_KEYS[i]||[]),function(r){e.each(n,function(e,n){t[n].nodes[r]=function(){return e}})})})},{"../../types":85,lodash:135}],21:[function(r,t,n){t.exports=e;function e(){this.line=1;this.column=0}e.prototype.push=function(t){for(var e=0;e<t.length;e++){if(t[e]==="\n"){this.line++;this.column=0}else{this.column++}}};e.prototype.unshift=function(t){for(var e=0;e<t.length;e++){if(t[e]==="\n"){this.line--}else{this.column--}}}},{}],22:[function(t,n,a){n.exports=e;var i=t("source-map");var r=t("../types");function e(t,e,r){this.position=t;this.opts=e;if(e.sourceMap){this.map=new i.SourceMapGenerator({file:e.sourceMapName,sourceRoot:e.sourceRoot});this.map.setSourceContent(e.sourceFileName,r)}else{this.map=null}}e.prototype.get=function(){var e=this.map;if(e){return e.toJSON()}else{return e}};e.prototype.mark=function(e,o){var i=e.loc;if(!i)return;var a=this.map;if(!a)return;if(r.isProgram(e)||r.isFile(e))return;var s=this.position;var t={line:s.line,column:s.column};var n=i[o];if(t.line===n.line&&t.column===n.column)return;a.addMapping({source:this.opts.sourceFileName,generated:t,original:n})}},{"../types":85,"source-map":178}],23:[function(r,n,a){n.exports=e;var i=r("lodash");function t(e,r,t){e+=r;if(e>=t)e-=t;return e}function e(e,t){this.tokens=i.sortBy(e.concat(t),"start");this.used={};this._lastFoundIndex=0}e.prototype.getNewlinesBefore=function(o){var a;var s;var e=this.tokens;var r;for(var n=0;n<e.length;n++){var i=t(n,this._lastFoundIndex,this.tokens.length);r=e[i];if(o.start===r.start){a=e[i-1];s=r;this._lastFoundIndex=i;break}}return this.getNewlinesBetween(a,s)};e.prototype.getNewlinesAfter=function(s){var o;var e;var r=this.tokens;var n;for(var i=0;i<r.length;i++){var a=t(i,this._lastFoundIndex,this.tokens.length);n=r[a];if(s.end===n.end){o=n;e=r[a+1];this._lastFoundIndex=a;break}}if(e.type.type==="eof"){return 1}else{var l=this.getNewlinesBetween(o,e);if(s.type==="Line"&&!l){return 1}else{return l}}};e.prototype.getNewlinesBetween=function(t,n){var i=t?t.loc.end.line:1;var a=n.loc.start.line;var r=0;for(var e=i;e<a;e++){if(typeof this.used[e]==="undefined"){this.used[e]=true;r++}}return r}},{lodash:135}],24:[function(t,o,l){var i=t("./types");var a=t("lodash");var s=t("estraverse");a.extend(s.VisitorKeys,i.VISITOR_KEYS);var r=t("ast-types");var e=r.Type.def;var n=r.Type.or;e("AssignmentPattern").bases("Pattern").build("left","right").field("left",e("Pattern")).field("right",e("Expression"));e("ImportBatchSpecifier").bases("Specifier").build("name").field("name",e("Identifier"));e("VirtualPropertyExpression").bases("Expression").build("object","property").field("object",e("Expression")).field("property",n(e("Identifier"),e("Expression")));e("PrivateDeclaration").bases("Declaration").build("declarations").field("declarations",[e("Identifier")]);e("BindMemberExpression").bases("Expression").build("object","property","arguments").field("object",e("Expression")).field("property",n(e("Identifier"),e("Expression"))).field("arguments",[e("Expression")]);e("BindFunctionExpression").bases("Expression").build("callee","arguments").field("callee",e("Expression")).field("arguments",[e("Expression")]);r.finalize()},{"./types":85,"ast-types":101,estraverse:129,lodash:135}],25:[function(t,r,n){var e=t("../../types");r.exports=function i(r,i){var n=r.blocks.shift();if(!n)return;var t=i(r,i);if(!t){t=i();if(r.filter){t=e.ifStatement(r.filter,e.blockStatement([t]))}}return e.forOfStatement(e.variableDeclaration("let",[e.variableDeclarator(n.left)]),n.right,e.blockStatement([t]))}},{"../../types":85}],26:[function(t,r,a){var n=t("../../traverse");var i=t("../../util");var e=t("../../types");r.exports=function(t,o,s){var a=e.toComputedKey(t,t.key);if(!e.isLiteral(a))return t;var r=e.toIdentifier(a.value);a=e.identifier(r);var l=false;var u=s.get(r,true);n(t,{enter:function(t,n,i){if(!e.isIdentifier(t,{name:r}))return;if(!e.isReferenced(t,n))return;var a=i.get(r,true);if(a!==u)return;l=true;this.stop()}},s);if(l){t.value=i.template("property-method-assignment-wrapper",{FUNCTION:t.value,FUNCTION_ID:a,FUNCTION_KEY:o.generateUidIdentifier(r,s),WRAPPER_KEY:o.generateUidIdentifier(r+"Wrapper",s)})}else{t.value.id=a}}},{"../../traverse":81,"../../types":85,"../../util":87}],27:[function(t,r,i){var n=t("../../traverse");var e=t("../../types");r.exports=function(t,a){t.async=false;t.generator=true;n(t,{enter:function(t){if(e.isFunction(t))this.skip();if(e.isAwaitExpression(t)){t.type="YieldExpression"}}});var r=e.callExpression(a,[t]);if(e.isFunctionDeclaration(t)){var i=e.variableDeclaration("var",[e.variableDeclarator(t.id,r)]);i._blockHoist=true;return i}else{return r}}},{"../../traverse":81,"../../types":85}],28:[function(r,n,e){var t=r("../../types");e.has=function(r){var e=r.body[0];return t.isExpressionStatement(e)&&t.isLiteral(e.expression,{value:"use strict"})};e.wrap=function(t,n){var r;if(e.has(t)){r=t.body.shift()}n();if(r){t.body.unshift(r)}}},{"../../types":85}],29:[function(r,a,o){a.exports=t;var n=r("../../traverse");var s=r("../../util");var e=r("../../types");var i=r("lodash");function t(e){this.file=e;this.localExports=this.getLocalExports();this.localImports=this.getLocalImports();this.remapAssignments()}t.prototype.getLocalExports=function(){var t={};n(this.file.ast,{enter:function(r){var n=r&&r.declaration;if(e.isExportDeclaration(r)&&n&&e.isStatement(n)){i.extend(t,e.getIds(n,true))}}});return t};t.prototype.getLocalImports=function(){var t={};n(this.file.ast,{enter:function(r){if(e.isImportDeclaration(r)){i.extend(t,e.getIds(r,true))}}});return t};t.prototype.checkCollisions=function(){var t=this.localImports;var r=this.file;var s=function(r){return e.isIdentifier(r)&&i.has(t,r.name)&&t[r.name]!==r};var a=function(e){if(s(e)){throw r.errorWithNode(e,"Illegal assignment of module import")}};n(r.ast,{enter:function(r){if(e.isAssignmentExpression(r)){var t=r.left;if(e.isMemberExpression(t)){while(t.object)t=t.object}a(t)}else if(e.isDeclaration(r)){i.each(e.getIds(r,true),a)}}})};t.prototype.remapExportAssignment=function(t){return e.assignmentExpression("=",t.left,e.assignmentExpression(t.operator,e.memberExpression(e.identifier("exports"),t.left),t.right))};t.prototype.remapAssignments=function(){var t=this.localExports;var r=this;var i=function(n,i){var r=n.name;return e.isIdentifier(n)&&t[r]&&t[r]===i.get(r,true)};n(this.file.ast,{enter:function(t,l,s){if(e.isUpdateExpression(t)&&i(t.argument,s)){this.skip();var u=e.assignmentExpression(t.operator[0]+"=",t.argument,e.literal(1));var o=r.remapExportAssignment(u);if(e.isExpressionStatement(l)||t.prefix){return o}var n=[];n.push(o);var a;if(t.operator==="--"){a="+"}else{a="-"}n.push(e.binaryExpression(a,t.argument,e.literal(1)));return e.sequenceExpression(n)}if(e.isAssignmentExpression(t)&&i(t.left,s)){this.skip();return r.remapExportAssignment(t)}}})};t.prototype.getModuleName=function(){var e=this.file.opts;var r=e.filenameRelative;var t="";if(e.moduleRoot){t=e.moduleRoot+"/"}if(!e.filenameRelative){return t+e.filename.replace(/^\//,"")}if(e.sourceRoot){var n=new RegExp("^"+e.sourceRoot+"/?");r=r.replace(n,"")}if(!e.keepModuleIdExtensions){r=r.replace(/\.(.*?)$/,"")}t+=r;t=t.replace(/\\/g,"/");return t};t.prototype._pushStatement=function(t,r){if(e.isClass(t)||e.isFunction(t)){if(t.id){r.push(e.toStatement(t));t=t.id}}return t};t.prototype._hoistExport=function(r,t,n){if(e.isFunctionDeclaration(r)){t._blockHoist=n||2}return t};t.prototype._exportSpecifier=function(n,t,r,i){var s=false;if(r.specifiers.length===1)s=r;if(r.source){if(e.isExportBatchSpecifier(t)){i.push(this._exportsWildcard(n(),r))}else{var a;if(e.isSpecifierDefault(t)&&!this.noInteropRequire){a=e.callExpression(this.file.addHelper("interop-require"),[n()])}else{a=e.memberExpression(n(),t.id)}i.push(this._exportsAssign(e.getSpecifierName(t),a,r))}}else{i.push(this._exportsAssign(e.getSpecifierName(t),t.id,r))}};t.prototype._exportsWildcard=function(t){return e.expressionStatement(e.callExpression(this.file.addHelper("defaults"),[e.identifier("exports"),e.callExpression(this.file.addHelper("interop-require-wildcard"),[t])]))};t.prototype._exportsAssign=function(e,t){return s.template("exports-assign",{VALUE:t,KEY:e},true)};t.prototype.exportDeclaration=function(r,a){var t=r.declaration;var o=t.id;if(r.default){o=e.identifier("default")}var s;if(e.isVariableDeclaration(t)){for(var n=0;n<t.declarations.length;n++){var i=t.declarations[n];i.init=this._exportsAssign(i.id,i.init,r).expression;var l=e.variableDeclaration(t.kind,[i]);if(n===0)e.inherits(l,t);a.push(l)}}else{var u=t;if(e.isFunctionDeclaration(t)||e.isClassDeclaration(t)){u=t.id;a.push(t)}s=this._exportsAssign(o,u,r);a.push(s);this._hoistExport(t,s)}}},{"../../traverse":81,"../../types":85,"../../util":87,lodash:135}],30:[function(e,t,n){var r=e("../../util");t.exports=function(e){var t=function(){this.noInteropExport=true;e.apply(this,arguments)};r.inherits(t,e);return t}},{"../../util":87}],31:[function(e,t,r){t.exports=e("./_strict")(e("./amd"))},{"./_strict":30,"./amd":32}],32:[function(r,a,l){a.exports=t;var n=r("./_default");var i=r("./common");var s=r("../../util");var e=r("../../types");var o=r("lodash");function t(){i.apply(this,arguments);this.ids={}}s.inherits(t,n);t.prototype.buildDependencyLiterals=function(){var t=[];for(var r in this.ids){t.push(e.literal(r))}return t};t.prototype.transform=function(s){var n=s.program;var l=n.body;var t=[e.literal("exports")];if(this.passModuleArg)t.push(e.literal("module"));t=t.concat(this.buildDependencyLiterals());t=e.arrayExpression(t);var r=o.values(this.ids);if(this.passModuleArg)r.unshift(e.identifier("module"));r.unshift(e.identifier("exports"));var u=e.functionExpression(null,r,e.blockStatement(l));var i=[t,u];var a=this.getModuleName();if(a)i.unshift(e.literal(a));var f=e.callExpression(e.identifier("define"),i);n.body=[e.expressionStatement(f)]};t.prototype.getModuleName=function(){if(this.file.opts.moduleIds){return n.prototype.getModuleName.apply(this,arguments)}else{return null}};t.prototype._push=function(r){var e=r.source.value;var t=this.ids;if(t[e]){return t[e]}else{return this.ids[e]=this.file.generateUidIdentifier(e)}};t.prototype.importDeclaration=function(e){this._push(e)};t.prototype.importSpecifier=function(r,n,i){var a=e.getSpecifierName(r);var t=this._push(n);if(e.isImportBatchSpecifier(r)){}else if(e.isSpecifierDefault(r)&&!this.noInteropRequire){t=e.callExpression(this.file.addHelper("interop-require"),[t])}else{t=e.memberExpression(t,r.id,false)}i.push(e.variableDeclaration("var",[e.variableDeclarator(a,t)]))};t.prototype.exportDeclaration=function(e){if(e.default&&!this.noInteropExport){this.passModuleArg=true}i.prototype.exportDeclaration.apply(this,arguments)};t.prototype.exportSpecifier=function(t,e,r){var n=this;return this._exportSpecifier(function(){return n._push(e)},t,e,r)}},{"../../types":85,"../../util":87,"./_default":29,"./common":34,lodash:135}],33:[function(e,t,r){t.exports=e("./_strict")(e("./common"))},{"./_strict":30,"./common":34}],34:[function(n,a,o){a.exports=r;var i=n("./_default");var s=n("../../traverse");var t=n("../../util");var e=n("../../types");function r(r){i.apply(this,arguments);var t=false;s(r.ast,{enter:function(r){if(e.isExportDeclaration(r)&&!r.default)t=true}});this.hasNonDefaultExports=t}t.inherits(r,i);r.prototype.importSpecifier=function(r,n,i){var a=e.getSpecifierName(r);if(e.isSpecifierDefault(r)){i.push(e.variableDeclaration("var",[e.variableDeclarator(a,e.callExpression(this.file.addHelper("interop-require"),[t.template("require",{MODULE_NAME:n.source})]))]))}else{if(r.type==="ImportBatchSpecifier"){i.push(e.variableDeclaration("var",[e.variableDeclarator(a,e.callExpression(this.file.addHelper("interop-require-wildcard"),[e.callExpression(e.identifier("require"),[n.source])]))]))}else{i.push(t.template("require-assign-key",{VARIABLE_NAME:a,MODULE_NAME:n.source,KEY:r.id}))}}};r.prototype.importDeclaration=function(e,r){r.push(t.template("require",{MODULE_NAME:e.source},true))};r.prototype.exportDeclaration=function(s,n){if(s.default&&!this.noInteropRequire&&!this.noInteropExport){var a=s.declaration;var r;var o="exports-default-module";if(this.hasNonDefaultExports)o="exports-default-module-override";if(e.isFunctionDeclaration(a)||!this.hasNonDefaultExports){r=t.template(o,{VALUE:this._pushStatement(a,n)},true);n.push(this._hoistExport(a,r,3));return}else{r=t.template("common-export-default-assign",{EXTENDS_HELPER:this.file.addHelper("extends")},true);r._blockHoist=0;n.push(r)}}i.prototype.exportDeclaration.apply(this,arguments)};r.prototype.exportSpecifier=function(r,t,n){this._exportSpecifier(function(){return e.callExpression(e.identifier("require"),[t.source])},r,t,n)}},{"../../traverse":81,"../../types":85,"../../util":87,"./_default":29}],35:[function(r,n,i){n.exports=e;var t=r("../../types");function e(){}e.prototype.exportDeclaration=function(e,n){var r=t.toStatement(e.declaration,true);if(r)n.push(t.inherits(r,e))};e.prototype.importDeclaration=e.prototype.importSpecifier=e.prototype.exportSpecifier=function(){}},{"../../types":85}],36:[function(r,o,u){o.exports=t;var i=r("./amd");var l=r("../helpers/use-strict");var a=r("../../traverse");var s=r("../../util");var e=r("../../types");var n=r("lodash");function t(e){this.exportIdentifier=e.generateUidIdentifier("export");this.noInteropRequire=true;i.apply(this,arguments)}s.inherits(t,i);t.prototype._addImportSource=function(e,t){e._importSource=t.source&&t.source.value;return e};t.prototype._exportsWildcard=function(r,n){var t=this.file.generateUidIdentifier("key");var i=e.memberExpression(r,t,true);var a=e.variableDeclaration("var",[e.variableDeclarator(t)]);var s=r;var o=e.blockStatement([e.expressionStatement(this.buildExportCall(t,i))]);return this._addImportSource(e.forInStatement(a,s,o),n)};t.prototype._exportsAssign=function(t,r,n){var i=this.buildExportCall(e.literal(t.name),r,true);return this._addImportSource(i,n)};t.prototype.remapExportAssignment=function(t){return this.buildExportCall(e.literal(t.left.name),t)};t.prototype.buildExportCall=function(r,n,i){var t=e.callExpression(this.exportIdentifier,[r,n]);if(i){return e.expressionStatement(t)}else{return t}};t.prototype.importSpecifier=function(r,e,t){i.prototype.importSpecifier.apply(this,arguments);this._addImportSource(n.last(t),e)};t.prototype.buildRunnerSetters=function(t,r){return e.arrayExpression(n.map(this.ids,function(s,o){var i=[];a(t,{enter:function(t){if(t._importSource===o){if(e.isVariableDeclaration(t)){n.each(t.declarations,function(t){r.push(e.variableDeclarator(t.id));i.push(e.expressionStatement(e.assignmentExpression("=",t.id,t.init)))})}else{i.push(t)}this.remove()}}});return e.functionExpression(null,[s],e.blockStatement(i))}))};t.prototype.transform=function(p){var u=p.program;var i=[];var f=this.getModuleName();var d=e.literal(f);var t=e.blockStatement(u.body);var o=s.template("system",{MODULE_NAME:d,MODULE_DEPENDENCIES:e.arrayExpression(this.buildDependencyLiterals()),EXPORT_IDENTIFIER:this.exportIdentifier,SETTERS:this.buildRunnerSetters(t,i),EXECUTE:e.functionExpression(null,[],t)},true);var r=o.expression.arguments[2].body.body;if(!f)o.expression.arguments.shift();var m=r.pop();a(t,{enter:function(t,r,s){if(e.isFunction(t)){return this.skip()}if(e.isVariableDeclaration(t)){if(t.kind!=="var"&&!e.isProgram(r)){return}var a=[];n.each(t.declarations,function(t){i.push(e.variableDeclarator(t.id));if(t.init){var r=e.expressionStatement(e.assignmentExpression("=",t.id,t.init));a.push(r)}});if(e.isFor(r)){if(r.left===t){return t.declarations[0].id}if(r.init===t){return e.toSequenceExpression(a,s)}}return a}}});if(i.length){var c=e.variableDeclaration("var",i);c._blockHoist=true;r.unshift(c)}a(t,{enter:function(t){if(e.isFunction(t))this.skip();if(e.isFunctionDeclaration(t)||t._blockHoist){r.push(t);this.remove()}}});r.push(m);if(l.has(t)){r.unshift(t.body.shift())}u.body=[o]}},{"../../traverse":81,"../../types":85,"../../util":87,"../helpers/use-strict":28,"./amd":32,lodash:135}],37:[function(e,t,r){t.exports=e("./_strict")(e("./umd"))
},{"./_strict":30,"./umd":38}],38:[function(t,a,o){a.exports=n;var i=t("./amd");var r=t("../../util");var e=t("../../types");var s=t("lodash");function n(){i.apply(this,arguments)}r.inherits(n,i);n.prototype.transform=function(c){var o=c.program;var y=o.body;var a=[];for(var p in this.ids){a.push(e.literal(p))}var h=s.values(this.ids);var n=[e.identifier("exports")];if(this.passModuleArg)n.push(e.identifier("module"));n=n.concat(h);var f=e.functionExpression(null,n,e.blockStatement(y));var t=[e.literal("exports")];if(this.passModuleArg)t.push(e.literal("module"));t=t.concat(a);t=[e.arrayExpression(t)];var l=r.template("test-exports");var d=r.template("test-module");var m=this.passModuleArg?e.logicalExpression("&&",l,d):l;var i=[e.identifier("exports")];if(this.passModuleArg)i.push(e.identifier("module"));i=i.concat(a.map(function(t){return e.callExpression(e.identifier("require"),[t])}));var u=this.getModuleName();if(u)t.unshift(e.literal(u));var v=r.template("umd-runner-body",{AMD_ARGUMENTS:t,COMMON_TEST:m,COMMON_ARGUMENTS:i});var g=e.callExpression(v,[f]);o.body=[e.expressionStatement(g)]}},{"../../types":85,"../../util":87,"./amd":32,lodash:135}],39:[function(e,i,o){i.exports=t;var a=e("./transformer");var r=e("../file");var s=e("../util");var n=e("lodash");function t(e,t){var n=new r(t);return n.parse(e)}t.fromAst=function(e,n,i){e=s.normaliseAst(e);var t=new r(i);t.addCode(n);t.transform(e);return t.generate()};t._ensureTransformerNames=function(a,r){for(var e=0;e<r.length;e++){var i=r[e];if(!n.has(t.transformers,i)){throw new ReferenceError("unknown transformer "+i+" specified in "+a)}}};t.transformers={};t.moduleFormatters={commonStrict:e("./modules/common-strict"),umdStrict:e("./modules/umd-strict"),amdStrict:e("./modules/amd-strict"),common:e("./modules/common"),system:e("./modules/system"),ignore:e("./modules/ignore"),amd:e("./modules/amd"),umd:e("./modules/umd")};n.each({specNoForInOfAssignment:e("./transformers/spec-no-for-in-of-assignment"),specSetters:e("./transformers/spec-setters"),methodBinding:e("./transformers/playground-method-binding"),memoizationOperator:e("./transformers/playground-memoization-operator"),objectGetterMemoization:e("./transformers/playground-object-getter-memoization"),asyncToGenerator:e("./transformers/optional-async-to-generator"),bluebirdCoroutines:e("./transformers/optional-bluebird-coroutines"),react:e("./transformers/react"),modules:e("./transformers/es6-modules"),propertyNameShorthand:e("./transformers/es6-property-name-shorthand"),arrayComprehension:e("./transformers/es7-array-comprehension"),generatorComprehension:e("./transformers/es7-generator-comprehension"),arrowFunctions:e("./transformers/es6-arrow-functions"),classes:e("./transformers/es6-classes"),objectSpread:e("./transformers/es7-object-spread"),exponentiationOperator:e("./transformers/es7-exponentiation-operator"),spread:e("./transformers/es6-spread"),templateLiterals:e("./transformers/es6-template-literals"),propertyMethodAssignment:e("./transformers/es6-property-method-assignment"),computedPropertyNames:e("./transformers/es6-computed-property-names"),destructuring:e("./transformers/es6-destructuring"),defaultParameters:e("./transformers/es6-default-parameters"),forOf:e("./transformers/es6-for-of"),unicodeRegex:e("./transformers/es6-unicode-regex"),abstractReferences:e("./transformers/es7-abstract-references"),constants:e("./transformers/es6-constants"),letScoping:e("./transformers/es6-let-scoping"),_blockHoist:e("./transformers/_block-hoist"),generators:e("./transformers/es6-generators"),restParameters:e("./transformers/es6-rest-parameters"),protoToAssign:e("./transformers/optional-proto-to-assign"),_declarations:e("./transformers/_declarations"),useStrict:e("./transformers/use-strict"),_aliasFunctions:e("./transformers/_alias-functions"),_moduleFormatter:e("./transformers/_module-formatter"),typeofSymbol:e("./transformers/optional-typeof-symbol"),coreAliasing:e("./transformers/optional-core-aliasing"),undefinedToVoid:e("./transformers/optional-undefined-to-void"),specPropertyLiterals:e("./transformers/spec-property-literals"),specMemberExpressionLiterals:e("./transformers/spec-member-expression-literals")},function(r,e){t.transformers[e]=new a(e,r)})},{"../file":3,"../util":87,"./modules/amd":32,"./modules/amd-strict":31,"./modules/common":34,"./modules/common-strict":33,"./modules/ignore":35,"./modules/system":36,"./modules/umd":38,"./modules/umd-strict":37,"./transformer":40,"./transformers/_alias-functions":41,"./transformers/_block-hoist":42,"./transformers/_declarations":43,"./transformers/_module-formatter":44,"./transformers/es6-arrow-functions":45,"./transformers/es6-classes":46,"./transformers/es6-computed-property-names":47,"./transformers/es6-constants":48,"./transformers/es6-default-parameters":49,"./transformers/es6-destructuring":50,"./transformers/es6-for-of":51,"./transformers/es6-generators":52,"./transformers/es6-let-scoping":53,"./transformers/es6-modules":54,"./transformers/es6-property-method-assignment":55,"./transformers/es6-property-name-shorthand":56,"./transformers/es6-rest-parameters":57,"./transformers/es6-spread":58,"./transformers/es6-template-literals":59,"./transformers/es6-unicode-regex":60,"./transformers/es7-abstract-references":61,"./transformers/es7-array-comprehension":62,"./transformers/es7-exponentiation-operator":63,"./transformers/es7-generator-comprehension":64,"./transformers/es7-object-spread":65,"./transformers/optional-async-to-generator":66,"./transformers/optional-bluebird-coroutines":67,"./transformers/optional-core-aliasing":68,"./transformers/optional-proto-to-assign":69,"./transformers/optional-typeof-symbol":70,"./transformers/optional-undefined-to-void":71,"./transformers/playground-memoization-operator":72,"./transformers/playground-method-binding":73,"./transformers/playground-object-getter-memoization":74,"./transformers/react":75,"./transformers/spec-member-expression-literals":76,"./transformers/spec-no-for-in-of-assignment":77,"./transformers/spec-property-literals":78,"./transformers/spec-setters":79,"./transformers/use-strict":80,lodash:135}],40:[function(r,n,s){n.exports=t;var i=r("../traverse");var a=r("../types");var e=r("lodash");function t(t,e,r){this.manipulateOptions=e.manipulateOptions;this.experimental=!!e.experimental;this.secondPass=!!e.secondPass;this.transformer=this.normalise(e);this.optional=!!e.optional;this.opts=r||{};this.key=t}t.prototype.normalise=function(t){var r=this;if(e.isFunction(t)){t={ast:t}}e.each(t,function(n,i){if(i[0]==="_"){r[i]=n;return}if(e.isFunction(n))n={enter:n};if(!e.isObject(n))return;t[i]=n;var s=a.FLIPPED_ALIAS_KEYS[i];if(s){e.each(s,function(e){t[e]=n})}});return t};t.prototype.astRun=function(t,r){var e=this.transformer;if(e.ast&&e.ast[r]){e.ast[r](t.ast,t)}};t.prototype.transform=function(e){var r=this.transformer;var t=function(t){return function(a,s,o){var n=r[a.type];if(!n)return;var i=n.enter;if(t)i=n.exit;if(!i)return;return i.call(this,a,s,e,o)}};this.astRun(e,"before");i(e.ast,{enter:t(),exit:t(true)});this.astRun(e,"after")};t.prototype.canRun=function(a){var t=a.opts;var r=this.key;if(r[0]==="_")return true;var n=t.blacklist;if(n.length&&e.contains(n,r))return false;var i=t.whitelist;if(i.length&&!e.contains(i,r))return false;if(this.optional&&!e.contains(t.optional,r))return false;if(this.experimental&&!t.experimental)return false;return true}},{"../traverse":81,"../types":85,lodash:135}],41:[function(r,a,t){var n=r("../../traverse");var e=r("../../types");var i=function(l,u,a,s){var t;var r;var f=function(){return t=t||a.generateUidIdentifier("arguments",s)};var c=function(){return r=r||a.generateUidIdentifier("this",s)};n(u,{enter:function(t){if(!t._aliasFunction){if(e.isFunction(t)){return this.skip()}else{return}}n(t,{enter:function(t,n){if(e.isFunction(t)&&!t._aliasFunction){return this.skip()}if(t._ignoreAliasFunctions)return this.skip();var r;if(e.isIdentifier(t)&&t.name==="arguments"){r=f}else if(e.isThisExpression(t)){r=c}else{return}if(e.isReferenced(t,n))return r()}});return this.skip()}});var i;var o=function(t,r){i=i||l();i.unshift(e.variableDeclaration("var",[e.variableDeclarator(t,r)]))};if(t){o(t,e.identifier("arguments"))}if(r){o(r,e.thisExpression())}};t.Program=function(e,n,t,r){i(function(){return e.body},e,t,r)};t.FunctionDeclaration=t.FunctionExpression=function(t,a,r,n){i(function(){e.ensureBlock(t);return t.body.body},t,r,n)}},{"../../traverse":81,"../../types":85}],42:[function(t,i,r){var n=t("../helpers/use-strict");var e=t("lodash");r.BlockStatement=r.Program={exit:function(t){var i=false;for(var r=0;r<t.body.length;r++){var a=t.body[r];if(a&&a._blockHoist!=null)i=true}if(!i)return;n.wrap(t,function(){var r=e.groupBy(t.body,function(t){var e=t._blockHoist;if(e==null)e=1;if(e===true)e=2;return e});t.body=e.flatten(e.values(r).reverse())})}}},{"../helpers/use-strict":28,lodash:135}],43:[function(r,i,e){var n=r("../helpers/use-strict");var t=r("../../types");e.secondPass=true;e.BlockStatement=e.Program=function(r){if(!r._declarations)return;var i={};var e;n.wrap(r,function(){for(var s in r._declarations){var n=r._declarations[s];e=n.kind||"var";var a=t.variableDeclarator(n.id,n.init);if(!n.init){i[e]=i[e]||[];i[e].push(a)}else{r.body.unshift(t.variableDeclaration(e,[a]))}}for(e in i){r.body.unshift(t.variableDeclaration(e,i[e]))}});r._declarations=null}},{"../../types":85,"../helpers/use-strict":28}],44:[function(e,n,t){var r=e("../transform");t.ast={exit:function(t,e){if(!r.transformers.modules.canRun(e))return;if(e.moduleFormatter.transform){e.moduleFormatter.transform(t)}}}},{"../transform":39}],45:[function(e,n,t){var r=e("../../types");t.ArrowFunctionExpression=function(e){r.ensureBlock(e);e._aliasFunction="arrow";e.expression=false;e.type="FunctionExpression";return e}},{"../../types":85}],46:[function(r,o,i){var a=r("../helpers/name-method");var s=r("../../traverse");var n=r("../../util");var e=r("../../types");i.ClassDeclaration=function(e,i,r,n){return new t(e,r,n,true).run()};i.ClassExpression=function(n,r,i,a){if(!n.id){if(e.isProperty(r)&&r.value===n&&!r.computed&&e.isIdentifier(r.key)){n.id=r.key}if(e.isVariableDeclarator(r)&&e.isIdentifier(r.id)){n.id=r.id}}return new t(n,i,a,false).run()};function t(e,t,r,n){this.isStatement=n;this.scope=r;this.node=e;this.file=t;this.hasInstanceMutators=false;this.hasStaticMutators=false;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=e.id||t.generateUidIdentifier("class",r);this.superName=e.superClass;this.isLoose=t.isLoose("classes")}t.prototype.run=function(){var t=this.superName;var i=this.className;var l=this.file;var r=this.body=[];var n;if(this.node.id){n=e.functionDeclaration(i,[],e.blockStatement([]));r.push(n)}else{n=e.functionExpression(null,[],e.blockStatement([]));r.push(e.variableDeclaration("var",[e.variableDeclarator(i,n)]))}this.constructor=n;var s=[];var o=[];if(t){o.push(t);if(!e.isIdentifier(t)){var u=this.scope.generateUidBasedOnNode(t,this.file);t=u}s.push(t);this.superName=t;r.push(e.expressionStatement(e.callExpression(l.addHelper("inherits"),[i,t])))}this.buildBody();e.inheritsComments(r[0],this.node);var a;if(r.length===1){a=e.toExpression(n)}else{r.push(e.returnStatement(i));a=e.callExpression(e.functionExpression(null,s,e.blockStatement(r)),o)}if(this.isStatement){return e.variableDeclaration("let",[e.variableDeclarator(i,a)])}else{return a}};t.prototype.buildBody=function(){var p=this.constructor;var o=this.className;var f=this.superName;var c=this.node.body.body;var s=this.body;for(var a=0;a<c.length;a++){var t=c[a];if(e.isMethodDefinition(t)){this.replaceSuperReferences(t);if(t.key.name==="constructor"){this.pushConstructor(t)}else{this.pushMethod(t)}}else if(e.isPrivateDeclaration(t)){this.closure=true;s.unshift(t)}}if(!this.hasConstructor&&f&&!e.isFalsyExpression(f)){var u="class-super-constructor-call";if(this.isLoose)u+="-loose";p.body.body.push(n.template(u,{CLASS_NAME:o,SUPER_NAME:this.superName},true))}var i;var r;if(this.hasInstanceMutators){i=n.buildDefineProperties(this.instanceMutatorMap)}if(this.hasStaticMutators){r=n.buildDefineProperties(this.staticMutatorMap)}if(i||r){r=r||e.literal(null);var l=[o,r];if(i)l.push(i);s.push(e.expressionStatement(e.callExpression(this.file.addHelper("prototype-properties"),l)))}};t.prototype.pushMethod=function(t){var r=t.key;var i=t.kind;if(i===""){a(t,this.file,this.scope);if(this.isLoose){var s=this.className;if(!t.static)s=e.memberExpression(s,e.identifier("prototype"));r=e.memberExpression(s,r,t.computed);var o=e.expressionStatement(e.assignmentExpression("=",r,t.value));e.inheritsComments(o,t);this.body.push(o);return}i="value"}var l=this.instanceMutatorMap;if(t.static){this.hasStaticMutators=true;l=this.staticMutatorMap}else{this.hasInstanceMutators=true}n.pushMutatorMap(l,r,i,t.computed,t)};t.prototype.superProperty=function(t,r,n,i){return e.callExpression(this.file.addHelper("get"),[e.callExpression(e.memberExpression(e.identifier("Object"),e.identifier("getPrototypeOf")),[r?this.className:e.memberExpression(this.className,e.identifier("prototype"))]),n?t:e.literal(t.name),i])};t.prototype.looseSuperProperty=function(r,t,n){var a=r.key;var i=this.superName||e.identifier("Function");if(n.property===t){return}else if(e.isCallExpression(n,{callee:t})){n.arguments.unshift(e.thisExpression());if(a.name==="constructor"){return e.memberExpression(i,e.identifier("call"))}else{t=i;if(!r.static){t=e.memberExpression(t,e.identifier("prototype"))}t=e.memberExpression(t,a,r.computed);return e.memberExpression(t,e.identifier("call"))}}else if(e.isMemberExpression(n)&&!r.static){return e.memberExpression(i,e.identifier("prototype"))}else{return i}};t.prototype.replaceSuperReferences=function(t){var i=t.value;var r=this;var n;a(i,true);if(n){i.body.body.unshift(e.variableDeclaration("var",[e.variableDeclarator(n,e.thisExpression())]))}function a(t,i){s(t,{enter:function(t,u){if(e.isFunction(t)&&!e.isArrowFunctionExpression(t)){a(t,false);return this.skip()}if(e.isProperty(t,{method:true})||e.isMethodDefinition(t)){return this.skip()}var f=function(){if(i){return e.thisExpression()}else{return n=n||r.file.generateUidIdentifier("this")}};var s=l;if(r.isLoose)s=o;return s(f,t,u)}})}function o(a,n,s){if(e.isIdentifier(n,{name:"super"})){return r.looseSuperProperty(t,n,s)}else if(e.isCallExpression(n)){var i=n.callee;if(!e.isMemberExpression(i))return;if(i.object.name!=="super")return;e.appendToMemberExpression(i,e.identifier("call"));n.arguments.unshift(a())}}function l(c,n,l){var a;var o;var i;if(e.isIdentifier(n,{name:"super"})){if(!(e.isMemberExpression(l)&&!l.computed&&l.property===n)){throw r.file.errorWithNode(n,"illegal use of bare super")}}else if(e.isCallExpression(n)){var s=n.callee;if(e.isIdentifier(s,{name:"super"})){a=t.key;o=t.computed;i=n.arguments}else{if(!e.isMemberExpression(s))return;if(s.object.name!=="super")return;a=s.property;o=s.computed;i=n.arguments}}else if(e.isMemberExpression(n)){if(!e.isIdentifier(n.object,{name:"super"}))return;a=n.property;o=n.computed}if(!a)return;var u=c();var f=r.superProperty(a,t.static,o,u);if(i){if(i.length===1&&e.isSpreadElement(i[0])){return e.callExpression(e.memberExpression(f,e.identifier("apply")),[u,i[0].argument])}else{return e.callExpression(e.memberExpression(f,e.identifier("call")),[u].concat(i))}}else{return f}}};t.prototype.pushConstructor=function(n){if(n.kind){throw this.file.errorWithNode(n,"illegal kind for constructor method")}var t=this.constructor;var r=n.value;this.hasConstructor=true;e.inherits(t,r);e.inheritsComments(t,n);t._ignoreUserWhitespace=true;t.defaults=r.defaults;t.params=r.params;t.body=r.body;t.rest=r.rest}},{"../../traverse":81,"../../types":85,"../../util":87,"../helpers/name-method":26}],47:[function(t,a,r){var e=t("../../types");r.ObjectExpression=function(r,d,a,m){var s=false;for(var o=0;o<r.properties.length;o++){s=e.isProperty(r.properties[o],{computed:true,kind:"init"});if(s)break}if(!s)return;var p=[];var l=m.generateUidBasedOnNode(d,a);var t=[];var u=e.functionExpression(null,[],e.blockStatement(t));u._aliasFunction=true;var c=i;if(a.isLoose("computedPropertyNames"))c=n;var f=c(r,t,l,p,a);if(f)return f;t.unshift(e.variableDeclaration("var",[e.variableDeclarator(l,e.objectExpression(p))]));t.push(e.returnStatement(l));return e.callExpression(u,[])};var n=function(n,i,a){for(var t=0;t<n.properties.length;t++){var r=n.properties[t];i.push(e.expressionStatement(e.assignmentExpression("=",e.memberExpression(a,r.key,r.computed),r.value)))}};var i=function(p,o,f,l,c){var i=p.properties;var t,n;for(var r=0;r<i.length;r++){t=i[r];if(t.kind!=="init")continue;n=t.key;if(!t.computed&&e.isIdentifier(n)){t.key=e.literal(n.name)}}var u=false;for(r=0;r<i.length;r++){t=i[r];if(t.computed){u=true}if(t.kind!=="init"||!u||e.isLiteral(e.toComputedKey(t,t.key),{value:"__proto__"})){l.push(t);i[r]=null}}for(r=0;r<i.length;r++){t=i[r];if(!t)continue;n=t.key;var a;if(t.computed&&e.isMemberExpression(n)&&e.isIdentifier(n.object,{name:"Symbol"})){a=e.assignmentExpression("=",e.memberExpression(f,n,true),t.value)}else{a=e.callExpression(c.addHelper("define-property"),[f,n,t.value])}o.push(e.expressionStatement(a))}if(o.length===1){var s=o[0].expression;if(e.isCallExpression(s)){s.arguments[0]=e.objectExpression(l);return s}}}},{"../../types":85}],48:[function(r,a,t){var i=r("../../traverse");var e=r("../../types");var n=r("lodash");t.Program=t.BlockStatement=t.ForInStatement=t.ForOfStatement=t.ForStatement=function(r,u,l){var a=false;var t={};var s=function(i,a,s){for(var r in a){var o=a[r];if(!n.has(t,r))continue;if(i&&e.isBlockStatement(i)&&i!==t[r])continue;if(s){var u=s.get(r);if(u&&u===o)continue}throw l.errorWithNode(o,r+" is read-only")}};var o=function(t){return e.getIds(t,true,["MemberExpression"])};n.each(r.body,function(r,l){if(e.isExportDeclaration(r)){r=r.declaration}if(e.isVariableDeclaration(r,{kind:"const"})){for(var n=0;n<r.declarations.length;n++){var u=r.declarations[n];var f=o(u);for(var i in f){var p=f[i];var c={};c[i]=p;s(l,c);t[i]=l;a=true}u._ignoreConstant=true}r._ignoreConstant=true;r.kind="let"}});if(!a)return;i(r,{enter:function(t,r,n){if(t._ignoreConstant)return;if(e.isVariableDeclaration(t))return;if(e.isVariableDeclarator(t)||e.isDeclaration(t)||e.isAssignmentExpression(t)){s(r,o(t),n)}}})}},{"../../traverse":81,"../../types":85,lodash:135}],49:[function(t,a,r){var n=t("../../traverse");var i=t("../../util");var e=t("../../types");r.Function=function(t,b,v,c){if(!t.defaults||!t.defaults.length)return;e.ensureBlock(t);var h=t.params.map(function(t){return e.getIds(t)});var o=false;var a;var y=function(i){var r=function(t,r){if(!e.isIdentifier(t)||!e.isReferenced(t,r))return;if(i.indexOf(t.name)>=0){throw v.errorWithNode(t,"Temporal dead zone - accessing a variable before it's initialized")}if(c.has(t.name,true)){o=true}};r(a,t);n(a,{enter:r})};for(var r=0;r<t.defaults.length;r++){a=t.defaults[r];if(!a)continue;var g=t.params[r];var p=h.slice(r);for(var l=0;l<p.length;l++){y(p[l])}var d=c.get(g.name,true);if(d&&t.params.indexOf(d)<0){o=true}}var s=[];var m=e.identifier("arguments");m._ignoreAliasFunctions=true;var f=0;for(r=0;r<t.defaults.length;r++){a=t.defaults[r];if(!a){f=+r+1;continue}s.push(i.template("default-parameter",{VARIABLE_NAME:t.params[r],DEFAULT_VALUE:a,ARGUMENT_KEY:e.literal(+r),ARGUMENTS:m},true))}t.params=t.params.slice(0,f);if(o){var u=e.functionExpression(null,[],t.body,t.generator);u._aliasFunction=true;s.push(e.returnStatement(e.callExpression(u,[])));t.body=e.blockStatement(s)}else{t.body.body=s.concat(t.body.body)}t.defaults=[]}},{"../../traverse":81,"../../types":85,"../../util":87}],50:[function(a,u,t){var e=a("../../types");var n=function(r,t,n){var i=r.operator;if(e.isMemberExpression(t))i="=";if(i){return e.expressionStatement(e.assignmentExpression("=",t,n))}else{return e.variableDeclaration(r.kind,[e.variableDeclarator(t,n)])}};var r=function(r,i,t,a){if(e.isObjectPattern(t)){o(r,i,t,a)}else if(e.isArrayPattern(t)){l(r,i,t,a)}else if(e.isAssignmentPattern(t)){s(r,i,t,a)}else{i.push(n(r,t,a))}};var s=function(t,i,a,s){var r=t.scope.generateUidBasedOnNode(s,t.file);i.push(e.variableDeclaration("var",[e.variableDeclarator(r,s)]));i.push(n(t,a.left,e.conditionalExpression(e.binaryExpression("===",r,e.identifier("undefined")),a.right,r)))};var o=function(l,u,a,d){for(var o=0;o<a.properties.length;o++){var t=a.properties[o];if(e.isSpreadProperty(t)){var i=[];for(var s=0;s<a.properties.length;s++){var f=a.properties[s];if(s>=o)break;if(e.isSpreadProperty(f))continue;var c=f.key;if(e.isIdentifier(c)){c=e.literal(f.key.name)}i.push(c)}i=e.arrayExpression(i);var h=e.callExpression(l.file.addHelper("object-without-properties"),[d,i]);u.push(n(l,t.argument,h))}else{if(e.isLiteral(t.key))t.computed=true;var p=t.value;var m=e.memberExpression(d,t.key,t.computed);if(e.isPattern(p)){r(l,u,p,m)}else{u.push(n(l,p,m))}}}};var l=function(i,l,n,a){if(!n.elements)return;var t;var u=false;for(t=0;t<n.elements.length;t++){if(e.isSpreadElement(n.elements[t])){u=true;break}}var c=i.file.toArray(a,!u&&n.elements.length);var f=i.scope.generateUidBasedOnNode(a,i.file);l.push(e.variableDeclaration("var",[e.variableDeclarator(f,c)]));a=f;for(t=0;t<n.elements.length;t++){var s=n.elements[t];if(!s)continue;t=+t;var o;if(e.isSpreadElement(s)){o=i.file.toArray(a);if(t>0){o=e.callExpression(e.memberExpression(o,e.identifier("slice")),[e.literal(t)])}s=s.argument}else{o=e.memberExpression(a,e.literal(t),true)}r(i,l,s,o)}};var i=function(n){var i=n.nodes;var s=n.pattern;var t=n.id;var o=n.file;var l=n.scope;if(!e.isArrayExpression(t)&&!e.isMemberExpression(t)&&!e.isIdentifier(t)){var a=l.generateUidBasedOnNode(t,o);i.push(e.variableDeclaration("var",[e.variableDeclarator(a,t)]));t=a}r(n,i,s,t)};t.ForInStatement=t.ForOfStatement=function(t,f,i,a){var n=t.left;if(!e.isVariableDeclaration(n))return;var s=n.declarations[0].id;if(!e.isPattern(s))return;var o=i.generateUidIdentifier("ref",a);t.left=e.variableDeclaration(n.kind,[e.variableDeclarator(o,null)]);var l=[];r({kind:n.kind,file:i,scope:a},l,s,o);e.ensureBlock(t);var u=t.body;u.body=l.concat(u.body)};t.Function=function(t,l,r,n){var a=[];var s=false;t.params=t.params.map(function(t){if(!e.isPattern(t))return t;s=true;var o=r.generateUidIdentifier("ref",n);i({kind:"var",nodes:a,pattern:t,id:o,file:r,scope:n});return o});if(!s)return;e.ensureBlock(t);var o=t.body;o.body=a.concat(o.body)};t.CatchClause=function(t,l,n,i){var a=t.param;if(!e.isPattern(a))return;var s=n.generateUidIdentifier("ref",i);t.param=s;var o=[];r({kind:"var",file:n,scope:i},o,a,s);t.body.body=o.concat(t.body.body)};t.ExpressionStatement=function(o,l,i,a){var t=o.expression;if(t.type!=="AssignmentExpression")return;if(!e.isPattern(t.left))return;var n=[];var s=i.generateUidIdentifier("ref",a);n.push(e.variableDeclaration("var",[e.variableDeclarator(s,t.right)]));r({operator:t.operator,file:i,scope:a},n,t.left,s);return n};t.AssignmentExpression=function(t,l,s,n){if(l.type==="ExpressionStatement")return;if(!e.isPattern(t.left))return;var o=s.generateUid("temp",n);var i=e.identifier(o);n.push({key:o,id:i});var a=[];a.push(e.assignmentExpression("=",i,t.right));r({operator:t.operator,file:s,scope:n},a,t.left,i);a.push(i);return e.toSequenceExpression(a,n)};t.VariableDeclaration=function(a,o,l,d){if(e.isForInStatement(o)||e.isForOfStatement(o))return;var s=[];var r;var t;var u=false;for(r=0;r<a.declarations.length;r++){t=a.declarations[r];if(e.isPattern(t.id)){u=true;break}}if(!u)return;for(r=0;r<a.declarations.length;r++){t=a.declarations[r];var f=t.init;var c=t.id;var p={kind:a.kind,nodes:s,pattern:c,id:f,file:l,scope:d};if(e.isPattern(c)&&f){i(p);if(+r!==a.declarations.length-1){e.inherits(s[s.length-1],t)}}else{s.push(e.inherits(n(p,t.id,t.init),t))}}if(!e.isProgram(o)&&!e.isBlockStatement(o)){t=null;for(r=0;r<s.length;r++){a=s[r];t=t||e.variableDeclaration(a.kind,[]);if(!e.isVariableDeclaration(a)&&t.kind!==a.kind){throw l.errorWithNode(a,"Cannot use this node within the current parent")}t.declarations=t.declarations.concat(a.declarations)}return t}return s}},{"../../types":85}],51:[function(t,s,n){var r=t("../../util");var e=t("../../types");n.ForOfStatement=function(t,f,l,c){var u=a;if(l.isLoose("forOf"))u=i;var n=u(t,f,l,c);var s=n.declar;var o=n.loop;var r=o.body;e.inheritsComments(o,t);e.ensureBlock(t);if(s){if(n.shouldUnshift){r.body.unshift(s)}else{r.body.push(s)}}r.body=r.body.concat(t.body.body);return o};var i=function(s,u,n,a){var t=s.left;var o,i;if(e.isIdentifier(t)||e.isPattern(t)){i=t}else if(e.isVariableDeclaration(t)){i=t.declarations[0].id;o=e.variableDeclaration(t.kind,[e.variableDeclarator(i)])}else{throw n.errorWithNode(t,"Unknown node type "+t.type+" in ForOfStatement")}var l=r.template("for-of-loose",{LOOP_OBJECT:n.generateUidIdentifier("iterator",a),IS_ARRAY:n.generateUidIdentifier("isArray",a),OBJECT:s.right,INDEX:n.generateUidIdentifier("i",a),ID:i});return{shouldUnshift:true,declar:o,loop:l}};var a=function(a,f,n,s){var t=a.left;var i;var o=n.generateUidIdentifier("step",s);var l=e.memberExpression(o,e.identifier("value"));if(e.isIdentifier(t)||e.isPattern(t)){i=e.expressionStatement(e.assignmentExpression("=",t,l))}else if(e.isVariableDeclaration(t)){i=e.variableDeclaration(t.kind,[e.variableDeclarator(t.declarations[0].id,l)])}else{throw n.errorWithNode(t,"Unknown node type "+t.type+" in ForOfStatement")}var u=r.template("for-of",{ITERATOR_KEY:n.generateUidIdentifier("iterator",s),STEP_KEY:o,OBJECT:a.right});return{declar:i,loop:u}}},{"../../types":85,"../../util":87}],52:[function(e,n,t){var r=e("regenerator");t.ast={before:function(e,t){r.transform(e,{includeRuntime:t.opts.includeRegenerator&&"if used"})}}},{regenerator:154}],53:[function(a,f,s){var r=a("../../traverse");var u=a("../../util");var e=a("../../types");var n=a("lodash");var i=function(t,r){if(!e.isVariableDeclaration(t))return false;if(t._let)return true;if(t.kind!=="let")return false;if(!e.isFor(r)||e.isFor(r)&&r.left!==t){n.each(t.declarations,function(t){t.init=t.init||e.identifier("undefined")})}t._let=true;t.kind="var";return true};var o=function(t,r){return e.isVariableDeclaration(t,{kind:"var"})&&!i(t,r)};var l=function(t){for(var e=0;e<t.length;e++){delete t[e]._let}};s.VariableDeclaration=function(e,t){i(e,t)};s.Loop=function(r,n,s,o){var a=r.left||r.init;if(i(a,r)){e.ensureBlock(r);r.body._letDeclars=[a]}if(e.isLabeledStatement(n)){r.label=n.label}var l=new t(r,r.body,n,s,o);l.run();if(r.label&&!e.isLabeledStatement(n)){return e.labeledStatement(r.label,r)}};s.BlockStatement=function(n,r,i,a){if(!e.isLoop(r)){var s=new t(false,n,r,i,a);s.run()}};function t(e,t,r,n,i){this.loopParent=e;this.parent=r;this.scope=i;this.block=t;this.file=n;this.letReferences={};this.body=[]}t.prototype.run=function(){var t=this.block;if(t._letDone)return;t._letDone=true;this.info=this.getInfo();this.remap();if(e.isFunction(this.parent))return this.noClosure();if(!this.info.keys.length)return this.noClosure();var o=this.getLetReferences();if(!o)return this.noClosure();this.has=this.checkLoop();this.hoistVarDeclarations();l(this.info.declarators);var s=n.values(this.letReferences);var i=e.functionExpression(null,s,e.blockStatement(t.body));i._aliasFunction=true;t.body=this.body;var u=this.getParams(s);var a=e.callExpression(i,u);var f=this.file.generateUidIdentifier("ret",this.scope);var c=r.hasType(i.body,"YieldExpression",e.FUNCTION_TYPES);if(c){i.generator=true;a=e.yieldExpression(a,true)}this.build(f,a)};t.prototype.noClosure=function(){l(this.info.declarators)};t.prototype.remap=function(){var a=this.info.duplicates;var s=this.block;if(!this.info.hasDuplicates)return;var n=function(t,n,r){if(!e.isIdentifier(t))return;if(!e.isReferenced(t,n))return;if(r&&r.hasOwn(t.name))return;t.name=a[t.name]||t.name};var i=function(e,t){n(e,t);r(e,{enter:n})};var t=this.loopParent;if(t){i(t.right,t);i(t.test,t);i(t.update,t)}r(s,{enter:n})};t.prototype.getInfo=function(){var a=this.block;var u=this.scope;var p=this.file;var t={outsideKeys:[],declarators:a._letDeclars||[],duplicates:{},hasDuplicates:false,keys:[]};var f=function(r,e){var n=u.parentGet(e);if(n&&n!==r){t.duplicates[e]=r.name=p.generateUid(e,u);t.hasDuplicates=true}};var s;for(var r=0;r<t.declarators.length;r++){s=t.declarators[r];var o=e.getIds(s,true);n.each(o,f);o=Object.keys(o);t.outsideKeys=t.outsideKeys.concat(o);t.keys=t.keys.concat(o)}if(a.body){for(r=0;r<a.body.length;r++){s=a.body[r];if(!i(s,a))continue;var c=e.getIds(s,true);for(var l in c){f(c[l],l);t.keys.push(l)}}}return t};t.prototype.checkLoop=function(){var t={hasContinue:false,hasReturn:false,hasBreak:false};r(this.block,{enter:function(r,i){var n;if(e.isFunction(r)||e.isLoop(r)){return this.skip()}if(r&&!r.label){if(e.isBreakStatement(r)){if(e.isSwitchCase(i))return;t.hasBreak=true;n=e.returnStatement(e.literal("break"))}else if(e.isContinueStatement(r)){t.hasContinue=true;n=e.returnStatement(e.literal("continue"))}}if(e.isReturnStatement(r)){t.hasReturn=true;n=e.returnStatement(e.objectExpression([e.property("init",e.identifier("v"),r.argument||e.identifier("undefined"))]))}if(n)return e.inherits(n,r)}});return t};t.prototype.hoistVarDeclarations=function(){var t=this;r(this.block,{enter:function(r,n){if(e.isForStatement(r)){if(o(r.init,r)){r.init=e.sequenceExpression(t.pushDeclar(r.init))}}else if(e.isFor(r)){if(o(r.left,r)){r.left=r.left.declarations[0].id}}else if(o(r,n)){return t.pushDeclar(r).map(e.expressionStatement)}else if(e.isFunction(r)){return this.skip()}}})};t.prototype.getParams=function(e){var t=this.info;e=n.cloneDeep(e);n.each(e,function(e){e.name=t.duplicates[e.name]||e.name});return e};t.prototype.getLetReferences=function(){var t=false;var i=this;r(this.block,{enter:function(a,o,s){if(e.isFunction(a)){r(a,{enter:function(r,a){if(!e.isIdentifier(r))return;if(!e.isReferenced(r,a))return;if(s.hasOwn(r.name,true))return;t=true;if(!n.contains(i.info.outsideKeys,r.name))return;i.letReferences[r.name]=r}});return this.skip()}}});return t};t.prototype.pushDeclar=function(t){this.body.push(e.variableDeclaration(t.kind,t.declarations.map(function(t){return e.variableDeclarator(t.id)})));var i=[];for(var n=0;n<t.declarations.length;n++){var r=t.declarations[n];if(!r.init)continue;var a=e.assignmentExpression("=",r.id,r.init);i.push(e.inherits(a,r))}return i};t.prototype.build=function(n,r){var t=this.has;if(t.hasReturn||t.hasBreak||t.hasContinue){this.buildHas(n,r)}else{this.body.push(e.expressionStatement(r))}};t.prototype.buildHas=function(n,f){var i=this.body;i.push(e.variableDeclaration("var",[e.variableDeclarator(n,f)]));var s=this.loopParent;var a;var t=this.has;var r=[];if(t.hasReturn){a=u.template("let-scoping-return",{RETURN:n})}if(t.hasBreak||t.hasContinue){var o=s.label=s.label||this.file.generateUidIdentifier("loop",this.scope);if(t.hasBreak){r.push(e.switchCase(e.literal("break"),[e.breakStatement(o)]))}if(t.hasContinue){r.push(e.switchCase(e.literal("continue"),[e.continueStatement(o)]))}if(t.hasReturn){r.push(e.switchCase(null,[a]))}if(r.length===1){var l=r[0];i.push(e.ifStatement(e.binaryExpression("===",n,l.test),l.consequent[0]))}else{i.push(e.switchStatement(n,r))}}else{if(t.hasReturn)i.push(a)}}},{"../../traverse":81,"../../types":85,"../../util":87,lodash:135}],54:[function(r,n,e){var t=r("../../types");e.ast={before:function(e,t){e.program.body=t.dynamicImports.concat(e.program.body)}};e.ImportDeclaration=function(e,n,i){var t=[];if(e.specifiers.length){for(var r=0;r<e.specifiers.length;r++){i.moduleFormatter.importSpecifier(e.specifiers[r],e,t,n)}}else{i.moduleFormatter.importDeclaration(e,t,n)}if(t.length===1){t[0]._blockHoist=e._blockHoist}return t};e.ExportDeclaration=function(e,i,a){var r=[];if(e.declaration){if(t.isVariableDeclaration(e.declaration)){var s=e.declaration.declarations[0];s.init=s.init||t.identifier("undefined")}a.moduleFormatter.exportDeclaration(e,r,i)}else{for(var n=0;n<e.specifiers.length;n++){a.moduleFormatter.exportSpecifier(e.specifiers[n],e,r,i)
}}return r}},{"../../types":85}],55:[function(t,a,r){var i=t("../helpers/name-method");var n=t("../../util");var e=t("../../types");r.Property=function(e,n,t,r){if(!e.method)return;e.method=false;i(e,t,r)};r.ObjectExpression=function(t){var r={};var i=false;t.properties=t.properties.filter(function(e){if(e.kind==="get"||e.kind==="set"){i=true;n.pushMutatorMap(r,e.key,e.kind,e.computed,e.value);return false}else{return true}});if(!i)return;return e.callExpression(e.memberExpression(e.identifier("Object"),e.identifier("defineProperties")),[t,n.buildDefineProperties(r)])}},{"../../types":85,"../../util":87,"../helpers/name-method":26}],56:[function(e,i,t){var r=e("../../types");var n=e("lodash");t.Property=function(e){if(!e.shorthand)return;e.shorthand=false;e.key=r.removeComments(n.clone(e.key))}},{"../../types":85,lodash:135}],57:[function(t,i,r){var n=t("../../util");var e=t("../../types");r.Function=function(t,c,s){if(!t.rest)return;var f=t.rest;delete t.rest;e.ensureBlock(t);var o=e.identifier("arguments");o._ignoreAliasFunctions=true;var r=e.literal(t.params.length);var a=s.generateUidIdentifier("key");var i=s.generateUidIdentifier("len");var l=a;var u=i;if(t.params.length){l=e.binaryExpression("-",a,r);u=e.conditionalExpression(e.binaryExpression(">",i,r),e.binaryExpression("-",i,r),e.literal(0))}t.body.body.unshift(n.template("rest",{ARGUMENTS:o,ARRAY_KEY:l,ARRAY_LEN:u,START:r,ARRAY:f,KEY:a,LEN:i}))}},{"../../types":85,"../../util":87}],58:[function(i,o,t){var e=i("../../types");var a=i("lodash");var s=function(e,t){return t.toArray(e.argument)};var r=function(r){for(var t=0;t<r.length;t++){if(e.isSpreadElement(r[t])){return true}}return false};var n=function(a,l){var r=[];var t=[];var o=function(){if(!t.length)return;r.push(e.arrayExpression(t));t=[]};for(var n=0;n<a.length;n++){var i=a[n];if(e.isSpreadElement(i)){o();r.push(s(i,l))}else{t.push(i)}}o();return r};t.ArrayExpression=function(s,l,o){var a=s.elements;if(!r(a))return;var i=n(a,o);var t=i.shift();if(!e.isArrayExpression(t)){i.unshift(t);t=e.arrayExpression([])}return e.callExpression(e.memberExpression(t,e.identifier("concat")),i)};t.CallExpression=function(t,p,u,c){var a=t.arguments;if(!r(a))return;var o=e.identifier("undefined");t.arguments=[];var s;if(a.length===1&&a[0].argument.name==="arguments"){s=[a[0].argument]}else{s=n(a,u)}var f=s.shift();if(s.length){t.arguments.push(e.callExpression(e.memberExpression(f,e.identifier("concat")),s))}else{t.arguments.push(f)}var i=t.callee;if(e.isMemberExpression(i)){var l=c.generateTempBasedOnNode(i.object,u);if(l){i.object=e.assignmentExpression("=",l,i.object);o=l}else{o=i.object}e.appendToMemberExpression(i,e.identifier("apply"))}else{t.callee=e.memberExpression(t.callee,e.identifier("apply"))}t.arguments.unshift(o)};t.NewExpression=function(i,f,o){var t=i.arguments;if(!r(t))return;var l=e.isIdentifier(i.callee)&&a.contains(e.NATIVE_TYPE_NAMES,i.callee.name);var s=n(t,o);if(l){s.unshift(e.arrayExpression([e.literal(null)]))}var u=s.shift();if(s.length){t=e.callExpression(e.memberExpression(u,e.identifier("concat")),s)}else{t=u}if(l){return e.newExpression(e.callExpression(e.memberExpression(o.addHelper("bind"),e.identifier("apply")),[i.callee,t]),[])}else{return e.callExpression(o.addHelper("apply-constructor"),[i.callee,t])}}},{"../../types":85,lodash:135}],59:[function(n,i,t){var e=n("../../types");var r=function(t,r){return e.binaryExpression("+",t,r)};t.TaggedTemplateExpression=function(s,f,o){var t=[];var i=s.quasi;var r=[];var n=[];for(var a=0;a<i.quasis.length;a++){var l=i.quasis[a];r.push(e.literal(l.value.cooked));n.push(e.literal(l.value.raw))}r=e.arrayExpression(r);n=e.arrayExpression(n);var u="tagged-template-literal";if(o.isLoose("templateLiterals"))u+="-loose";t.push(e.callExpression(o.addHelper(u),[r,n]));t=t.concat(i.expressions);return e.callExpression(s.tag,t)};t.TemplateLiteral=function(i){var t=[];var n;for(n=0;n<i.quasis.length;n++){var o=i.quasis[n];t.push(e.literal(o.value.cooked));var s=i.expressions.shift();if(s)t.push(s)}if(t.length>1){var l=t[t.length-1];if(e.isLiteral(l,{value:""}))t.pop();var a=r(t.shift(),t.shift());for(n=0;n<t.length;n++){a=r(a,t[n])}return a}else{return t[0]}}},{"../../types":85}],60:[function(e,i,t){var r=e("regexpu/rewrite-pattern");var n=e("lodash");t.Literal=function(i){var e=i.regex;if(!e)return;var t=e.flags.split("");if(e.flags.indexOf("u")<0)return;n.pull(t,"u");e.pattern=r(e.pattern,e.flags);e.flags=t.join("")}},{lodash:135,"regexpu/rewrite-pattern":177}],61:[function(n,a,t){var r=n("../../util");var e=n("../../types");t.experimental=true;var i=function(n,t,i){if(e.isExpressionStatement(n)){return t}else{var r=[];if(e.isSequenceExpression(t)){r=t.expressions}else{r.push(t)}r.push(i);return e.sequenceExpression(r)}};t.AssignmentExpression=function(t,l,u,f){var s=t.left;if(!e.isVirtualPropertyExpression(s))return;var n=t.right;var a;if(!e.isExpressionStatement(l)){a=f.generateTempBasedOnNode(t.right,u);if(a)n=a}if(t.operator!=="="){n=e.binaryExpression(t.operator[0],r.template("abstract-expression-get",{PROPERTY:t.property,OBJECT:t.object}),n)}var o=r.template("abstract-expression-set",{PROPERTY:s.property,OBJECT:s.object,VALUE:n});if(a){o=e.sequenceExpression([e.assignmentExpression("=",a,t.right),o])}return i(l,o,n)};t.UnaryExpression=function(n,a){var t=n.argument;if(!e.isVirtualPropertyExpression(t))return;if(n.operator!=="delete")return;var s=r.template("abstract-expression-delete",{PROPERTY:t.property,OBJECT:t.object});return i(a,s,e.literal(true))};t.CallExpression=function(a,l,s,o){var t=a.callee;if(!e.isVirtualPropertyExpression(t))return;var i=o.generateTempBasedOnNode(t.object,s);var n=r.template("abstract-expression-call",{PROPERTY:t.property,OBJECT:i||t.object});n.arguments=n.arguments.concat(a.arguments);if(i){return e.sequenceExpression([e.assignmentExpression("=",i,t.object),n])}else{return n}};t.VirtualPropertyExpression=function(e){return r.template("abstract-expression-get",{PROPERTY:e.property,OBJECT:e.object})};t.PrivateDeclaration=function(t){return e.variableDeclaration("const",t.declarations.map(function(t){return e.variableDeclarator(t,e.newExpression(e.identifier("WeakMap"),[]))}))}},{"../../types":85,"../../util":87}],62:[function(e,o,t){var i=e("../helpers/build-comprehension");var a=e("../../traverse");var r=e("../../util");var n=e("../../types");t.experimental=true;var s=function(t,l,u,f){var o=f.generateUidBasedOnNode(l,u);var e=r.template("array-comprehension-container",{KEY:o});e.callee._aliasFunction=true;var c=e.callee.body;var s=c.body;if(a.hasType(t,"YieldExpression",n.FUNCTION_TYPES)){e.callee.generator=true;e=n.yieldExpression(e,true)}var p=s.pop();s.push(i(t,function(){return r.template("array-push",{STATEMENT:t.body,KEY:o},true)}));s.push(p);return e};t.ComprehensionExpression=function(e,t,r,n){if(e.generator)return;return s(e,t,r,n)}},{"../../traverse":81,"../../types":85,"../../util":87,"../helpers/build-comprehension":25}],63:[function(n,i,t){t.experimental=true;var e=n("../../types");var r=e.memberExpression(e.identifier("Math"),e.identifier("pow"));t.AssignmentExpression=function(t){if(t.operator!=="**=")return;t.operator="=";t.right=e.callExpression(r,[t.left,t.right])};t.BinaryExpression=function(t){if(t.operator!=="**")return;return e.callExpression(r,[t.left,t.right])}},{"../../types":85}],64:[function(t,i,r){var n=t("../helpers/build-comprehension");var e=t("../../types");r.experimental=true;r.ComprehensionExpression=function(t){if(!t.generator)return;var r=[];var i=e.functionExpression(null,[],e.blockStatement(r),true);i._aliasFunction=true;r.push(n(t,function(){return e.expressionStatement(e.yieldExpression(t.body))}));return e.callExpression(i,[])}},{"../../types":85,"../helpers/build-comprehension":25}],65:[function(r,n,t){var e=r("../../types");t.experimental=true;t.ObjectExpression=function(i,u,l){var s=false;var t;var r;for(t=0;t<i.properties.length;t++){r=i.properties[t];if(e.isSpreadProperty(r)){s=true;break}}if(!s)return;var n=[];var a=[];var o=function(){if(!a.length)return;n.push(e.objectExpression(a));a=[]};for(t=0;t<i.properties.length;t++){r=i.properties[t];if(e.isSpreadProperty(r)){o();n.push(r.argument)}else{a.push(r)}}o();if(!e.isObjectExpression(n[0])){n.unshift(e.objectExpression([]))}return e.callExpression(l.addHelper("extends"),n)}},{"../../types":85}],66:[function(t,i,e){var r=t("../helpers/remap-async-to-generator");var n=t("./optional-bluebird-coroutines");e.optional=true;e.manipulateOptions=n.manipulateOptions;e.Function=function(e,n,t){if(!e.async||e.generator)return;return r(e,t.addHelper("async-to-generator"))}},{"../helpers/remap-async-to-generator":27,"./optional-bluebird-coroutines":67}],67:[function(t,i,e){var n=t("../helpers/remap-async-to-generator");var r=t("../../types");e.manipulateOptions=function(e){e.experimental=true;e.blacklist.push("generators")};e.optional=true;e.Function=function(e,i,t){if(!e.async||e.generator)return;return n(e,r.memberExpression(t.addImport("bluebird"),r.identifier("coroutine")))}},{"../../types":85,"../helpers/remap-async-to-generator":27}],68:[function(t,u,n){var a=t("../../traverse");var s=t("../../util");var i=t("core-js/library");var e=t("../../types");var r=t("lodash");var o=function(e){return e.name!=="_"&&r.has(i,e.name)};var l=["Symbol","Promise","Map","WeakMap","Set","WeakSet"];n.optional=true;n.ast={enter:function(t,e){e._coreId=e.addImport("core-js/library","core")},exit:function(n,t){a(n,{enter:function(n,f){var a;if(e.isMemberExpression(n)&&e.isReferenced(n,f)){var c=n.object;a=n.property;if(!e.isReferenced(c,n))return;if(!n.computed&&o(c)&&r.has(i[c.name],a.name)){this.skip();return e.prependToMemberExpression(n,t._coreId)}}else if(e.isIdentifier(n)&&!e.isMemberExpression(f)&&e.isReferenced(n,f)&&r.contains(l,n.name)){return e.memberExpression(t._coreId,n)}else if(e.isCallExpression(n)){if(n.arguments.length)return;var u=n.callee;if(!e.isMemberExpression(u))return;if(!u.computed)return;a=u.property;if(!e.isIdentifier(a.object,{name:"Symbol"}))return;if(!e.isIdentifier(a.property,{name:"iterator"}))return;return s.template("corejs-iterator",{CORE_ID:t._coreId,VALUE:u.object})}}})}}},{"../../traverse":81,"../../types":85,"../../util":87,"core-js/library":128,lodash:135}],69:[function(r,o,t){var e=r("../../types");var a=r("lodash");var s=function(t){return e.isLiteral(e.toComputedKey(t,t.key),{value:"__proto__"})};var n=function(r){var t=r.left;return e.isMemberExpression(t)&&e.isLiteral(e.toComputedKey(t,t.property),{value:"__proto__"})};var i=function(t,r,n){return e.expressionStatement(e.callExpression(n.addHelper("defaults"),[r,t.right]))};t.optional=true;t.secondPass=true;t.AssignmentExpression=function(t,o,s,l){if(e.isExpressionStatement(o))return;if(!n(t))return;var r=[];var u=t.left.object;var a=l.generateTempBasedOnNode(t.left.object,s);r.push(e.expressionStatement(e.assignmentExpression("=",a,u)));r.push(i(t,a,s));if(a)r.push(a);return e.toSequenceExpression(r)};t.ExpressionStatement=function(r,s,a){var t=r.expression;if(!e.isAssignmentExpression(t,{operator:"="}))return;if(n(t)){return i(t,t.left.object,a)}};t.ObjectExpression=function(t,u,l){var r;for(var n=0;n<t.properties.length;n++){var i=t.properties[n];if(s(i)){r=i.value;a.pull(t.properties,i)}}if(r){var o=[e.objectExpression([]),r];if(t.properties.length)o.push(t);return e.callExpression(l.addHelper("extends"),o)}}},{"../../types":85,lodash:135}],70:[function(r,n,t){var e=r("../../types");t.optional=true;t.UnaryExpression=function(t,a,i){this.skip();if(t.operator==="typeof"){var r=e.callExpression(i.addHelper("typeof"),[t.argument]);if(e.isIdentifier(t.argument)){var n=e.literal("undefined");return e.conditionalExpression(e.binaryExpression("===",e.unaryExpression("typeof",t.argument),n),n,r)}else{return r}}}},{"../../types":85}],71:[function(r,n,t){var e=r("../../types");t.optional=true;t.Identifier=function(t,r){if(t.name==="undefined"&&e.isReferenced(t,r)){return e.unaryExpression("void",e.literal(0),true)}}},{"../../types":85}],72:[function(l,u,t){var e=l("../../types");var r=function(t){var r=e.isAssignmentExpression(t)&&t.operator==="?=";if(r)e.assertMemberExpression(t.left);return r};var n=function(a,t,s,o){var r=t.property;var n=e.toComputedKey(t,t.property);if(e.isLiteral(n)){return n}else{var i=o.generateUidBasedOnNode(r,s);a.push(e.variableDeclaration("var",[e.variableDeclarator(i,r)]));return i}};var i=function(n,t,i,a){var r=a.generateUidBasedOnNode(t,i);n.push(e.variableDeclaration("var",[e.variableDeclarator(r,t)]));return r};var a=function(t,r,n){return e.unaryExpression("!",e.callExpression(e.memberExpression(n.addHelper("has-own"),e.identifier("call")),[t,r]),true)};var s=function(r,n,t){var i=r.computed||e.isLiteral(t);return e.memberExpression(n,t,i)};var o=function(t,r,n){return e.assignmentExpression("=",s(t.left,r,n),t.right)};t.ExpressionStatement=function(d,m,s,u){var l=d.expression;if(!r(l))return;var t=[];var f=l.left;var c=i(t,f.object,s,u);var p=n(t,f,s,u);t.push(e.ifStatement(a(c,p,s),e.expressionStatement(o(l,c,p))));return t};t.AssignmentExpression=function(l,m,u,f){if(e.isExpressionStatement(m))return;if(!r(l))return;var t=[];var c=l.left;var p=i(t,c.object,u,f);var d=n(t,c,u,f);t.push(e.logicalExpression("&&",a(p,d,u),o(l,p,d)));t.push(s(c,p,d));return e.toSequenceExpression(t,f)}},{"../../types":85}],73:[function(r,n,t){var e=r("../../types");t.BindMemberExpression=function(t,l,a,s){var n=t.object;var o=t.property;var r=s.generateTempBasedOnNode(t.object,a);if(r)n=r;var i=e.callExpression(e.memberExpression(e.memberExpression(n,o),e.identifier("bind")),[n].concat(t.arguments));if(r){return e.sequenceExpression([e.assignmentExpression("=",r,t.object),i])}else{return i}};t.BindFunctionExpression=function(t,s,r,n){var a=function(a){var i=r.generateUidIdentifier("val",n);return e.functionExpression(null,[i],e.blockStatement([e.returnStatement(e.callExpression(e.memberExpression(i,t.callee),a))]))};var i=n.generateTemp(r,"args");return e.sequenceExpression([e.assignmentExpression("=",i,e.arrayExpression(t.arguments)),a(t.arguments.map(function(r,t){return e.memberExpression(i,e.literal(t),true)}))])}},{"../../types":85}],74:[function(t,i,r){var n=t("../../traverse");var e=t("../../types");r.Property=r.MethodDefinition=function(t,s,a){if(t.kind!=="memo")return;t.kind="get";var i=t.value;e.ensureBlock(i);var r=t.key;if(e.isIdentifier(r)&&!t.computed){r=e.literal(r.name)}n(i,{enter:function(t){if(e.isFunction(t))return;if(e.isReturnStatement(t)&&t.argument){t.argument=e.memberExpression(e.callExpression(a.addHelper("define-property"),[e.thisExpression(),r,t.argument]),r,true)}}})}},{"../../traverse":81,"../../types":85}],75:[function(r,o,t){var i=r("esutils");var e=r("../../types");var a=r("lodash");t.XJSIdentifier=function(t){if(i.keyword.isIdentifierName(t.name)){t.type="Identifier"}else{return e.literal(t.name)}};t.XJSNamespacedName=function(e,r,t){throw t.errorWithNode(e,"Namespace tags are not supported. ReactJSX is not XML.")};t.XJSMemberExpression={exit:function(t){t.computed=e.isLiteral(t.property);t.type="MemberExpression"}};t.XJSExpressionContainer=function(e){return e.expression};t.XJSAttribute={exit:function(t){var r=t.value||e.literal(true);return e.inherits(e.property("init",t.name,r),t)}};var n=function(e){return/^[a-z]|\-/.test(e)};t.XJSOpeningElement={exit:function(c,d,p){var u=p.opts.reactCompat;var t=c.name;var s=[];var r;if(e.isIdentifier(t)){r=t.name}else if(e.isLiteral(t)){r=t.value}if(!u){if(r&&n(r)){s.push(e.literal(r))}else{s.push(t)}}var a=c.attributes;if(a.length){var o=[];var i=[];var f=function(){if(!o.length)return;i.push(e.objectExpression(o));o=[]};while(a.length){var l=a.shift();if(e.isXJSSpreadAttribute(l)){f();i.push(l.argument)}else{o.push(l)}}f();if(i.length===1){a=i[0]}else{if(!e.isObjectExpression(i[0])){i.unshift(e.objectExpression([]))}a=e.callExpression(e.memberExpression(e.identifier("React"),e.identifier("__spread")),i)}}else{a=e.literal(null)}s.push(a);if(u){if(r&&n(r)){return e.callExpression(e.memberExpression(e.memberExpression(e.identifier("React"),e.identifier("DOM")),t,e.isLiteral(t)),s)}}else{t=e.memberExpression(e.identifier("React"),e.identifier("createElement"))}return e.callExpression(t,s)}};t.XJSElement={exit:function(s){var r=s.openingElement;for(var o=0;o<s.children.length;o++){var n=s.children[o];if(e.isLiteral(n)&&a.isString(n.value)){var l=n.value.split(/\r\n|\n|\r/);for(var i=0;i<l.length;i++){var u=l[i];var f=i===0;var c=i===l.length-1;var t=u.replace(/\t/g," ");if(!f){t=t.replace(/^[ ]+/,"")}if(!c){t=t.replace(/[ ]+$/,"")}if(t){r.arguments.push(e.literal(t))}}continue}else if(e.isXJSEmptyExpression(n)){continue}r.arguments.push(n)}if(r.arguments.length>=3){r._prettyCall=true}return e.inherits(r,s)}};var s=function(u,t){if(!t||!e.isCallExpression(t))return;var r=t.callee;if(!e.isMemberExpression(r))return;var f=r.object;if(!e.isIdentifier(f,{name:"React"}))return;var n=r.property;if(!e.isIdentifier(n,{name:"createClass"}))return;var s=t.arguments;if(s.length!==1)return;var o=s[0];if(!e.isObjectExpression(o))return;var i=o.properties;var l=true;for(var a=0;a<i.length;a++){n=i[a];if(e.isIdentifier(n.key,{name:"displayName"})){l=false;break}}if(l){i.unshift(e.property("init",e.identifier("displayName"),e.literal(u)))}};t.AssignmentExpression=t.Property=t.VariableDeclarator=function(t){var r,n;if(e.isAssignmentExpression(t)){r=t.left;n=t.right}else if(e.isProperty(t)){r=t.key;n=t.value}else if(e.isVariableDeclarator(t)){r=t.id;n=t.init}if(e.isMemberExpression(r)){r=r.property}if(e.isIdentifier(r)){s(r.name,n)}}},{"../../types":85,esutils:133,lodash:135}],76:[function(t,n,r){var e=t("../../types");r.MemberExpression=function(t){var r=t.property;if(t.computed&&e.isLiteral(r)&&e.isValidIdentifier(r.value)){t.property=e.identifier(r.value);t.computed=false}else if(!t.computed&&e.isIdentifier(r)&&!e.isValidIdentifier(r.name)){t.property=e.literal(r.name);t.computed=true}}},{"../../types":85}],77:[function(t,n,e){var r=t("../../types");e.ForInStatement=e.ForOfStatement=function(n,a,i){var e=n.left;if(r.isVariableDeclaration(e)){var t=e.declarations[0];if(t.init)throw i.errorWithNode(t,"No assignments allowed in for-in/of head")}}},{"../../types":85}],78:[function(t,n,r){var e=t("../../types");r.Property=function(r){var t=r.key;if(e.isLiteral(t)&&e.isValidIdentifier(t.value)){r.key=e.identifier(t.value);r.computed=false}else if(!r.computed&&e.isIdentifier(t)&&!e.isValidIdentifier(t.name)){r.key=e.literal(t.name)}}},{"../../types":85}],79:[function(t,r,e){e.MethodDefinition=e.Property=function(e,r,t){if(e.kind==="set"&&e.value.params.length!==1){throw t.errorWithNode(e.value,"Setters must have only one parameter")}}},{}],80:[function(e,i,r){var n=e("../helpers/use-strict");var t=e("../../types");r.ast={exit:function(e){if(!n.has(e.program)){e.program.body.unshift(t.expressionStatement(t.literal("use strict")))}}}},{"../../types":85,"../helpers/use-strict":28}],81:[function(i,a,o){a.exports=t;var s=i("./scope");var r=i("../types");var n=i("lodash");function e(e){this.didSkip=false;this.didRemove=false;this.didStop=false;this.didFlatten=e?e.didFlatten:false}e.prototype.flatten=function(){this.didFlatten=true};e.prototype.remove=function(){this.didRemove=true;this.skip()};e.prototype.skip=function(){this.didSkip=true};e.prototype.stop=function(){this.didStop=true;this.skip()};e.prototype.maybeReplace=function(e,i,a,t){if(e===false)return t;if(e==null)return t;var s=Array.isArray(e);var o=e;if(s)o=e[0];if(o)r.inheritsComments(o,t);t=i[a]=e;if(s&&n.contains(r.STATEMENT_OR_BLOCK_KEYS,a)&&!r.isBlockStatement(i)){r.ensureBlock(i,a)}if(s){this.flatten()}return t};e.prototype.visit=function(i,a,n,u,f){var e=i[a];if(!e)return;if(n.blacklist&&n.blacklist.indexOf(e.type)>-1)return;var o;var l=u;if(r.isScope(e))l=new s(e,u);if(n.enter){o=n.enter.call(this,e,f,l);e=this.maybeReplace(o,i,a,e);if(this.didRemove){i[a]=null;this.flatten()}if(this.didSkip)return}t(e,n,l);if(n.exit){o=n.exit.call(this,e,f,l);e=this.maybeReplace(o,i,a,e)}};function t(i,o,u){if(!i)return;if(Array.isArray(i)){for(var f=0;f<i.length;f++)t(i[f],o,u);return}var c=r.VISITOR_KEYS[i.type];if(!c)return;o=o||{};var a=null;for(var p=0;p<c.length;p++){var s=c[p];var l=i[s];if(!l)continue;if(Array.isArray(l)){for(var d=0;d<l.length;d++){a=new e(a);a.visit(l,d,o,u,i);if(a.didStop)return}if(a&&a.didFlatten){i[s]=n.flatten(i[s]);if(s==="body"){i[s]=n.compact(i[s])}}}else{a=new e(a);a.visit(i,s,o,u,i);if(a.didStop)return}}}t.removeProperties=function(e){var r=function(e){delete e._declarations;delete e.extendedRange;delete e._scopeInfo;delete e.tokens;delete e.range;delete e.start;delete e.end;delete e.loc;delete e.raw;i(e.trailingComments);i(e.leadingComments)};var i=function(e){n.each(e,r)};r(e);t(e,{enter:r});return e};t.hasType=function(r,i,e){e=[].concat(e||[]);var a=false;if(n.contains(e,r.type))return false;if(r.type===i)return true;t(r,{blacklist:e,enter:function(e){if(e.type===i){a=true;this.skip()}}});return a}},{"../types":85,"./scope":82,lodash:135}],82:[function(n,s,l){s.exports=t;var o=n("./index");var e=n("../types");var r=n("lodash");var a=["left","init"];function t(t,r){this.parent=r;this.block=t;var e=this.getInfo();this.references=e.references;this.declarations=e.declarations}var i=n("jshint/src/vars");t.defaultDeclarations=r.flatten([i.newEcmaIdentifiers,i.node,i.ecmaIdentifiers,i.reservedVars].map(r.keys));t.add=function(t,n){if(!t)return;r.defaults(n,e.getIds(t,true))};t.prototype.generateTemp=function(t,r){var e=t.generateUidIdentifier(r||"temp",this);this.push({key:e.name,id:e});return e};t.prototype.generateUidBasedOnNode=function(r,s){var t=r;if(e.isAssignmentExpression(r)){t=r.left}else if(e.isVariableDeclarator(r)){t=r.id}else if(e.isProperty(t)){t=t.key}var i=[];var n=function(t){if(e.isMemberExpression(t)){n(t.object);n(t.property)}else if(e.isIdentifier(t)){i.push(t.name)}else if(e.isLiteral(t)){i.push(t.value)}else if(e.isCallExpression(t)){n(t.callee)}};n(t);var a=i.join("$");a=a.replace(/^_/,"")||"ref";return s.generateUidIdentifier(a,this)};t.prototype.generateTempBasedOnNode=function(t,n){if(e.isIdentifier(t)&&this.has(t.name,true)){return null}var r=this.generateUidBasedOnNode(t,n);this.push({key:r.name,id:r});return r};t.prototype.getInfo=function(){var n=this.block;if(n._scopeInfo)return n._scopeInfo;var s=n._scopeInfo={};var l=s.references={};var u=s.declarations={};var i=function(e,r){t.add(e,l);if(!r)t.add(e,u)};if(e.isFor(n)){r.each(a,function(r){var t=n[r];if(e.isLet(t))i(t)});n=n.body}if(e.isBlockStatement(n)||e.isProgram(n)){r.each(n.body,function(t){if(e.isLet(t))i(t)})}if(e.isCatchClause(n)){i(n.param)}if(e.isProgram(n)||e.isFunction(n)){o(n,{enter:function(t,s,o){if(e.isFor(t)){r.each(a,function(n){var r=t[n];if(e.isVar(r))i(r)})}if(e.isFunction(t))return this.skip();if(n.id&&t===n.id)return;if(e.isIdentifier(t)&&e.isReferenced(t,s)&&!o.has(t.name)){i(t,true)}if(e.isDeclaration(t)&&!e.isLet(t)){i(t)}}},this)}if(e.isFunction(n)){i(n.rest);r.each(n.params,function(e){i(e)})}return s};t.prototype.push=function(r){var t=this.block;if(e.isFor(t)||e.isCatchClause(t)||e.isFunction(t)){e.ensureBlock(t);t=t.body}if(e.isBlockStatement(t)||e.isProgram(t)){t._declarations=t._declarations||{};t._declarations[r.key]={kind:r.kind,id:r.id,init:r.init}}else{throw new TypeError("cannot add a declaration here in node type "+t.type)}};t.prototype.add=function(e){t.add(e,this.references)};t.prototype.get=function(e,t){return e&&(this.getOwn(e,t)||this.parentGet(e,t))};t.prototype.getOwn=function(t,n){var e=this.references;if(n)e=this.declarations;return r.has(e,t)&&e[t]};t.prototype.parentGet=function(e,t){return this.parent&&this.parent.get(e,t)};t.prototype.has=function(e,n){return e&&(this.hasOwn(e,n)||this.parentHas(e,n))||r.contains(t.defaultDeclarations,e)};t.prototype.hasOwn=function(e,t){return!!this.getOwn(e,t)};t.prototype.parentHas=function(e,t){return this.parent&&this.parent.has(e,t)}},{"../types":85,"./index":81,"jshint/src/vars":134,lodash:135}],83:[function(t,e,r){e.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement","Loop","While"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement","Loop","While"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ExportDeclaration:["Statement","Declaration"],ImportDeclaration:["Statement","Declaration"],ArrowFunctionExpression:["Scope","Function","Expression"],FunctionDeclaration:["Statement","Declaration","Scope","Function"],FunctionExpression:["Scope","Function","Expression"],BlockStatement:["Statement","Scope"],Program:["Scope"],CatchClause:["Scope"],LogicalExpression:["Binary","Expression"],BinaryExpression:["Binary","Expression"],UnaryExpression:["UnaryLike","Expression"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Statement","Declaration","Class"],ClassExpression:["Class","Expression"],ForOfStatement:["Statement","For","Scope","Loop"],ForInStatement:["Statement","For","Scope","Loop"],ForStatement:["Statement","For","Scope","Loop"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],AssignmentPattern:["Pattern"],Property:["UserWhitespacable"],XJSElement:["UserWhitespacable","Expression"],ArrayExpression:["Expression"],AssignmentExpression:["Expression"],AwaitExpression:["Expression"],BindFunctionExpression:["Expression"],BindMemberExpression:["Expression"],CallExpression:["Expression"],ComprehensionExpression:["Expression"],ConditionalExpression:["Expression"],Identifier:["Expression"],Literal:["Expression"],MemberExpression:["Expression"],NewExpression:["Expression"],ObjectExpression:["Expression"],SequenceExpression:["Expression"],TaggedTemplateExpression:["Expression"],ThisExpression:["Expression"],UpdateExpression:["Expression"],VirtualPropertyExpression:["Expression"],XJSEmptyExpression:["Expression"],XJSMemberExpression:["Expression"],YieldExpression:["Expression"]}},{}],84:[function(t,e,r){e.exports={ArrayExpression:["elements"],ArrowFunctionExpression:["params","body"],AssignmentExpression:["operator","left","right"],BinaryExpression:["operator","left","right"],BlockStatement:["body"],CallExpression:["callee","arguments"],ConditionalExpression:["test","consequent","alternate"],ExpressionStatement:["expression"],File:["program","comments","tokens"],FunctionExpression:["id","params","body","generator"],FunctionDeclaration:["id","params","body","generator"],Identifier:["name"],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],Literal:["value"],LogicalExpression:["operator","left","right"],MemberExpression:["object","property","computed"],MethodDefinition:["key","value","computed","kind"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],Program:["body"],Property:["kind","key","value","computed"],ReturnStatement:["argument"],SequenceExpression:["expressions"],ThrowExpression:["argument"],UnaryExpression:["operator","argument","prefix"],VariableDeclaration:["kind","declarations"],VariableDeclarator:["id","init"],WithStatement:["object","body"],YieldExpression:["argument","delegate"]}},{}],85:[function(r,s,n){var i=r("esutils");var t=r("lodash");var e=n;e.NATIVE_TYPE_NAMES=["Array","Object","Number","Boolean","Date","Array","String"];function a(t,r){var n=e["is"+t]=function(n,i){return e.is(t,n,i,r)};e["assert"+t]=function(r,e){e=e||{};if(!n(r,e)){throw new Error("Expected type "+JSON.stringify(t)+" with option "+JSON.stringify(e))}}}e.STATEMENT_OR_BLOCK_KEYS=["consequent","body"];e.VISITOR_KEYS=r("./visitor-keys");e.ALIAS_KEYS=r("./alias-keys");e.FLIPPED_ALIAS_KEYS={};t.each(e.VISITOR_KEYS,function(t,e){a(e,true)});t.each(e.ALIAS_KEYS,function(r,n){t.each(r,function(t){var r=e.FLIPPED_ALIAS_KEYS[t]=e.FLIPPED_ALIAS_KEYS[t]||[];r.push(n)})});t.each(e.FLIPPED_ALIAS_KEYS,function(r,t){e[t.toUpperCase()+"_TYPES"]=r;a(t,false)});e.is=function(n,t,i,s){if(!t)return;var r=n===t.type;if(!r&&!s){var a=e.FLIPPED_ALIAS_KEYS[n];if(typeof a!=="undefined")r=a.indexOf(t.type)>-1}if(!r){return false}if(typeof i!=="undefined")return e.shallowEqual(t,i);return true};e.BUILDER_KEYS=t.defaults(r("./builder-keys"),e.VISITOR_KEYS);t.each(e.BUILDER_KEYS,function(n,r){e[r[0].toLowerCase()+r.slice(1)]=function(){var i=arguments;var e={type:r};t.each(n,function(t,r){e[t]=i[r]});return e}});e.toComputedKey=function(r,t){if(!r.computed){if(e.isIdentifier(t))t=e.literal(t.name)}return t};e.isFalsyExpression=function(t){if(e.isLiteral(t)){return!t.value}else if(e.isIdentifier(t)){return t.name==="undefined"}return false};e.toSequenceExpression=function(n,i){var r=[];t.each(n,function(n){if(e.isExpression(n)){r.push(n)}if(e.isExpressionStatement(n)){r.push(n.expression)}else if(e.isVariableDeclaration(n)){t.each(n.declarations,function(t){i.push({kind:n.kind,key:t.id.name,id:t.id});r.push(e.assignmentExpression("=",t.id,t.init))})}});if(r.length===1){return r[0]}else{return e.sequenceExpression(r)}};e.shallowEqual=function(i,r){var n=Object.keys(r);var e;for(var t=0;t<n.length;t++){e=n[t];if(i[e]!==r[e])return false}return true};e.appendToMemberExpression=function(t,r,n){t.object=e.memberExpression(t.object,t.property,t.computed);t.property=r;t.computed=!!n;return t};e.prependToMemberExpression=function(t,r){t.object=e.memberExpression(r,t.object);return t};e.isReferenced=function(n,r){if(e.isProperty(r)&&r.key===n&&!r.computed)return false;if(e.isFunction(r)){if(t.contains(r.params,n))return false;if(r.rest===n)return false}if(e.isMethodDefinition(r)&&r.key===n&&!r.computed){return false}if(e.isCatchClause(r)&&r.param===n)return false;if(e.isVariableDeclarator(r)&&r.id===n)return false;var i=e.isMemberExpression(r);var a=i&&r.property===n&&r.computed;var s=i&&r.object===n;if(!i||a||s)return true;return false};e.isValidIdentifier=function(e){return t.isString(e)&&i.keyword.isIdentifierName(e)&&!i.keyword.isReservedWordES6(e,true)};e.toIdentifier=function(t){if(e.isIdentifier(t))return t.name;t=t+"";t=t.replace(/[^a-zA-Z0-9$_]/g,"-");t=t.replace(/^[-0-9]+/,"");t=t.replace(/[-_\s]+(.)?/g,function(t,e){return e?e.toUpperCase():""});t=t.replace(/^\_/,"");if(!e.isValidIdentifier(t)){t="_"+t}return t||"_"};e.ensureBlock=function(r,t){t=t||"body";r[t]=e.toBlock(r[t],r)};e.toStatement=function(t,i){if(e.isStatement(t)){return t}var n=false;var r;if(e.isClass(t)){n=true;r="ClassDeclaration"}else if(e.isFunction(t)){n=true;r="FunctionDeclaration"}if(n&&!t.id){r=false}if(!r){if(i){return false}else{throw new Error("cannot turn "+t.type+" to a statement")}}t.type=r;return t};n.toExpression=function(t){if(e.isExpressionStatement(t)){t=t.expression}if(e.isClass(t)){t.type="ClassExpression"}else if(e.isFunction(t)){t.type="FunctionExpression"}if(e.isExpression(t)){return t}else{throw new Error("cannot turn "+t.type+" to an expression")}};e.toBlock=function(t,r){if(e.isBlockStatement(t)){return t}if(e.isEmptyStatement(t)){t=[]}if(!Array.isArray(t)){if(!e.isStatement(t)){if(e.isFunction(r)){t=e.returnStatement(t)}else{t=e.expressionStatement(t)}}t=[t]}return e.blockStatement(t)};e.getIds=function(f,c,o){o=o||[];var i=[].concat(f);var s={};while(i.length){var r=i.shift();if(!r)continue;if(t.contains(o,r.type))continue;var l=e.getIds.nodes[r.type];var u=e.getIds.arrays[r.type];var n,a;if(e.isIdentifier(r)){s[r.name]=r}else if(l){for(n=0;n<l.length;n++){a=l[n];if(r[a]){i.push(r[a]);break}}}else if(u){for(n=0;n<u.length;n++){a=u[n];i=i.concat(r[a]||[])}}}if(!c)s=t.keys(s);return s};e.getIds.nodes={AssignmentExpression:["left"],ImportBatchSpecifier:["name"],ImportSpecifier:["name","id"],ExportSpecifier:["name","id"],VariableDeclarator:["id"],FunctionDeclaration:["id"],ClassDeclaration:["id"],MemeberExpression:["object"],SpreadElement:["argument"],Property:["value"]};
e.getIds.arrays={ExportDeclaration:["specifiers","declaration"],ImportDeclaration:["specifiers"],VariableDeclaration:["declarations"],ArrayPattern:["elements"],ObjectPattern:["properties"]};e.isLet=function(t){return e.isVariableDeclaration(t)&&(t.kind!=="var"||t._let)};e.isVar=function(t){return e.isVariableDeclaration(t,{kind:"var"})&&!t._let};e.COMMENT_KEYS=["leadingComments","trailingComments"];e.removeComments=function(r){t.each(e.COMMENT_KEYS,function(e){delete r[e]});return r};e.inheritsComments=function(r,n){t.each(e.COMMENT_KEYS,function(e){r[e]=t.uniq(t.compact([].concat(r[e],n[e])))});return r};e.inherits=function(t,r){t.loc=r.loc;t.end=r.end;t.range=r.range;t.start=r.start;e.inheritsComments(t,r);return t};e.getSpecifierName=function(e){return e.name||e.id};e.isSpecifierDefault=function(t){return e.isIdentifier(t.id)&&t.id.name==="default"}},{"./alias-keys":83,"./builder-keys":84,"./visitor-keys":86,esutils:133,lodash:135}],86:[function(t,e,r){e.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BindFunctionExpression:["callee","arguments"],BindMemberExpression:["object","property","arguments"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right","body"],ComprehensionExpression:["filter","blocks","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportBatchSpecifier:["id"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateDeclaration:["declarations"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SpreadProperty:["argument"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],VirtualPropertyExpression:["object","property"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"],AnyTypeAnnotation:[],ArrayTypeAnnotation:[],BooleanTypeAnnotation:[],ClassProperty:["key"],DeclareClass:[],DeclareFunction:[],DeclareModule:[],DeclareVariable:[],FunctionTypeAnnotation:[],FunctionTypeParam:[],GenericTypeAnnotation:[],InterfaceExtends:[],InterfaceDeclaration:[],IntersectionTypeAnnotation:[],NullableTypeAnnotation:[],NumberTypeAnnotation:[],StringLiteralTypeAnnotation:[],StringTypeAnnotation:[],TupleTypeAnnotation:[],TypeofTypeAnnotation:[],TypeAlias:[],TypeAnnotation:[],TypeParameterDeclaration:[],TypeParameterInstantiation:[],ObjectTypeAnnotation:[],ObjectTypeCallProperty:[],ObjectTypeIndexer:[],ObjectTypeProperty:[],QualifiedTypeIdentifier:[],UnionTypeAnnotation:[],VoidTypeAnnotation:[],XJSAttribute:["name","value"],XJSClosingElement:["name"],XJSElement:["openingElement","closingElement","children"],XJSEmptyExpression:[],XJSExpressionContainer:["expression"],XJSIdentifier:[],XJSMemberExpression:["object","property"],XJSNamespacedName:["namespace","name"],XJSOpeningElement:["name","attributes"],XJSSpreadAttribute:["argument"]}},{}],87:[function(t,r,e){(function(u,l){t("./patch");var c=t("estraverse");var i=t("./traverse");var f=t("acorn-6to5");var a=t("path");var d=t("util");var s=t("fs");var r=t("./types");var n=t("lodash");e.inherits=d.inherits;e.canCompile=function(t,r){var i=r||e.canCompile.EXTENSIONS;var s=a.extname(t);return n.contains(i,s)};e.canCompile.EXTENSIONS=[".js",".jsx",".es6",".es"];e.isInteger=function(e){return n.isNumber(e)&&e%1===0};e.resolve=function(e){try{return t.resolve(e)}catch(r){return null}};e.trimRight=function(e){return e.replace(/[\n\s]+$/g,"")};e.list=function(e){return e?e.split(","):[]};e.regexify=function(e){if(!e)return new RegExp(/.^/);if(Array.isArray(e))e=e.join("|");if(n.isString(e))return new RegExp(e);if(n.isRegExp(e))return e;throw new TypeError("illegal type for regexify")};e.arrayify=function(t){if(!t)return[];if(n.isString(t))return e.list(t);if(Array.isArray(t))return t;throw new TypeError("illegal type for arrayify")};e.isAbsolute=function(e){if(!e)return false;if(e[0]==="/")return true;if(e[1]===":"&&e[2]==="\\")return true;return false};e.sourceMapToComment=function(e){var t=JSON.stringify(e);var r=new u(t).toString("base64");return"//# sourceMappingURL=data:application/json;base64,"+r};e.pushMutatorMap=function(s,t,l,o,u){var e;if(r.isIdentifier(t)){e=t.name;if(o)e="computed:"+e}else if(r.isLiteral(t)){e=String(t.value)}else{e=JSON.stringify(i.removeProperties(n.cloneDeep(t)))}var a;if(n.has(s,e)){a=s[e]}else{a={}}s[e]=a;a._key=t;if(o){a._computed=true}a[l]=u};e.buildDefineProperties=function(t){var e=r.objectExpression([]);n.each(t,function(t){var i=r.objectExpression([]);var a=r.property("init",t._key,i,t._computed);if(!t.get&&!t.set){t.writable=r.literal(true)}t.enumerable=r.literal(true);t.configurable=r.literal(true);n.each(t,function(e,t){if(t[0]==="_")return;e=n.clone(e);var a=e;if(r.isMethodDefinition(e))e=e.value;var s=r.property("init",r.identifier(t),e);r.inheritsComments(s,a);r.removeComments(a);i.properties.push(s)});e.properties.push(a)});return e};e.template=function(o,t,l){var a=e.templates[o];if(!a)throw new ReferenceError("unknown template "+o);if(t===true){l=true;t=null}a=n.cloneDeep(a);if(!n.isEmpty(t)){i(a,{enter:function(e){if(r.isIdentifier(e)&&n.has(t,e.name)){return t[e.name]}}})}var s=a.body[0];if(!l&&r.isExpressionStatement(s)){return s.expression}else{return s}};e.codeFrame=function(t,r,n){n=Math.max(n,0);t=t.split("\n");var i=Math.max(r-3,0);var a=Math.min(t.length,r+3);var s=(a+"").length;if(!r&&!n){i=0;a=t.length}return"\n"+t.slice(i,a).map(function(l,u){var a=u+i+1;var o=a===r?"> ":" ";var f=a+e.repeat(s+1);o+=f+"| ";var t=o+l;if(n&&a===r){t+="\n";t+=e.repeat(o.length-2);t+="|"+e.repeat(n)+"^"}return t}).join("\n")};e.repeat=function(n,e){e=e||" ";var t="";for(var r=0;r<n;r++){t+=e}return t};e.normaliseAst=function(e,t,n){if(e&&e.type==="Program"){return r.file(e,t||[],n||[])}else{throw new Error("Not a valid ast?")}};e.parse=function(n,l,u){try{var i=[];var a=[];var r=f.parse(l,{allowImportExportEverywhere:true,allowReturnOutsideFunction:true,ecmaVersion:n.experimental?7:6,playground:n.playground,strictMode:true,onComment:i,locations:true,onToken:a,ranges:true});c.attachComments(r,i,a);r=e.normaliseAst(r,i,a);if(u){return u(r)}else{return r}}catch(t){if(!t._6to5){t._6to5=true;var s=n.filename+": "+t.message;var o=t.loc;if(o){var p=e.codeFrame(l,o.line,o.column);s+=p}if(t.stack)t.stack=t.stack.replace(t.message,s);t.message=s}throw t}};e.parseTemplate=function(t,r){var n=e.parse({filename:t},r).program;return i.removeProperties(n)};var p=function(){var r={};var t=l+"/transformation/templates";if(!s.existsSync(t)){throw new Error("no templates directory - this is most likely the "+"result of a broken `npm publish`. Please report to "+"https://github.com/6to5/6to5/issues")}n.each(s.readdirSync(t),function(n){if(n[0]===".")return;var o=a.basename(n,a.extname(n));var i=t+"/"+n;var l=s.readFileSync(i,"utf8");r[o]=e.parseTemplate(i,l)});return r};try{e.templates=t("../../templates.json")}catch(o){if(o.code!=="MODULE_NOT_FOUND")throw o;e.templates=p()}}).call(this,t("buffer").Buffer,"/lib/6to5")},{"../../templates.json":189,"./patch":24,"./traverse":81,"./types":85,"acorn-6to5":1,buffer:104,estraverse:129,fs:102,lodash:135,path:111,util:127}],88:[function(u,g,b){var o=u("../lib/types");var l=o.Type;var e=l.def;var t=l.or;var a=o.builtInTypes;var i=a.string;var p=a.number;var n=a.boolean;var c=a.RegExp;var f=u("../lib/shared");var r=f.defaults;var s=f.geq;e("Printable").field("loc",t(e("SourceLocation"),null),r["null"],true);e("Node").bases("Printable").field("type",i);e("SourceLocation").build("start","end","source").field("start",e("Position")).field("end",e("Position")).field("source",t(i,null),r["null"]);e("Position").build("line","column").field("line",s(1)).field("column",s(0));e("Program").bases("Node").build("body").field("body",[e("Statement")]).field("comments",t([t(e("Block"),e("Line"))],null),r["null"],true);e("Function").bases("Node").field("id",t(e("Identifier"),null),r["null"]).field("params",[e("Pattern")]).field("body",t(e("BlockStatement"),e("Expression")));e("Statement").bases("Node");e("EmptyStatement").bases("Statement").build();e("BlockStatement").bases("Statement").build("body").field("body",[e("Statement")]);e("ExpressionStatement").bases("Statement").build("expression").field("expression",e("Expression"));e("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",e("Expression")).field("consequent",e("Statement")).field("alternate",t(e("Statement"),null),r["null"]);e("LabeledStatement").bases("Statement").build("label","body").field("label",e("Identifier")).field("body",e("Statement"));e("BreakStatement").bases("Statement").build("label").field("label",t(e("Identifier"),null),r["null"]);e("ContinueStatement").bases("Statement").build("label").field("label",t(e("Identifier"),null),r["null"]);e("WithStatement").bases("Statement").build("object","body").field("object",e("Expression")).field("body",e("Statement"));e("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",e("Expression")).field("cases",[e("SwitchCase")]).field("lexical",n,r["false"]);e("ReturnStatement").bases("Statement").build("argument").field("argument",t(e("Expression"),null));e("ThrowStatement").bases("Statement").build("argument").field("argument",e("Expression"));e("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",e("BlockStatement")).field("handler",t(e("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[e("CatchClause")],function(){return this.handler?[this.handler]:[]},true).field("guardedHandlers",[e("CatchClause")],r.emptyArray).field("finalizer",t(e("BlockStatement"),null),r["null"]);e("CatchClause").bases("Node").build("param","guard","body").field("param",e("Pattern")).field("guard",t(e("Expression"),null),r["null"]).field("body",e("BlockStatement"));e("WhileStatement").bases("Statement").build("test","body").field("test",e("Expression")).field("body",e("Statement"));e("DoWhileStatement").bases("Statement").build("body","test").field("body",e("Statement")).field("test",e("Expression"));e("ForStatement").bases("Statement").build("init","test","update","body").field("init",t(e("VariableDeclaration"),e("Expression"),null)).field("test",t(e("Expression"),null)).field("update",t(e("Expression"),null)).field("body",e("Statement"));e("ForInStatement").bases("Statement").build("left","right","body","each").field("left",t(e("VariableDeclaration"),e("Expression"))).field("right",e("Expression")).field("body",e("Statement")).field("each",n);e("DebuggerStatement").bases("Statement").build();e("Declaration").bases("Statement");e("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",e("Identifier"));e("FunctionExpression").bases("Function","Expression").build("id","params","body");e("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",t("var","let","const")).field("declarations",[t(e("VariableDeclarator"),e("Identifier"))]);e("VariableDeclarator").bases("Node").build("id","init").field("id",e("Pattern")).field("init",t(e("Expression"),null));e("Expression").bases("Node","Pattern");e("ThisExpression").bases("Expression").build();e("ArrayExpression").bases("Expression").build("elements").field("elements",[t(e("Expression"),null)]);e("ObjectExpression").bases("Expression").build("properties").field("properties",[e("Property")]);e("Property").bases("Node").build("kind","key","value").field("kind",t("init","get","set")).field("key",t(e("Literal"),e("Identifier"))).field("value",e("Expression"));e("SequenceExpression").bases("Expression").build("expressions").field("expressions",[e("Expression")]);var d=t("-","+","!","~","typeof","void","delete");e("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",d).field("argument",e("Expression")).field("prefix",n,r["true"]);var m=t("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");e("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",m).field("left",e("Expression")).field("right",e("Expression"));var h=t("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");e("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",h).field("left",e("Pattern")).field("right",e("Expression"));var y=t("++","--");e("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",y).field("argument",e("Expression")).field("prefix",n);var v=t("||","&&");e("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",v).field("left",e("Expression")).field("right",e("Expression"));e("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",e("Expression")).field("consequent",e("Expression")).field("alternate",e("Expression"));e("NewExpression").bases("Expression").build("callee","arguments").field("callee",e("Expression")).field("arguments",[e("Expression")]);e("CallExpression").bases("Expression").build("callee","arguments").field("callee",e("Expression")).field("arguments",[e("Expression")]);e("MemberExpression").bases("Expression").build("object","property","computed").field("object",e("Expression")).field("property",t(e("Identifier"),e("Expression"))).field("computed",n);e("Pattern").bases("Node");e("ObjectPattern").bases("Pattern").build("properties").field("properties",[e("PropertyPattern")]);e("PropertyPattern").bases("Pattern").build("key","pattern").field("key",t(e("Literal"),e("Identifier"))).field("pattern",e("Pattern"));e("ArrayPattern").bases("Pattern").build("elements").field("elements",[t(e("Pattern"),null)]);e("SwitchCase").bases("Node").build("test","consequent").field("test",t(e("Expression"),null)).field("consequent",[e("Statement")]);e("Identifier").bases("Node","Expression","Pattern").build("name").field("name",i);e("Literal").bases("Node","Expression").build("value").field("value",t(i,n,null,p,c));e("Block").bases("Printable").build("loc","value").field("value",i);e("Line").bases("Printable").build("loc","value").field("value",i)},{"../lib/shared":99,"../lib/types":100}],89:[function(i,o,l){i("./core");var n=i("../lib/types");var e=n.Type.def;var r=n.Type.or;var a=n.builtInTypes;var t=a.string;var s=a.boolean;e("XMLDefaultDeclaration").bases("Declaration").field("namespace",e("Expression"));e("XMLAnyName").bases("Expression");e("XMLQualifiedIdentifier").bases("Expression").field("left",r(e("Identifier"),e("XMLAnyName"))).field("right",r(e("Identifier"),e("Expression"))).field("computed",s);e("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",r(e("Identifier"),e("Expression"))).field("computed",s);e("XMLAttributeSelector").bases("Expression").field("attribute",e("Expression"));e("XMLFilterExpression").bases("Expression").field("left",e("Expression")).field("right",e("Expression"));e("XMLElement").bases("XML","Expression").field("contents",[e("XML")]);e("XMLList").bases("XML","Expression").field("contents",[e("XML")]);e("XML").bases("Node");e("XMLEscape").bases("XML").field("expression",e("Expression"));e("XMLText").bases("XML").field("text",t);e("XMLStartTag").bases("XML").field("contents",[e("XML")]);e("XMLEndTag").bases("XML").field("contents",[e("XML")]);e("XMLPointTag").bases("XML").field("contents",[e("XML")]);e("XMLName").bases("XML").field("contents",r(t,[e("XML")]));e("XMLAttribute").bases("XML").field("value",t);e("XMLCdata").bases("XML").field("contents",t);e("XMLComment").bases("XML").field("contents",t);e("XMLProcessingInstruction").bases("XML").field("target",t).field("contents",r(t,null))},{"../lib/types":100,"./core":88}],90:[function(o,f,c){o("./core");var a=o("../lib/types");var e=a.Type.def;var t=a.Type.or;var i=a.builtInTypes;var n=i.boolean;var u=i.object;var s=i.string;var r=o("../lib/shared").defaults;e("Function").field("generator",n,r["false"]).field("expression",n,r["false"]).field("defaults",[t(e("Expression"),null)],r.emptyArray).field("rest",t(e("Identifier"),null),r["null"]);e("FunctionDeclaration").build("id","params","body","generator","expression");e("FunctionExpression").build("id","params","body","generator","expression");e("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,r["null"]).field("generator",false);e("YieldExpression").bases("Expression").build("argument","delegate").field("argument",t(e("Expression"),null)).field("delegate",n,r["false"]);e("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",e("Expression")).field("blocks",[e("ComprehensionBlock")]).field("filter",t(e("Expression"),null));e("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",e("Expression")).field("blocks",[e("ComprehensionBlock")]).field("filter",t(e("Expression"),null));e("ComprehensionBlock").bases("Node").build("left","right","each").field("left",e("Pattern")).field("right",e("Expression")).field("each",n);e("ModuleSpecifier").bases("Literal").build("value").field("value",s);e("Property").field("key",t(e("Literal"),e("Identifier"),e("Expression"))).field("method",n,r["false"]).field("shorthand",n,r["false"]).field("computed",n,r["false"]);e("PropertyPattern").field("key",t(e("Literal"),e("Identifier"),e("Expression"))).field("computed",n,r["false"]);e("MethodDefinition").bases("Declaration").build("kind","key","value").field("kind",t("init","get","set","")).field("key",t(e("Literal"),e("Identifier"),e("Expression"))).field("value",e("Function")).field("computed",n,r["false"]);e("SpreadElement").bases("Node").build("argument").field("argument",e("Expression"));e("ArrayExpression").field("elements",[t(e("Expression"),e("SpreadElement"),null)]);e("NewExpression").field("arguments",[t(e("Expression"),e("SpreadElement"))]);e("CallExpression").field("arguments",[t(e("Expression"),e("SpreadElement"))]);e("SpreadElementPattern").bases("Pattern").build("argument").field("argument",e("Pattern"));var l=t(e("MethodDefinition"),e("VariableDeclarator"),e("ClassPropertyDefinition"),e("ClassProperty"));e("ClassProperty").bases("Declaration").build("key").field("key",t(e("Literal"),e("Identifier"),e("Expression"))).field("computed",n,r["false"]);e("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",l);e("ClassBody").bases("Declaration").build("body").field("body",[l]);e("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",e("Identifier")).field("body",e("ClassBody")).field("superClass",t(e("Expression"),null),r["null"]);e("ClassExpression").bases("Expression").build("id","body","superClass").field("id",t(e("Identifier"),null),r["null"]).field("body",e("ClassBody")).field("superClass",t(e("Expression"),null),r["null"]).field("implements",[e("ClassImplements")],r.emptyArray);e("ClassImplements").bases("Node").build("id").field("id",e("Identifier")).field("superClass",t(e("Expression"),null),r["null"]);e("Specifier").bases("Node");e("NamedSpecifier").bases("Specifier").field("id",e("Identifier")).field("name",t(e("Identifier"),null),r["null"]);e("ExportSpecifier").bases("NamedSpecifier").build("id","name");e("ExportBatchSpecifier").bases("Specifier").build();e("ImportSpecifier").bases("NamedSpecifier").build("id","name");e("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",e("Identifier"));e("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",e("Identifier"));e("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",n).field("declaration",t(e("Declaration"),e("Expression"),null)).field("specifiers",[t(e("ExportSpecifier"),e("ExportBatchSpecifier"))],r.emptyArray).field("source",t(e("ModuleSpecifier"),null),r["null"]);e("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[t(e("ImportSpecifier"),e("ImportNamespaceSpecifier"),e("ImportDefaultSpecifier"))],r.emptyArray).field("source",e("ModuleSpecifier"));e("TaggedTemplateExpression").bases("Expression").field("tag",e("Expression")).field("quasi",e("TemplateLiteral"));e("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[e("TemplateElement")]).field("expressions",[e("Expression")]);e("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:s,raw:s}).field("tail",n)},{"../lib/shared":99,"../lib/types":100,"./core":88}],91:[function(t,o,l){t("./core");var r=t("../lib/types");var e=r.Type.def;var n=r.Type.or;var s=r.builtInTypes;var i=s.boolean;var a=t("../lib/shared").defaults;e("Function").field("async",i,a["false"]);e("SpreadProperty").bases("Node").build("argument").field("argument",e("Expression"));e("ObjectExpression").field("properties",[n(e("Property"),e("SpreadProperty"))]);e("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",e("Pattern"));e("ObjectPattern").field("properties",[n(e("PropertyPattern"),e("SpreadPropertyPattern"))]);e("AwaitExpression").bases("Expression").build("argument","all").field("argument",n(e("Expression"),null)).field("all",i,a["false"])},{"../lib/shared":99,"../lib/types":100,"./core":88}],92:[function(a,f,c){a("./core");var o=a("../lib/types");var e=o.Type.def;var t=o.Type.or;var u=o.builtInTypes;var i=u.string;var n=u.boolean;var r=a("../lib/shared").defaults;e("XJSAttribute").bases("Node").build("name","value").field("name",t(e("XJSIdentifier"),e("XJSNamespacedName"))).field("value",t(e("Literal"),e("XJSExpressionContainer"),null),r["null"]);e("XJSIdentifier").bases("Node").build("name").field("name",i);e("XJSNamespacedName").bases("Node").build("namespace","name").field("namespace",e("XJSIdentifier")).field("name",e("XJSIdentifier"));e("XJSMemberExpression").bases("MemberExpression").build("object","property").field("object",t(e("XJSIdentifier"),e("XJSMemberExpression"))).field("property",e("XJSIdentifier")).field("computed",n,r.false);var s=t(e("XJSIdentifier"),e("XJSNamespacedName"),e("XJSMemberExpression"));e("XJSSpreadAttribute").bases("Node").build("argument").field("argument",e("Expression"));var l=[t(e("XJSAttribute"),e("XJSSpreadAttribute"))];e("XJSExpressionContainer").bases("Expression").build("expression").field("expression",e("Expression"));e("XJSElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",e("XJSOpeningElement")).field("closingElement",t(e("XJSClosingElement"),null),r["null"]).field("children",[t(e("XJSElement"),e("XJSExpressionContainer"),e("XJSText"),e("Literal"))],r.emptyArray).field("name",s,function(){return this.openingElement.name}).field("selfClosing",n,function(){return this.openingElement.selfClosing}).field("attributes",l,function(){return this.openingElement.attributes});e("XJSOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",s).field("attributes",l,r.emptyArray).field("selfClosing",n,r["false"]);e("XJSClosingElement").bases("Node").build("name").field("name",s);e("XJSText").bases("Literal").build("value").field("value",i);e("XJSEmptyExpression").bases("Expression").build();e("Type").bases("Node");e("AnyTypeAnnotation").bases("Type");e("VoidTypeAnnotation").bases("Type");e("NumberTypeAnnotation").bases("Type");e("StringTypeAnnotation").bases("Type");e("StringLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",i).field("raw",i);e("BooleanTypeAnnotation").bases("Type");e("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation",e("Type"));e("NullableTypeAnnotation").bases("Type").build("typeAnnotation").field("typeAnnotation",e("Type"));e("FunctionTypeAnnotation").bases("Type").build("params","returnType","rest","typeParameters").field("params",[e("FunctionTypeParam")]).field("returnType",e("Type")).field("rest",t(e("FunctionTypeParam"),null)).field("typeParameters",t(e("TypeParameterDeclaration"),null));e("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",e("Identifier")).field("typeAnnotation",e("Type")).field("optional",n);e("ObjectTypeAnnotation").bases("Type").build("properties").field("properties",[e("ObjectTypeProperty")]).field("indexers",[e("ObjectTypeIndexer")],r.emptyArray).field("callProperties",[e("ObjectTypeCallProperty")],r.emptyArray);e("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",t(e("Literal"),e("Identifier"))).field("value",e("Type")).field("optional",n);e("ObjectTypeIndexer").bases("Node").build("id","key","value").field("id",e("Identifier")).field("key",e("Type")).field("value",e("Type"));e("ObjectTypeCallProperty").bases("Node").build("value").field("value",e("FunctionTypeAnnotation")).field("static",n,false);e("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",t(e("Identifier"),e("QualifiedTypeIdentifier"))).field("id",e("Identifier"));e("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",t(e("Identifier"),e("QualifiedTypeIdentifier"))).field("typeParameters",t(e("TypeParameterInstantiation"),null));e("MemberTypeAnnotation").bases("Type").build("object","property").field("object",e("Identifier")).field("property",t(e("MemberTypeAnnotation"),e("GenericTypeAnnotation")));e("UnionTypeAnnotation").bases("Type").build("types").field("types",[e("Type")]);e("IntersectionTypeAnnotation").bases("Type").build("types").field("types",[e("Type")]);e("TypeofTypeAnnotation").bases("Type").build("argument").field("argument",e("Type"));e("Identifier").field("typeAnnotation",t(e("TypeAnnotation"),null),r["null"]);e("TypeParameterDeclaration").bases("Node").build("params").field("params",[e("Identifier")]);e("TypeParameterInstantiation").bases("Node").build("params").field("params",[e("Type")]);e("Function").field("returnType",t(e("TypeAnnotation"),null),r["null"]).field("typeParameters",t(e("TypeParameterDeclaration"),null),r["null"]);e("ClassProperty").build("key","typeAnnotation").field("typeAnnotation",e("TypeAnnotation")).field("static",n,false);e("ClassImplements").field("typeParameters",t(e("TypeParameterInstantiation"),null),r["null"]);e("InterfaceDeclaration").bases("Statement").build("id","body","extends").field("id",e("Identifier")).field("typeParameters",t(e("TypeParameterDeclaration"),null),r["null"]).field("body",e("ObjectTypeAnnotation")).field("extends",[e("InterfaceExtends")]);e("InterfaceExtends").bases("Node").build("id").field("id",e("Identifier")).field("typeParameters",t(e("TypeParameterInstantiation"),null));e("TypeAlias").bases("Statement").build("id","typeParameters","right").field("id",e("Identifier")).field("typeParameters",t(e("TypeParameterDeclaration"),null)).field("right",e("Type"));e("TupleTypeAnnotation").bases("Type").build("types").field("types",[e("Type")]);e("DeclareVariable").bases("Statement").build("id").field("id",e("Identifier"));e("DeclareFunction").bases("Statement").build("id").field("id",e("Identifier"));e("DeclareClass").bases("InterfaceDeclaration").build("id");e("DeclareModule").bases("Statement").build("id","body").field("id",t(e("Identifier"),e("Literal"))).field("body",e("BlockStatement"))},{"../lib/shared":99,"../lib/types":100,"./core":88}],93:[function(t,a,s){t("./core");var r=t("../lib/types");var e=r.Type.def;var i=r.Type.or;var n=t("../lib/shared").geq;e("ForOfStatement").bases("Statement").build("left","right","body").field("left",i(e("VariableDeclaration"),e("Expression"))).field("right",e("Expression")).field("body",e("Statement"));e("LetStatement").bases("Statement").build("head","body").field("head",[e("VariableDeclarator")]).field("body",e("Statement"));e("LetExpression").bases("Expression").build("head","body").field("head",[e("VariableDeclarator")]).field("body",e("Expression"));e("GraphExpression").bases("Expression").build("index","expression").field("index",n(0)).field("expression",e("Literal"));e("GraphIndexExpression").bases("Expression").build("index").field("index",n(0))},{"../lib/shared":99,"../lib/types":100,"./core":88}],94:[function(o,p,y){var t=o("assert");var e=o("../main");var l=e.getFieldNames;var s=e.getFieldValue;var r=e.builtInTypes.array;var n=e.builtInTypes.object;var u=e.builtInTypes.Date;var f=e.builtInTypes.RegExp;var c=Object.prototype.hasOwnProperty;function a(t,n,e){if(r.check(e)){e.length=0}else{e=null}return i(t,n,e)}a.assert=function(r,n){var e=[];if(!a(r,n,e)){if(e.length===0){t.strictEqual(r,n)}else{t.ok(false,"Nodes differ in the following path: "+e.map(d).join(""))}}};function d(e){if(/[_$a-z][_$a-z0-9]*/i.test(e)){return"."+e}return"["+JSON.stringify(e)+"]"}function i(e,t,i){if(e===t){return true}if(r.check(e)){return m(e,t,i)}if(n.check(e)){return h(e,t,i)}if(u.check(e)){return u.check(t)&&+e===+t}if(f.check(e)){return f.check(t)&&(e.source===t.source&&e.global===t.global&&e.multiline===t.multiline&&e.ignoreCase===t.ignoreCase)}return e==t}function m(a,s,n){r.assert(a);var o=a.length;if(!r.check(s)||s.length!==o){if(n){n.push("length")}return false}for(var e=0;e<o;++e){if(n){n.push(e)}if(e in a!==e in s){return false}if(!i(a[e],s[e],n)){return false}if(n){t.strictEqual(n.pop(),e)}}return true}function h(o,f,r){n.assert(o);if(!n.check(f)){return false}if(o.type!==f.type){if(r){r.push("type")}return false}var d=l(o);var p=d.length;var m=l(f);var h=m.length;if(p===h){for(var e=0;e<p;++e){var a=d[e];var y=s(o,a);var v=s(f,a);if(r){r.push(a)}if(!i(y,v,r)){return false}if(r){t.strictEqual(r.pop(),a)}}return true}if(!r){return false}var u=Object.create(null);for(e=0;e<p;++e){u[d[e]]=true}for(e=0;e<h;++e){a=m[e];if(!c.call(u,a)){r.push(a);return false}delete u[a]}for(a in u){r.push(a);break}return false}p.exports=a},{"../main":101,assert:103}],95:[function(i,c,b){var t=i("assert");var n=i("./types");var e=n.namedTypes;var f=n.builders;var m=n.builtInTypes.number;var p=n.builtInTypes.array;var l=i("./path");var u=i("./scope");function a(e,r,n){t.ok(this instanceof a);l.call(this,e,r,n)}i("util").inherits(a,l);var r=a.prototype;Object.defineProperties(r,{node:{get:function(){Object.defineProperty(this,"node",{configurable:true,value:this._computeNode()});return this.node}},parent:{get:function(){Object.defineProperty(this,"parent",{configurable:true,value:this._computeParent()});return this.parent}},scope:{get:function(){Object.defineProperty(this,"scope",{configurable:true,value:this._computeScope()});
return this.scope}}});r.replace=function(){delete this.node;delete this.parent;delete this.scope;return l.prototype.replace.apply(this,arguments)};r.prune=function(){var e=this.parent;this.replace();return y(e)};r._computeNode=function(){var t=this.value;if(e.Node.check(t)){return t}var r=this.parentPath;return r&&r.node||null};r._computeParent=function(){var r=this.value;var t=this.parentPath;if(!e.Node.check(r)){while(t&&!e.Node.check(t.value)){t=t.parentPath}if(t){t=t.parentPath}}while(t&&!e.Node.check(t.value)){t=t.parentPath}return t||null};r._computeScope=function(){var r=this.value;var n=this.parentPath;var t=n&&n.scope;if(e.Node.check(r)&&u.isEstablishedBy(r)){t=new u(this,t)}return t||null};r.getValueProperty=function(e){return n.getFieldValue(this.value,e)};r.needsParens=function(l){var i=this.parentPath;if(!i){return false}var n=this.value;if(!e.Expression.check(n)){return false}if(n.type==="Identifier"){return false}while(!e.Node.check(i.value)){i=i.parentPath;if(!i){return false}}var r=i.value;switch(n.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return r.type==="MemberExpression"&&this.name==="object"&&r.object===n;case"BinaryExpression":case"LogicalExpression":switch(r.type){case"CallExpression":return this.name==="callee"&&r.callee===n;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return true;case"MemberExpression":return this.name==="object"&&r.object===n;case"BinaryExpression":case"LogicalExpression":var u=r.operator;var i=o[u];var f=n.operator;var a=o[f];if(i>a){return true}if(i===a&&this.name==="right"){t.strictEqual(r.right,n);return true}default:return false}case"SequenceExpression":switch(r.type){case"ForStatement":return false;case"ExpressionStatement":return this.name!=="expression";default:return true}case"YieldExpression":switch(r.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return true;default:return false}case"Literal":return r.type==="MemberExpression"&&m.check(n.value)&&this.name==="object"&&r.object===n;case"AssignmentExpression":case"ConditionalExpression":switch(r.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return true;case"CallExpression":return this.name==="callee"&&r.callee===n;case"ConditionalExpression":return this.name==="test"&&r.test===n;case"MemberExpression":return this.name==="object"&&r.object===n;default:return false}default:if(r.type==="NewExpression"&&this.name==="callee"&&r.callee===n){return s(n)}}if(l!==true&&!this.canBeFirstInStatement()&&this.firstInStatement())return true;return false};function d(t){return e.BinaryExpression.check(t)||e.LogicalExpression.check(t)}function g(t){return e.UnaryExpression.check(t)||e.SpreadElement&&e.SpreadElement.check(t)||e.SpreadProperty&&e.SpreadProperty.check(t)}var o={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(e,t){e.forEach(function(e){o[e]=t})});function s(t){if(e.CallExpression.check(t)){return true}if(p.check(t)){return t.some(s)}if(e.Node.check(t)){return n.someField(t,function(t,e){return s(e)})}return false}r.canBeFirstInStatement=function(){var t=this.node;return!e.FunctionExpression.check(t)&&!e.ObjectExpression.check(t)};r.firstInStatement=function(){return h(this)};function h(n){for(var i,r;n.parent;n=n.parent){i=n.node;r=n.parent.node;if(e.BlockStatement.check(r)&&n.parent.name==="body"&&n.name===0){t.strictEqual(r.body[0],i);return true}if(e.ExpressionStatement.check(r)&&n.name==="expression"){t.strictEqual(r.expression,i);return true}if(e.SequenceExpression.check(r)&&n.parent.name==="expressions"&&n.name===0){t.strictEqual(r.expressions[0],i);continue}if(e.CallExpression.check(r)&&n.name==="callee"){t.strictEqual(r.callee,i);continue}if(e.MemberExpression.check(r)&&n.name==="object"){t.strictEqual(r.object,i);continue}if(e.ConditionalExpression.check(r)&&n.name==="test"){t.strictEqual(r.test,i);continue}if(d(r)&&n.name==="left"){t.strictEqual(r.left,i);continue}if(e.UnaryExpression.check(r)&&!r.prefix&&n.name==="argument"){t.strictEqual(r.argument,i);continue}return false}return true}function y(t){if(e.VariableDeclaration.check(t.node)){var r=t.get("declarations").value;if(!r||r.length===0){return t.prune()}}else if(e.ExpressionStatement.check(t.node)){if(!t.get("expression").value){return t.prune()}}else if(e.IfStatement.check(t.node)){v(t)}return t}function v(t){var r=t.get("test").value;var n=t.get("alternate").value;var i=t.get("consequent").value;if(!i&&!n){var s=f.expressionStatement(r);t.replace(s)}else if(!i&&n){var a=f.unaryExpression("!",r,true);if(e.UnaryExpression.check(r)&&r.operator==="!"){a=r.argument}t.get("test").replace(a);t.get("consequent").replace(n);t.get("alternate").replace()}}c.exports=a},{"./path":97,"./scope":98,"./types":100,assert:103,util:127}],96:[function(o,m,b){var e=o("assert");var i=o("./types");var r=o("./node-path");var g=i.namedTypes.Node;var p=i.builtInTypes.array;var u=i.builtInTypes.object;var l=i.builtInTypes.function;var f=Object.prototype.hasOwnProperty;var y;function t(){e.ok(this instanceof t);this._reusableContextStack=[];this._methodNameTable=d(this);this.Context=v(this);this._visiting=false;this._changeReported=false}function d(n){var t=Object.create(null);for(var e in n){if(/^visit[A-Z]/.test(e)){t[e.slice("visit".length)]=true}}var a=i.computeSupertypeLookupTable(t);var s=Object.create(null);var t=Object.keys(a);var u=t.length;for(var r=0;r<u;++r){var o=t[r];e="visit"+a[o];if(l.check(n[e])){s[o]=e}}return s}t.fromMethodsObject=function E(i){if(i instanceof t){return i}if(!u.check(i)){return new t}function r(){e.ok(this instanceof r);t.call(this)}var a=r.prototype=Object.create(n);a.constructor=r;s(a,i);s(r,t);l.assert(r.fromMethodsObject);l.assert(r.visit);return new r};function s(r,e){for(var t in e){if(f.call(e,t)){r[t]=e[t]}}return r}t.visit=function x(e,a){var n=t.fromMethodsObject(a);if(e instanceof r){n.visit(e);return e.value}var i=new r({root:e});n.visit(i.get("root"));return i.value.root};var n=t.prototype;var h=["Recursively calling visitor.visit(path) resets visitor state.","Try this.visit(path) or this.traverse(path) instead."].join(" ");n.visit=function(t){e.ok(!this._visiting,h);this._visiting=true;this._changeReported=false;this.reset.apply(this,arguments);try{return this.visitWithoutReset(t)}finally{this._visiting=false}};n.reset=function(e){};n.visitWithoutReset=function(t){if(this instanceof this.Context){return this.visitor.visitWithoutReset(t)}e.ok(t instanceof r);var n=t.value;var i=g.check(n)&&this._methodNameTable[n.type];if(i){var a=this.acquireContext(t);try{a.invokeVisitorMethod(i)}finally{this.releaseContext(a)}}else{c(t,this)}};function c(s,o){e.ok(s instanceof r);e.ok(o instanceof t);var n=s.value;if(p.check(n)){s.each(o.visitWithoutReset,o)}else if(!u.check(n)){}else{var c=i.getFieldNames(n);var d=c.length;var m=[];for(var a=0;a<d;++a){var l=c[a];if(!f.call(n,l)){n[l]=i.getFieldValue(n,l)}m.push(s.get(l))}for(var a=0;a<d;++a){o.visitWithoutReset(m[a])}}}n.acquireContext=function(e){if(this._reusableContextStack.length===0){return new this.Context(e)}return this._reusableContextStack.pop().reset(e)};n.releaseContext=function(t){e.ok(t instanceof this.Context);this._reusableContextStack.push(t);t.currentPath=null};n.reportChanged=function(){this._changeReported=true};n.wasChangeReported=function(){return this._changeReported};function v(i){function n(a){e.ok(this instanceof n);e.ok(this instanceof t);e.ok(a instanceof r);Object.defineProperty(this,"visitor",{value:i,writable:false,enumerable:true,configurable:false});this.currentPath=a;this.needToCallTraverse=true;Object.seal(this)}e.ok(i instanceof t);var o=n.prototype=Object.create(i);o.constructor=n;s(o,a);return n}var a=Object.create(null);a.reset=function S(t){e.ok(this instanceof this.Context);e.ok(t instanceof r);this.currentPath=t;this.needToCallTraverse=true;return this};a.invokeVisitorMethod=function w(n){e.ok(this instanceof this.Context);e.ok(this.currentPath instanceof r);var t=this.visitor[n].call(this,this.currentPath);if(t===false){this.needToCallTraverse=false}else if(t!==y){this.currentPath=this.currentPath.replace(t)[0];if(this.needToCallTraverse){this.traverse(this.currentPath)}}e.strictEqual(this.needToCallTraverse,false,"Must either call this.traverse or return false in "+n)};a.traverse=function k(n,i){e.ok(this instanceof this.Context);e.ok(n instanceof r);e.ok(this.currentPath instanceof r);this.needToCallTraverse=false;c(n,t.fromMethodsObject(i||this.visitor))};a.visit=function I(n,i){e.ok(this instanceof this.Context);e.ok(n instanceof r);e.ok(this.currentPath instanceof r);this.needToCallTraverse=false;t.fromMethodsObject(i||this.visitor).visitWithoutReset(n)};a.reportChanged=function C(){this.visitor.reportChanged()};m.exports=t},{"./node-path":95,"./types":100,assert:103}],97:[function(f,p,g){var t=f("assert");var m=Object.prototype;var s=m.hasOwnProperty;var u=f("./types");var n=u.builtInTypes.array;var c=u.builtInTypes.number;var l=Array.prototype;var v=l.slice;var y=l.map;function i(n,e,r){t.ok(this instanceof i);if(e){t.ok(e instanceof i)}else{e=null;r=null}this.value=n;this.parentPath=e;this.name=r;this.__childCache=null}var e=i.prototype;function r(e){return e.__childCache||(e.__childCache=Object.create(null))}function d(t,e){var n=r(t);var a=t.getValueProperty(e);var i=n[e];if(!s.call(n,e)||i.value!==a){i=n[e]=new t.constructor(a,t,e)}return i}e.getValueProperty=function b(e){return this.value[e]};e.get=function E(i){var e=this;var r=arguments;var n=r.length;for(var t=0;t<n;++t){e=d(e,r[t])}return e};e.each=function x(i,t){var r=[];var n=this.value.length;var e=0;for(var e=0;e<n;++e){if(s.call(this.value,e)){r[e]=this.get(e)}}t=t||this;for(e=0;e<n;++e){if(s.call(r,e)){i.call(t,r[e])}}};e.map=function S(t,r){var e=[];this.each(function(r){e.push(t.call(this,r))},r);return e};e.filter=function w(t,r){var e=[];this.each(function(r){if(t.call(this,r)){e.push(r)}},r);return e};function o(){}function a(a,h,e,l){n.assert(a.value);if(h===0){return o}var u=a.value.length;if(u<1){return o}var y=arguments.length;if(y===2){e=0;l=u}else if(y===3){e=Math.max(e,0);l=u}else{e=Math.max(e,0);l=Math.min(l,u)}c.assert(e);c.assert(l);var f=Object.create(null);var p=r(a);for(var i=e;i<l;++i){if(s.call(a.value,i)){var d=a.get(i);t.strictEqual(d.name,i);var m=i+h;d.name=m;f[m]=d;delete p[i]}}delete p.length;return function(){for(var e in f){var r=f[e];t.strictEqual(r.name,+e);p[e]=r;a.value[e]=r.value}}}e.shift=function k(){var e=a(this,-1);var t=this.value.shift();e();return t};e.unshift=function I(r){var e=a(this,arguments.length);var t=this.value.unshift.apply(this.value,arguments);e();return t};e.push=function C(e){n.assert(this.value);delete r(this).length;return this.value.push.apply(this.value,arguments)};e.pop=function A(){n.assert(this.value);var e=r(this);delete e[this.value.length-1];delete e.length;return this.value.pop()};e.insertAt=function T(e,i){var r=arguments.length;var n=a(this,r-1,e);if(n===o){return this}e=Math.max(e,0);for(var t=1;t<r;++t){this.value[e+t-1]=arguments[t]}n();return this};e.insertBefore=function P(i){var t=this.parentPath;var n=arguments.length;var r=[this.name];for(var e=0;e<n;++e){r.push(arguments[e])}return t.insertAt.apply(t,r)};e.insertAfter=function L(i){var t=this.parentPath;var n=arguments.length;var r=[this.name+1];for(var e=0;e<n;++e){r.push(arguments[e])}return t.insertAt.apply(t,r)};function h(e){t.ok(e instanceof i);var s=e.parentPath;if(!s){return e}var a=s.value;var o=r(s);if(a[e.name]===e.value){o[e.name]=e}else if(n.check(a)){var l=a.indexOf(e.value);if(l>=0){o[e.name=l]=e}}else{a[e.name]=e.value;o[e.name]=e}t.strictEqual(a[e.name],e.value);t.strictEqual(e.parentPath.get(e.name),e);return e}e.replace=function _(o){var l=[];var e=this.parentPath.value;var p=r(this.parentPath);var i=arguments.length;h(this);if(n.check(e)){var f=e.length;var c=a(this.parentPath,i-1,this.name+1);var u=[this.name,1];for(var s=0;s<i;++s){u.push(arguments[s])}var d=e.splice.apply(e,u);t.strictEqual(d[0],this.value);t.strictEqual(e.length,f-1+i);c();if(i===0){delete this.value;delete p[this.name];this.__childCache=null}else{t.strictEqual(e[this.name],o);if(this.value!==o){this.value=o;this.__childCache=null}for(s=0;s<i;++s){l.push(this.parentPath.get(this.name+s))}t.strictEqual(l[0],this)}}else if(i===1){if(this.value!==o){this.__childCache=null}this.value=e[this.name]=o;l.push(this)}else if(i===0){delete e[this.name];delete this.value;this.__childCache=null}else{t.ok(false,"Could not replace path")}return l};p.exports=i},{"./types":100,assert:103}],98:[function(l,m,b){var i=l("assert");var n=l("./types");var d=n.Type;var e=n.namedTypes;var v=e.Node;var p=e.Expression;var h=n.builtInTypes.array;var f=Object.prototype.hasOwnProperty;var c=n.builders;function a(t,e){i.ok(this instanceof a);i.ok(t instanceof l("./node-path"));o.assert(t.value);var r;if(e){i.ok(e instanceof a);r=e.depth+1}else{e=null;r=0}Object.defineProperties(this,{path:{value:t},node:{value:t.value},isGlobal:{value:!e,enumerable:true},depth:{value:r},parent:{value:e},bindings:{value:{}}})}var y=[e.Program,e.Function,e.CatchClause];var o=d.or.apply(d,y);a.isEstablishedBy=function(e){return o.check(e)};var r=a.prototype;r.didScan=false;r.declares=function(e){this.scan();return f.call(this.bindings,e)};r.declareTemporary=function(e){if(e){i.ok(/^[a-z$_]/i.test(e),e)}else{e="t$"}e+=this.depth.toString(36)+"$";this.scan();var t=0;while(this.declares(e+t)){++t}var r=e+t;return this.bindings[r]=n.builders.identifier(r)};r.injectTemporary=function(t,n){t||(t=this.declareTemporary());var r=this.path.get("body");if(e.BlockStatement.check(r.value)){r=r.get("body")}r.unshift(c.variableDeclaration("var",[c.variableDeclarator(t,n||null)]));return t};r.scan=function(e){if(e||!this.didScan){for(var t in this.bindings){delete this.bindings[t]}g(this.path,this.bindings);this.didScan=true}};r.getBindings=function(){this.scan();return this.bindings};function g(r,n){var i=r.value;o.assert(i);if(e.CatchClause.check(i)){t(r.get("param"),n)}else{u(r,n)}}function u(r,o){var a=r.value;if(r.parent&&e.FunctionExpression.check(r.parent.node)&&r.parent.node.id){t(r.parent.get("id"),o)}if(!a){}else if(h.check(a)){r.each(function(e){s(e,o)})}else if(e.Function.check(a)){r.get("params").each(function(e){t(e,o)});s(r.get("body"),o)}else if(e.VariableDeclarator.check(a)){t(r.get("id"),o);s(r.get("init"),o)}else if(a.type==="ImportSpecifier"||a.type==="ImportNamespaceSpecifier"||a.type==="ImportDefaultSpecifier"){t(a.name?r.get("name"):r.get("id"),o)}else if(v.check(a)&&!p.check(a)){n.eachField(a,function(t,n){var e=r.get(t);i.strictEqual(e.value,n);s(e,o)})}}function s(i,n){var r=i.value;if(!r||p.check(r)){}else if(e.FunctionDeclaration.check(r)){t(i.get("id"),n)}else if(e.ClassDeclaration&&e.ClassDeclaration.check(r)){t(i.get("id"),n)}else if(o.check(r)){if(e.CatchClause.check(r)){var a=r.param.name;var s=f.call(n,a);u(i.get("body"),n);if(!s){delete n[a]}}}else{u(i,n)}}function t(n,i){var r=n.value;e.Pattern.assert(r);if(e.Identifier.check(r)){if(f.call(i,r.name)){i[r.name].push(n)}else{i[r.name]=[n]}}else if(e.SpreadElement&&e.SpreadElement.check(r)){t(n.get("argument"),i)}}r.lookup=function(t){for(var e=this;e;e=e.parent)if(e.declares(t))break;return e};r.getGlobalScope=function(){var e=this;while(!e.isGlobal)e=e.parent;return e};m.exports=a},{"./node-path":95,"./types":100,assert:103}],99:[function(a,o,t){var n=a("../lib/types");var r=n.Type;var e=n.builtInTypes;var i=e.number;t.geq=function(e){return new r(function(t){return i.check(t)&&t>=e},i+" >= "+e)};t.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return false},"true":function(){return true},undefined:function(){}};var s=r.or(e.string,e.number,e.boolean,e.null,e.undefined);t.isPrimitive=new r(function(e){if(e===null)return true;var t=typeof e;return!(t==="object"||t==="function")},s.toString())},{"../lib/types":100}],100:[function(L,N,n){var e=L("assert");var x=Array.prototype;var P=x.slice;var F=x.map;var D=x.forEach;var I=Object.prototype;var l=I.toString;var g=l.call(function(){});var j=l.call("");var i=I.hasOwnProperty;function t(n,i){var r=this;e.ok(r instanceof t,r);e.strictEqual(l.call(n),g,n+" is not a function");var a=l.call(i);e.ok(a===g||a===j,i+" is neither a function nor a string");Object.defineProperties(r,{name:{value:i},check:{value:function(t,e){var i=n.call(r,t,e);if(!i&&e&&l.call(e)===g)e(r,t);return i}}})}var S=t.prototype;n.Type=t;S.assert=function(t,r){if(!this.check(t,r)){var n=h(t);e.ok(false,n+" does not match type "+this);return false}return true};function h(e){if(u.check(e))return"{"+Object.keys(e).map(function(t){return t+": "+e[t]}).join(", ")+"}";if(p.check(e))return"["+e.map(h).join(", ")+"]";return JSON.stringify(e)}S.toString=function(){var e=this.name;if(f.check(e))return e;if(c.check(e))return e.call(this)+"";return e+" type"};var y={};n.builtInTypes=y;function a(r,e){var n=l.call(r);Object.defineProperty(y,e,{enumerable:true,value:new t(function(e){return l.call(e)===n},e)});return y[e]}var f=a("","string");var c=a(function(){},"function");var p=a([],"array");var u=a({},"object");var B=a(/./,"RegExp");var V=a(new Date,"Date");var _=a(3,"number");var U=a(true,"boolean");var R=a(null,"null");var k=a(void 0,"undefined");function w(e,r){if(e instanceof t)return e;if(e instanceof o)return e.type;if(p.check(e))return t.fromArray(e);if(u.check(e))return t.fromObject(e);if(c.check(e))return new t(e,r);return new t(function(t){return t===e},k.check(r)?function(){return e+""}:r)}t.or=function(){var e=[];var n=arguments.length;for(var r=0;r<n;++r)e.push(w(arguments[r]));return new t(function(r,i){for(var t=0;t<n;++t)if(e[t].check(r,i))return true;return false},function(){return e.join(" | ")})};t.fromArray=function(t){e.ok(p.check(t));e.strictEqual(t.length,1,"only one element type is permitted for typed arrays");return w(t[0]).arrayOf()};S.arrayOf=function(){var e=this;return new t(function(t,r){return p.check(t)&&t.every(function(t){return e.check(t,r)})},function(){return"["+e+"]"})};t.fromObject=function(e){var r=Object.keys(e).map(function(t){return new m(t,e[t])});return new t(function(e,t){return u.check(e)&&r.every(function(r){return r.type.check(e[r.name],t)})},function(){return"{ "+r.join(", ")+" }"})};function m(r,t,n,s){var i=this;e.ok(i instanceof m);f.assert(r);t=w(t);var a={name:{value:r},type:{value:t},hidden:{value:!!s}};if(c.check(n)){a.defaultFn={value:n}}Object.defineProperties(i,a)}var C=m.prototype;C.toString=function(){return JSON.stringify(this.name)+": "+this.type};C.getValue=function(t){var e=t[this.name];if(!k.check(e))return e;if(this.defaultFn)e=this.defaultFn.call(t);return e};t.def=function(e){f.assert(e);return i.call(r,e)?r[e]:r[e]=new o(e)};var r=Object.create(null);function o(n){var r=this;e.ok(r instanceof o);Object.defineProperties(r,{typeName:{value:n},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new t(function(e,t){return r.check(e,t)},n)}})}o.fromValue=function(e){if(e&&typeof e==="object"){var t=e.type;if(typeof t==="string"&&i.call(r,t)){var n=r[t];if(n.finalized){return n}}}return null};var s=o.prototype;s.isSupertypeOf=function(t){if(t instanceof o){e.strictEqual(this.finalized,true);e.strictEqual(t.finalized,true);return i.call(t.allSupertypes,this.typeName)}else{e.ok(false,t+" is not a Def")}};n.getSupertypeNames=function(t){e.ok(i.call(r,t));var n=r[t];e.strictEqual(n.finalized,true);return n.supertypeList.slice(1)};n.computeSupertypeLookupTable=function(f){var s={};var o=Object.keys(r);var c=o.length;for(var t=0;t<c;++t){var l=o[t];var n=r[l];e.strictEqual(n.finalized,true);for(var a=0;a<n.supertypeList.length;++a){var u=n.supertypeList[a];if(i.call(f,u)){s[l]=u;break}}}return s};s.checkAllFields=function(t,n){var r=this.allFields;e.strictEqual(this.finalized,true);function i(i){var e=r[i];var a=e.type;var s=e.getValue(t);return a.check(s,n)}return u.check(t)&&Object.keys(r).every(i)};s.check=function(t,r){e.strictEqual(this.finalized,true,"prematurely checking unfinalized type "+this.typeName);if(!u.check(t))return false;var n=o.fromValue(t);if(!n){if(this.typeName==="SourceLocation"||this.typeName==="Position"){return this.checkAllFields(t,r)}return false}if(r&&n===this)return this.checkAllFields(t,r);if(!this.isSupertypeOf(n))return false;if(!r)return true;return n.checkAllFields(t,r)&&this.checkAllFields(t,false)};s.bases=function(){var t=this.baseNames;e.strictEqual(this.finalized,false);D.call(arguments,function(e){f.assert(e);if(t.indexOf(e)<0)t.push(e)});return this};Object.defineProperty(s,"buildable",{value:false});var T={};n.builders=T;var d={};n.defineMethod=function(e,t){var r=d[e];if(k.check(t)){delete d[e]}else{c.assert(t);Object.defineProperty(d,e,{enumerable:true,configurable:true,value:t})}return r};s.build=function(){var t=this;Object.defineProperty(t,"buildParams",{value:P.call(arguments),writable:false,enumerable:false,configurable:true});e.strictEqual(t.finalized,false);f.arrayOf().assert(t.buildParams);if(t.buildable){return t}t.field("type",t.typeName,function(){return t.typeName});Object.defineProperty(t,"buildable",{value:true});Object.defineProperty(T,M(t.typeName),{enumerable:true,value:function(){var n=arguments;var s=n.length;var r=Object.create(d);e.ok(t.finalized,"attempting to instantiate unfinalized type "+t.typeName);function a(a,u){if(i.call(r,a))return;var f=t.allFields;e.ok(i.call(f,a),a);var l=f[a];var c=l.type;var o;if(_.check(u)&&u<s){o=n[u]}else if(l.defaultFn){o=l.defaultFn.call(r)}else{var p="no value or default function given for field "+JSON.stringify(a)+" of "+t.typeName+"("+t.buildParams.map(function(e){return f[e]}).join(", ")+")";e.ok(false,p)}if(!c.check(o)){e.ok(false,h(o)+" does not match field "+l+" of type "+t.typeName)}r[a]=o}t.buildParams.forEach(function(e,t){a(e,t)});Object.keys(t.allFields).forEach(function(e){a(e)});e.strictEqual(r.type,t.typeName);return r}});return t};function M(e){return e.replace(/^[A-Z]+/,function(e){var t=e.length;switch(t){case 0:return"";case 1:return e.toLowerCase();default:return e.slice(0,t-1).toLowerCase()+e.charAt(t-1)}})}s.field=function(t,r,n,i){e.strictEqual(this.finalized,false);this.ownFields[t]=new m(t,r,n,i);return this};var A={};n.namedTypes=A;function b(t){var r=o.fromValue(t);if(r){return r.fieldNames.slice(0)}if("type"in t){e.ok(false,"did not recognize object of type "+JSON.stringify(t.type))}return Object.keys(t)}n.getFieldNames=b;function v(e,t){var r=o.fromValue(e);if(r){var n=r.allFields[t];if(n){return n.getValue(e)}}return e[t]}n.getFieldValue=v;n.eachField=function(e,t,r){b(e).forEach(function(r){t.call(this,r,v(e,r))},r)};n.someField=function(e,t,r){return b(e).some(function(r){return t.call(this,r,v(e,r))},r)};Object.defineProperty(s,"finalized",{value:false});s.finalize=function(){if(!this.finalized){var e=this.allFields;var n=this.allSupertypes;this.baseNames.forEach(function(i){var t=r[i];t.finalize();E(e,t.allFields);E(n,t.allSupertypes)});E(e,this.ownFields);n[this.typeName]=this;this.fieldNames.length=0;for(var t in e){if(i.call(e,t)&&!e[t].hidden){this.fieldNames.push(t)}}Object.defineProperty(A,this.typeName,{enumerable:true,value:this.type});Object.defineProperty(this,"finalized",{value:true});O(this.typeName,this.supertypeList)}};function O(n,t){t.length=0;t.push(n);var o=Object.create(null);for(var a=0;a<t.length;++a){n=t[a];var u=r[n];e.strictEqual(u.finalized,true);if(i.call(o,n)){delete t[o[n]]}o[n]=a;t.push.apply(t,u.baseNames)}for(var l=0,s=l,f=t.length;s<f;++s){if(i.call(t,s)){t[l++]=t[s]}}t.length=l}function E(e,t){Object.keys(t).forEach(function(r){e[r]=t[r]});return e}n.finalize=function(){Object.keys(r).forEach(function(e){r[e].finalize()})}},{assert:103}],101:[function(r,n,e){var t=r("./lib/types");r("./def/core");r("./def/es6");r("./def/es7");r("./def/mozilla");r("./def/e4x");r("./def/fb-harmony");t.finalize();e.Type=t.Type;e.builtInTypes=t.builtInTypes;e.namedTypes=t.namedTypes;e.builders=t.builders;e.defineMethod=t.defineMethod;e.getFieldNames=t.getFieldNames;e.getFieldValue=t.getFieldValue;e.eachField=t.eachField;e.someField=t.someField;e.getSupertypeNames=t.getSupertypeNames;e.astNodesAreEquivalent=r("./lib/equiv");e.finalize=t.finalize;e.NodePath=r("./lib/node-path");e.PathVisitor=r("./lib/path-visitor");e.visit=e.PathVisitor.visit},{"./def/core":88,"./def/e4x":89,"./def/es6":90,"./def/es7":91,"./def/fb-harmony":92,"./def/mozilla":93,"./lib/equiv":94,"./lib/node-path":95,"./lib/path-visitor":96,"./lib/types":100}],102:[function(e,t,r){},{}],103:[function(h,p,v){var t=h("util/");var n=Array.prototype.slice;var d=Object.prototype.hasOwnProperty;var e=p.exports=l;e.AssertionError=function g(e){this.name="AssertionError";this.actual=e.actual;this.expected=e.expected;this.operator=e.operator;if(e.message){this.message=e.message;this.generatedMessage=false}else{this.message=y(this);this.generatedMessage=true}var n=e.stackStartFunction||r;if(Error.captureStackTrace){Error.captureStackTrace(this,n)}else{var i=new Error;if(i.stack){var t=i.stack;var s=n.name;var a=t.indexOf("\n"+s);if(a>=0){var o=t.indexOf("\n",a+1);t=t.substring(o+1)}this.stack=t}}};t.inherits(e.AssertionError,Error);function u(r,e){if(t.isUndefined(e)){return""+e}if(t.isNumber(e)&&(isNaN(e)||!isFinite(e))){return e.toString()}if(t.isFunction(e)||t.isRegExp(e)){return e.toString()}return e}function a(e,r){if(t.isString(e)){return e.length<r?e:e.slice(0,r)}else{return e}}function y(e){return a(JSON.stringify(e.actual,u),128)+" "+e.operator+" "+a(JSON.stringify(e.expected,u),128)}function r(t,r,n,i,a){throw new e.AssertionError({message:n,actual:t,expected:r,operator:i,stackStartFunction:a})}e.fail=r;function l(t,n){if(!t)r(t,true,n,"==",e.ok)}e.ok=l;e.equal=function b(t,n,i){if(t!=n)r(t,n,i,"==",e.equal)};e.notEqual=function E(t,n,i){if(t==n){r(t,n,i,"!=",e.notEqual)}};e.deepEqual=function x(t,n,a){if(!i(t,n)){r(t,n,a,"deepEqual",e.deepEqual)}};function i(e,r){if(e===r){return true}else if(t.isBuffer(e)&&t.isBuffer(r)){if(e.length!=r.length)return false;for(var n=0;n<e.length;n++){if(e[n]!==r[n])return false}return true}else if(t.isDate(e)&&t.isDate(r)){return e.getTime()===r.getTime()}else if(t.isRegExp(e)&&t.isRegExp(r)){return e.source===r.source&&e.global===r.global&&e.multiline===r.multiline&&e.lastIndex===r.lastIndex&&e.ignoreCase===r.ignoreCase}else if(!t.isObject(e)&&!t.isObject(r)){return e==r}else{return m(e,r)}}function f(e){return Object.prototype.toString.call(e)=="[object Arguments]"}function m(r,a){if(t.isNullOrUndefined(r)||t.isNullOrUndefined(a))return false;if(r.prototype!==a.prototype)return false;if(f(r)){if(!f(a)){return false}r=n.call(r);a=n.call(a);return i(r,a)}try{var s=o(r),l=o(a),u,e}catch(c){return false}if(s.length!=l.length)return false;s.sort();l.sort();for(e=s.length-1;e>=0;e--){if(s[e]!=l[e])return false}for(e=s.length-1;e>=0;e--){u=s[e];if(!i(r[u],a[u]))return false}return true}e.notDeepEqual=function S(t,n,a){if(i(t,n)){r(t,n,a,"notDeepEqual",e.notDeepEqual)}};e.strictEqual=function w(t,n,i){if(t!==n){r(t,n,i,"===",e.strictEqual)}};e.notStrictEqual=function k(t,n,i){if(t===n){r(t,n,i,"!==",e.notStrictEqual)}};function c(t,e){if(!t||!e){return false}if(Object.prototype.toString.call(e)=="[object RegExp]"){return e.test(t)}else if(t instanceof e){return true}else if(e.call({},t)===true){return true}return false}function s(a,s,e,i){var n;if(t.isString(e)){i=e;e=null}try{s()}catch(o){n=o}i=(e&&e.name?" ("+e.name+").":".")+(i?" "+i:".");if(a&&!n){r(n,e,"Missing expected exception"+i)}if(!a&&c(n,e)){r(n,e,"Got unwanted exception"+i)}if(a&&n&&e&&!c(n,e)||!a&&n){throw n}}e.throws=function(e,t,r){s.apply(this,[true].concat(n.call(arguments)))};e.doesNotThrow=function(e,t){s.apply(this,[false].concat(n.call(arguments)))};e.ifError=function(e){if(e){throw e}};var o=Object.keys||function(e){var t=[];for(var r in e){if(d.call(e,r))t.push(r)}return t}},{"util/":127}],104:[function(p,F,s){var c=p("base64-js");var i=p("ieee754");var f=p("is-array");s.Buffer=e;s.SlowBuffer=e;s.INSPECT_MAX_BYTES=50;e.poolSize=8192;var E=1073741823;e.TYPED_ARRAY_SUPPORT=function(){try{var t=new ArrayBuffer(0);var e=new Uint8Array(t);e.foo=function(){return 42};return 42===e.foo()&&typeof e.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(r){return false}}();function e(t,s,o){if(!(this instanceof e))return new e(t,s,o);var a=typeof t;var i;if(a==="number")i=t>0?t>>>0:0;else if(a==="string"){if(s==="base64")t=P(t);i=e.byteLength(t,s)}else if(a==="object"&&t!==null){if(t.type==="Buffer"&&f(t.data))t=t.data;i=+t.length>0?Math.floor(+t.length):0}else throw new TypeError("must start with number, buffer, array or string");if(this.length>E)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+E.toString(16)+" bytes");var n;if(e.TYPED_ARRAY_SUPPORT){n=e._augment(new Uint8Array(i))}else{n=this;n.length=i;n._isBuffer=true}var r;if(e.TYPED_ARRAY_SUPPORT&&typeof t.byteLength==="number"){n._set(t)}else if(_(t)){if(e.isBuffer(t)){for(r=0;r<i;r++)n[r]=t.readUInt8(r)}else{for(r=0;r<i;r++)n[r]=(t[r]%256+256)%256}}else if(a==="string"){n.write(t,0,s)}else if(a==="number"&&!e.TYPED_ARRAY_SUPPORT&&!o){for(r=0;r<i;r++){n[r]=0}}return n}e.isBuffer=function(e){return!!(e!=null&&e._isBuffer)};e.compare=function(r,n){if(!e.isBuffer(r)||!e.isBuffer(n))throw new TypeError("Arguments must be Buffers");var i=r.length;var a=n.length;for(var t=0,s=Math.min(i,a);t<s&&r[t]===n[t];t++){}if(t!==s){i=r[t];a=n[t]}if(i<a)return-1;if(a<i)return 1;return 0};e.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};e.concat=function(t,n){if(!f(t))throw new TypeError("Usage: Buffer.concat(list[, length])");if(t.length===0){return new e(0)}else if(t.length===1){return t[0]}var r;if(n===undefined){n=0;for(r=0;r<t.length;r++){n+=t[r].length}}var i=new e(n);var a=0;for(r=0;r<t.length;r++){var s=t[r];s.copy(i,a);a+=s.length}return i};e.byteLength=function(e,r){var t;e=e+"";switch(r||"utf8"){case"ascii":case"binary":case"raw":t=e.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":t=e.length*2;break;case"hex":t=e.length>>>1;break;case"utf8":case"utf-8":t=u(e).length;break;case"base64":t=v(e).length;break;default:t=e.length}return t};e.prototype.length=undefined;e.prototype.parent=undefined;e.prototype.toString=function(r,t,e){var n=false;t=t>>>0;e=e===undefined||e===Infinity?this.length:e>>>0;if(!r)r="utf8";if(t<0)t=0;if(e>this.length)e=this.length;if(e<=t)return"";while(true){switch(r){case"hex":return L(this,t,e);case"utf8":case"utf-8":return k(this,t,e);case"ascii":return y(this,t,e);case"binary":return w(this,t,e);case"base64":return I(this,t,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,t,e);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase();n=true}}};e.prototype.equals=function(t){if(!e.isBuffer(t))throw new TypeError("Argument must be a Buffer");return e.compare(this,t)===0};e.prototype.inspect=function(){var e="";var t=s.INSPECT_MAX_BYTES;if(this.length>0){e=this.toString("hex",0,t).match(/.{2}/g).join(" ");if(this.length>t)e+=" ... "}return"<Buffer "+e+">"};e.prototype.compare=function(t){if(!e.isBuffer(t))throw new TypeError("Argument must be a Buffer");return e.compare(this,t)};e.prototype.get=function(e){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(e)};e.prototype.set=function(e,t){console.log(".set() is deprecated. Access using array indexes instead.");
return this.writeUInt8(e,t)};function N(a,s,r,e){r=Number(r)||0;var n=a.length-r;if(!e){e=n}else{e=Number(e);if(e>n){e=n}}var i=s.length;if(i%2!==0)throw new Error("Invalid hex string");if(e>i/2){e=i/2}for(var t=0;t<e;t++){var o=parseInt(s.substr(t*2,2),16);if(isNaN(o))throw new Error("Invalid hex string");a[r+t]=o}return t}function R(e,t,r,n){var i=a(u(t),e,r,n);return i}function g(e,t,r,n){var i=a(O(t),e,r,n);return i}function M(e,t,r,n){return g(e,t,r,n)}function A(e,t,r,n){var i=a(v(t),e,r,n);return i}function C(e,t,r,n){var i=a(D(t),e,r,n,2);return i}e.prototype.write=function(i,t,e,r){if(isFinite(t)){if(!isFinite(e)){r=e;e=undefined}}else{var s=r;r=t;t=e;e=s}t=Number(t)||0;var a=this.length-t;if(!e){e=a}else{e=Number(e);if(e>a){e=a}}r=String(r||"utf8").toLowerCase();var n;switch(r){case"hex":n=N(this,i,t,e);break;case"utf8":case"utf-8":n=R(this,i,t,e);break;case"ascii":n=g(this,i,t,e);break;case"binary":n=M(this,i,t,e);break;case"base64":n=A(this,i,t,e);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=C(this,i,t,e);break;default:throw new TypeError("Unknown encoding: "+r)}return n};e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function I(e,t,r){if(t===0&&r===e.length){return c.fromByteArray(e)}else{return c.fromByteArray(e.slice(t,r))}}function k(t,a,n){var i="";var r="";n=Math.min(t.length,n);for(var e=a;e<n;e++){if(t[e]<=127){i+=b(r)+String.fromCharCode(t[e]);r=""}else{r+="%"+t[e].toString(16)}}return i+b(r)}function y(r,i,e){var n="";e=Math.min(r.length,e);for(var t=i;t<e;t++){n+=String.fromCharCode(r[t])}return n}function w(e,t,r){return y(e,t,r)}function L(n,t,e){var i=n.length;if(!t||t<0)t=0;if(!e||e<0||e>i)e=i;var a="";for(var r=t;r<e;r++){a+=j(n[r])}return a}function S(n,i,a){var t=n.slice(i,a);var r="";for(var e=0;e<t.length;e+=2){r+=String.fromCharCode(t[e]+t[e+1]*256)}return r}e.prototype.slice=function(t,r){var n=this.length;t=~~t;r=r===undefined?n:~~r;if(t<0){t+=n;if(t<0)t=0}else if(t>n){t=n}if(r<0){r+=n;if(r<0)r=0}else if(r>n){r=n}if(r<t)r=t;if(e.TYPED_ARRAY_SUPPORT){return e._augment(this.subarray(t,r))}else{var a=r-t;var s=new e(a,undefined,true);for(var i=0;i<a;i++){s[i]=this[i+t]}return s}};function r(e,t,r){if(e%1!==0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}e.prototype.readUInt8=function(e,t){if(!t)r(e,1,this.length);return this[e]};e.prototype.readUInt16LE=function(e,t){if(!t)r(e,2,this.length);return this[e]|this[e+1]<<8};e.prototype.readUInt16BE=function(e,t){if(!t)r(e,2,this.length);return this[e]<<8|this[e+1]};e.prototype.readUInt32LE=function(e,t){if(!t)r(e,4,this.length);return(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};e.prototype.readUInt32BE=function(e,t){if(!t)r(e,4,this.length);return this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};e.prototype.readInt8=function(e,t){if(!t)r(e,1,this.length);if(!(this[e]&128))return this[e];return(255-this[e]+1)*-1};e.prototype.readInt16LE=function(e,n){if(!n)r(e,2,this.length);var t=this[e]|this[e+1]<<8;return t&32768?t|4294901760:t};e.prototype.readInt16BE=function(e,n){if(!n)r(e,2,this.length);var t=this[e+1]|this[e]<<8;return t&32768?t|4294901760:t};e.prototype.readInt32LE=function(e,t){if(!t)r(e,4,this.length);return this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};e.prototype.readInt32BE=function(e,t){if(!t)r(e,4,this.length);return this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};e.prototype.readFloatLE=function(e,t){if(!t)r(e,4,this.length);return i.read(this,e,true,23,4)};e.prototype.readFloatBE=function(e,t){if(!t)r(e,4,this.length);return i.read(this,e,false,23,4)};e.prototype.readDoubleLE=function(e,t){if(!t)r(e,8,this.length);return i.read(this,e,true,52,8)};e.prototype.readDoubleBE=function(e,t){if(!t)r(e,8,this.length);return i.read(this,e,false,52,8)};function n(t,r,n,i,a,s){if(!e.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");if(r>a||r<s)throw new TypeError("value is out of bounds");if(n+i>t.length)throw new TypeError("index out of range")}e.prototype.writeUInt8=function(t,r,i){t=+t;r=r>>>0;if(!i)n(this,t,r,1,255,0);if(!e.TYPED_ARRAY_SUPPORT)t=Math.floor(t);this[r]=t;return r+1};function l(r,t,n,i){if(t<0)t=65535+t+1;for(var e=0,a=Math.min(r.length-n,2);e<a;e++){r[n+e]=(t&255<<8*(i?e:1-e))>>>(i?e:1-e)*8}}e.prototype.writeUInt16LE=function(r,t,i){r=+r;t=t>>>0;if(!i)n(this,r,t,2,65535,0);if(e.TYPED_ARRAY_SUPPORT){this[t]=r;this[t+1]=r>>>8}else l(this,r,t,true);return t+2};e.prototype.writeUInt16BE=function(r,t,i){r=+r;t=t>>>0;if(!i)n(this,r,t,2,65535,0);if(e.TYPED_ARRAY_SUPPORT){this[t]=r>>>8;this[t+1]=r}else l(this,r,t,false);return t+2};function o(r,t,n,i){if(t<0)t=4294967295+t+1;for(var e=0,a=Math.min(r.length-n,4);e<a;e++){r[n+e]=t>>>(i?e:3-e)*8&255}}e.prototype.writeUInt32LE=function(r,t,i){r=+r;t=t>>>0;if(!i)n(this,r,t,4,4294967295,0);if(e.TYPED_ARRAY_SUPPORT){this[t+3]=r>>>24;this[t+2]=r>>>16;this[t+1]=r>>>8;this[t]=r}else o(this,r,t,true);return t+4};e.prototype.writeUInt32BE=function(r,t,i){r=+r;t=t>>>0;if(!i)n(this,r,t,4,4294967295,0);if(e.TYPED_ARRAY_SUPPORT){this[t]=r>>>24;this[t+1]=r>>>16;this[t+2]=r>>>8;this[t+3]=r}else o(this,r,t,false);return t+4};e.prototype.writeInt8=function(t,r,i){t=+t;r=r>>>0;if(!i)n(this,t,r,1,127,-128);if(!e.TYPED_ARRAY_SUPPORT)t=Math.floor(t);if(t<0)t=255+t+1;this[r]=t;return r+1};e.prototype.writeInt16LE=function(r,t,i){r=+r;t=t>>>0;if(!i)n(this,r,t,2,32767,-32768);if(e.TYPED_ARRAY_SUPPORT){this[t]=r;this[t+1]=r>>>8}else l(this,r,t,true);return t+2};e.prototype.writeInt16BE=function(r,t,i){r=+r;t=t>>>0;if(!i)n(this,r,t,2,32767,-32768);if(e.TYPED_ARRAY_SUPPORT){this[t]=r>>>8;this[t+1]=r}else l(this,r,t,false);return t+2};e.prototype.writeInt32LE=function(r,t,i){r=+r;t=t>>>0;if(!i)n(this,r,t,4,2147483647,-2147483648);if(e.TYPED_ARRAY_SUPPORT){this[t]=r;this[t+1]=r>>>8;this[t+2]=r>>>16;this[t+3]=r>>>24}else o(this,r,t,true);return t+4};e.prototype.writeInt32BE=function(t,r,i){t=+t;r=r>>>0;if(!i)n(this,t,r,4,2147483647,-2147483648);if(t<0)t=4294967295+t+1;if(e.TYPED_ARRAY_SUPPORT){this[r]=t>>>24;this[r+1]=t>>>16;this[r+2]=t>>>8;this[r+3]=t}else o(this,t,r,false);return r+4};function h(t,e,r,n,i,a){if(e>i||e<a)throw new TypeError("value is out of bounds");if(r+n>t.length)throw new TypeError("index out of range")}function m(t,r,e,n,a){if(!a)h(t,r,e,4,3.4028234663852886e38,-3.4028234663852886e38);i.write(t,r,e,n,23,4);return e+4}e.prototype.writeFloatLE=function(e,t,r){return m(this,e,t,true,r)};e.prototype.writeFloatBE=function(e,t,r){return m(this,e,t,false,r)};function d(t,r,e,n,a){if(!a)h(t,r,e,8,1.7976931348623157e308,-1.7976931348623157e308);i.write(t,r,e,n,52,8);return e+8}e.prototype.writeDoubleLE=function(e,t,r){return d(this,e,t,true,r)};e.prototype.writeDoubleBE=function(e,t,r){return d(this,e,t,false,r)};e.prototype.copy=function(i,n,t,r){var s=this;if(!t)t=0;if(!r&&r!==0)r=this.length;if(!n)n=0;if(r===t)return;if(i.length===0||s.length===0)return;if(r<t)throw new TypeError("sourceEnd < sourceStart");if(n<0||n>=i.length)throw new TypeError("targetStart out of bounds");if(t<0||t>=s.length)throw new TypeError("sourceStart out of bounds");if(r<0||r>s.length)throw new TypeError("sourceEnd out of bounds");if(r>this.length)r=this.length;if(i.length-n<r-t)r=i.length-n+t;var o=r-t;if(o<1e3||!e.TYPED_ARRAY_SUPPORT){for(var a=0;a<o;a++){i[a+n]=this[a+t]}}else{i._set(this.subarray(t,t+o),n)}};e.prototype.fill=function(n,t,r){if(!n)n=0;if(!t)t=0;if(!r)r=this.length;if(r<t)throw new TypeError("end < start");if(r===t)return;if(this.length===0)return;if(t<0||t>=this.length)throw new TypeError("start out of bounds");if(r<0||r>this.length)throw new TypeError("end out of bounds");var e;if(typeof n==="number"){for(e=t;e<r;e++){this[e]=n}}else{var i=u(n.toString());var a=i.length;for(e=t;e<r;e++){this[e]=i[e%a]}}return this};e.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(e.TYPED_ARRAY_SUPPORT){return new e(this).buffer}else{var r=new Uint8Array(this.length);for(var t=0,n=r.length;t<n;t+=1){r[t]=this[t]}return r.buffer}}else{throw new TypeError("Buffer.toArrayBuffer not supported in this browser")}};var t=e.prototype;e._augment=function(r){r.constructor=e;r._isBuffer=true;r._get=r.get;r._set=r.set;r.get=t.get;r.set=t.set;r.write=t.write;r.toString=t.toString;r.toLocaleString=t.toString;r.toJSON=t.toJSON;r.equals=t.equals;r.compare=t.compare;r.copy=t.copy;r.slice=t.slice;r.readUInt8=t.readUInt8;r.readUInt16LE=t.readUInt16LE;r.readUInt16BE=t.readUInt16BE;r.readUInt32LE=t.readUInt32LE;r.readUInt32BE=t.readUInt32BE;r.readInt8=t.readInt8;r.readInt16LE=t.readInt16LE;r.readInt16BE=t.readInt16BE;r.readInt32LE=t.readInt32LE;r.readInt32BE=t.readInt32BE;r.readFloatLE=t.readFloatLE;r.readFloatBE=t.readFloatBE;r.readDoubleLE=t.readDoubleLE;r.readDoubleBE=t.readDoubleBE;r.writeUInt8=t.writeUInt8;r.writeUInt16LE=t.writeUInt16LE;r.writeUInt16BE=t.writeUInt16BE;r.writeUInt32LE=t.writeUInt32LE;r.writeUInt32BE=t.writeUInt32BE;r.writeInt8=t.writeInt8;r.writeInt16LE=t.writeInt16LE;r.writeInt16BE=t.writeInt16BE;r.writeInt32LE=t.writeInt32LE;r.writeInt32BE=t.writeInt32BE;r.writeFloatLE=t.writeFloatLE;r.writeFloatBE=t.writeFloatBE;r.writeDoubleLE=t.writeDoubleLE;r.writeDoubleBE=t.writeDoubleBE;r.fill=t.fill;r.inspect=t.inspect;r.toArrayBuffer=t.toArrayBuffer;return r};var T=/[^+\/0-9A-z]/g;function P(e){e=x(e).replace(T,"");while(e.length%4!==0){e=e+"="}return e}function x(e){if(e.trim)return e.trim();return e.replace(/^\s+|\s+$/g,"")}function _(t){return f(t)||e.isBuffer(t)||t&&typeof t==="object"&&typeof t.length==="number"}function j(e){if(e<16)return"0"+e.toString(16);return e.toString(16)}function u(r){var n=[];for(var e=0;e<r.length;e++){var t=r.charCodeAt(e);if(t<=127){n.push(t)}else{var s=e;if(t>=55296&&t<=57343)e++;var a=encodeURIComponent(r.slice(s,e+1)).substr(1).split("%");for(var i=0;i<a.length;i++){n.push(parseInt(a[i],16))}}}return n}function O(t){var r=[];for(var e=0;e<t.length;e++){r.push(t.charCodeAt(e)&255)}return r}function D(n){var e,i,a;var t=[];for(var r=0;r<n.length;r++){e=n.charCodeAt(r);i=e>>8;a=e%256;t.push(a);t.push(i)}return t}function v(e){return c.toByteArray(e)}function a(r,n,i,t,a){if(a)t-=t%a;for(var e=0;e<t;e++){if(e+i>=n.length||e>=r.length)break;n[e+i]=r[e]}return e}function b(e){try{return decodeURIComponent(e)}catch(t){return String.fromCharCode(65533)}}},{"base64-js":105,ieee754:106,"is-array":107}],105:[function(r,n,e){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(n){"use strict";var s=typeof Uint8Array!=="undefined"?Uint8Array:Array;var o="+".charCodeAt(0);var l="/".charCodeAt(0);var r="0".charCodeAt(0);var i="a".charCodeAt(0);var a="A".charCodeAt(0);function e(t){var e=t.charCodeAt(0);if(e===o)return 62;if(e===l)return 63;if(e<r)return-1;if(e<r+10)return e-r+26+26;if(e<a+26)return e-a;if(e<i+26)return e-i+26}function u(t){var r,l,u,n,a,o;if(t.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var f=t.length;a="="===t.charAt(f-2)?2:"="===t.charAt(f-1)?1:0;o=new s(t.length*3/4-a);u=a>0?t.length-4:t.length;var c=0;function i(e){o[c++]=e}for(r=0,l=0;r<u;r+=4,l+=3){n=e(t.charAt(r))<<18|e(t.charAt(r+1))<<12|e(t.charAt(r+2))<<6|e(t.charAt(r+3));i((n&16711680)>>16);i((n&65280)>>8);i(n&255)}if(a===2){n=e(t.charAt(r))<<2|e(t.charAt(r+1))>>4;i(n&255)}else if(a===1){n=e(t.charAt(r))<<10|e(t.charAt(r+1))<<4|e(t.charAt(r+2))>>2;i(n>>8&255);i(n&255)}return o}function f(e){var a,s=e.length%3,r="",n,o;function i(e){return t.charAt(e)}function l(e){return i(e>>18&63)+i(e>>12&63)+i(e>>6&63)+i(e&63)}for(a=0,o=e.length-s;a<o;a+=3){n=(e[a]<<16)+(e[a+1]<<8)+e[a+2];r+=l(n)}switch(s){case 1:n=e[e.length-1];r+=i(n>>2);r+=i(n<<4&63);r+="==";break;case 2:n=(e[e.length-2]<<8)+e[e.length-1];r+=i(n>>10);r+=i(n>>4&63);r+=i(n<<2&63);r+="=";break}return r}n.toByteArray=u;n.fromByteArray=f})(typeof e==="undefined"?this.base64js={}:e)},{}],106:[function(t,r,e){e.read=function(l,o,p,a,c){var e,r,d=c*8-a-1,f=(1<<d)-1,u=f>>1,t=-7,n=p?c-1:0,s=p?-1:1,i=l[o+n];n+=s;e=i&(1<<-t)-1;i>>=-t;t+=d;for(;t>0;e=e*256+l[o+n],n+=s,t-=8);r=e&(1<<-t)-1;e>>=-t;t+=a;for(;t>0;r=r*256+l[o+n],n+=s,t-=8);if(e===0){e=1-u}else if(e===f){return r?NaN:(i?-1:1)*Infinity}else{r=r+Math.pow(2,a);e=e-u}return(i?-1:1)*r*Math.pow(2,e-a)};e.write=function(f,t,c,m,r,d){var e,n,i,o=d*8-r-1,l=(1<<o)-1,a=l>>1,p=r===23?Math.pow(2,-24)-Math.pow(2,-77):0,s=m?0:d-1,u=m?1:-1,h=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){n=isNaN(t)?1:0;e=l}else{e=Math.floor(Math.log(t)/Math.LN2);if(t*(i=Math.pow(2,-e))<1){e--;i*=2}if(e+a>=1){t+=p/i}else{t+=p*Math.pow(2,1-a)}if(t*i>=2){e++;i/=2}if(e+a>=l){n=0;e=l}else if(e+a>=1){n=(t*i-1)*Math.pow(2,r);e=e+a}else{n=t*Math.pow(2,a-1)*Math.pow(2,r);e=0}}for(;r>=8;f[c+s]=n&255,s+=u,n/=256,r-=8);e=e<<r|n;o+=r;for(;o>0;f[c+s]=e&255,s+=u,e/=256,o-=8);f[c+s-u]|=h*128}},{}],107:[function(n,e,i){var t=Array.isArray;var r=Object.prototype.toString;e.exports=t||function(e){return!!e&&"[object Array]"==r.call(e)}},{}],108:[function(s,i,o){function e(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}i.exports=e;e.EventEmitter=e;e.prototype._events=undefined;e.prototype._maxListeners=undefined;e.defaultMaxListeners=10;e.prototype.setMaxListeners=function(e){if(!a(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");this._maxListeners=e;return this};e.prototype.emit=function(u){var o,i,a,s,e,l;if(!this._events)this._events={};if(u==="error"){if(!this._events.error||r(this._events.error)&&!this._events.error.length){o=arguments[1];if(o instanceof Error){throw o}throw TypeError('Uncaught, unspecified "error" event.')}}i=this._events[u];if(n(i))return false;if(t(i)){switch(arguments.length){case 1:i.call(this);break;case 2:i.call(this,arguments[1]);break;case 3:i.call(this,arguments[1],arguments[2]);break;default:a=arguments.length;s=new Array(a-1);for(e=1;e<a;e++)s[e-1]=arguments[e];i.apply(this,s)}}else if(r(i)){a=arguments.length;s=new Array(a-1);for(e=1;e<a;e++)s[e-1]=arguments[e];l=i.slice();a=l.length;for(e=0;e<a;e++)l[e].apply(this,s)}return true};e.prototype.addListener=function(i,a){var s;if(!t(a))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",i,t(a.listener)?a.listener:a);if(!this._events[i])this._events[i]=a;else if(r(this._events[i]))this._events[i].push(a);else this._events[i]=[this._events[i],a];if(r(this._events[i])&&!this._events[i].warned){var s;if(!n(this._maxListeners)){s=this._maxListeners}else{s=e.defaultMaxListeners}if(s&&s>0&&this._events[i].length>s){this._events[i].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[i].length);if(typeof console.trace==="function"){console.trace()}}}return this};e.prototype.on=e.prototype.addListener;e.prototype.once=function(n,e){if(!t(e))throw TypeError("listener must be a function");var i=false;function r(){this.removeListener(n,r);if(!i){i=true;e.apply(this,arguments)}}r.listener=e;this.on(n,r);return this};e.prototype.removeListener=function(i,n){var e,s,o,a;if(!t(n))throw TypeError("listener must be a function");if(!this._events||!this._events[i])return this;e=this._events[i];o=e.length;s=-1;if(e===n||t(e.listener)&&e.listener===n){delete this._events[i];if(this._events.removeListener)this.emit("removeListener",i,n)}else if(r(e)){for(a=o;a-->0;){if(e[a]===n||e[a].listener&&e[a].listener===n){s=a;break}}if(s<0)return this;if(e.length===1){e.length=0;delete this._events[i]}else{e.splice(s,1)}if(this._events.removeListener)this.emit("removeListener",i,n)}return this};e.prototype.removeAllListeners=function(e){var n,r;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[e])delete this._events[e];return this}if(arguments.length===0){for(n in this._events){if(n==="removeListener")continue;this.removeAllListeners(n)}this.removeAllListeners("removeListener");this._events={};return this}r=this._events[e];if(t(r)){this.removeListener(e,r)}else{while(r.length)this.removeListener(e,r[r.length-1])}delete this._events[e];return this};e.prototype.listeners=function(e){var r;if(!this._events||!this._events[e])r=[];else if(t(this._events[e]))r=[this._events[e]];else r=this._events[e].slice();return r};e.listenerCount=function(e,n){var r;if(!e._events||!e._events[n])r=0;else if(t(e._events[n]))r=1;else r=e._events[n].length;return r};function t(e){return typeof e==="function"}function a(e){return typeof e==="number"}function r(e){return typeof e==="object"&&e!==null}function n(e){return e===void 0}},{}],109:[function(t,e,r){if(typeof Object.create==="function"){e.exports=function n(e,t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}else{e.exports=function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype;e.prototype=new r;e.prototype.constructor=e}}},{}],110:[function(t,e,r){e.exports=Array.isArray||function(e){return Object.prototype.toString.call(e)=="[object Array]"}},{}],111:[function(t,r,e){(function(i){function n(e,i){var r=0;for(var t=e.length-1;t>=0;t--){var n=e[t];if(n==="."){e.splice(t,1)}else if(n===".."){e.splice(t,1);r++}else if(r){e.splice(t,1);r--}}if(i){for(;r--;r){e.unshift("..")}}return e}var a=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var t=function(e){return a.exec(e).slice(1)};e.resolve=function(){var e="",t=false;for(var a=arguments.length-1;a>=-1&&!t;a--){var s=a>=0?arguments[a]:i.cwd();if(typeof s!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!s){continue}e=s+"/"+e;t=s.charAt(0)==="/"}e=n(r(e.split("/"),function(e){return!!e}),!t).join("/");return(t?"/":"")+e||"."};e.normalize=function(t){var i=e.isAbsolute(t),a=s(t,-1)==="/";t=n(r(t.split("/"),function(e){return!!e}),!i).join("/");if(!t&&!i){t="."}if(t&&a){t+="/"}return(i?"/":"")+t};e.isAbsolute=function(e){return e.charAt(0)==="/"};e.join=function(){var t=Array.prototype.slice.call(arguments,0);return e.normalize(r(t,function(e,t){if(typeof e!=="string"){throw new TypeError("Arguments to path.join must be strings")}return e}).join("/"))};e.relative=function(n,i){n=e.resolve(n).substr(1);i=e.resolve(i).substr(1);function l(t){var e=0;for(;e<t.length;e++){if(t[e]!=="")break}var r=t.length-1;for(;r>=0;r--){if(t[r]!=="")break}if(e>r)return[];return t.slice(e,r-e+1)}var a=l(n.split("/"));var s=l(i.split("/"));var u=Math.min(a.length,s.length);var o=u;for(var t=0;t<u;t++){if(a[t]!==s[t]){o=t;break}}var r=[];for(var t=o;t<a.length;t++){r.push("..")}r=r.concat(s.slice(o));return r.join("/")};e.sep="/";e.delimiter=":";e.dirname=function(i){var r=t(i),n=r[0],e=r[1];if(!n&&!e){return"."}if(e){e=e.substr(0,e.length-1)}return n+e};e.basename=function(n,r){var e=t(n)[2];if(r&&e.substr(-1*r.length)===r){e=e.substr(0,e.length-r.length)}return e};e.extname=function(e){return t(e)[3]};function r(e,r){if(e.filter)return e.filter(r);var n=[];for(var t=0;t<e.length;t++){if(r(e[t],t,e))n.push(e[t])}return n}var s="ab".substr(-1)==="b"?function(e,t,r){return e.substr(t,r)}:function(t,e,r){if(e<0)e=t.length+e;return t.substr(e,r)}}).call(this,t("_process"))},{_process:112}],112:[function(n,r,i){var e=r.exports={};e.nextTick=function(){var r=typeof window!=="undefined"&&window.setImmediate;var n=typeof window!=="undefined"&&window.MutationObserver;var i=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(r){return function(e){return window.setImmediate(e)}}var e=[];if(n){var t=document.createElement("div");var a=new MutationObserver(function(){var t=e.slice();e.length=0;t.forEach(function(e){e()})});a.observe(t,{attributes:true});return function s(r){if(!e.length){t.setAttribute("yes","no")}e.push(r)}}if(i){window.addEventListener("message",function(t){var r=t.source;if((r===window||r===null)&&t.data==="process-tick"){t.stopPropagation();if(e.length>0){var n=e.shift();n()}}},true);return function o(t){e.push(t);window.postMessage("process-tick","*")}}return function l(e){setTimeout(e,0)}}();e.title="browser";e.browser=true;e.env={};e.argv=[];function t(){}e.on=t;e.addListener=t;e.once=t;e.off=t;e.removeListener=t;e.removeAllListeners=t;e.emit=t;e.binding=function(e){throw new Error("process.binding is not supported")};e.cwd=function(){return"/"};e.chdir=function(e){throw new Error("process.chdir is not supported")}},{}],113:[function(e,t,r){t.exports=e("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":114}],114:[function(e,t,r){(function(s){t.exports=r;var o=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};var i=e("core-util-is");i.inherits=e("inherits");var a=e("./_stream_readable");var n=e("./_stream_writable");i.inherits(r,a);u(o(n.prototype),function(e){if(!r.prototype[e])r.prototype[e]=n.prototype[e]});function r(e){if(!(this instanceof r))return new r(e);a.call(this,e);n.call(this,e);if(e&&e.readable===false)this.readable=false;if(e&&e.writable===false)this.writable=false;this.allowHalfOpen=true;if(e&&e.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",l)}function l(){if(this.allowHalfOpen||this._writableState.ended)return;s.nextTick(this.end.bind(this))}function u(t,r){for(var e=0,n=t.length;e<n;e++){r(t[e],e)}}}).call(this,e("_process"))},{"./_stream_readable":116,"./_stream_writable":118,_process:112,"core-util-is":119,inherits:109}],115:[function(t,i,a){i.exports=e;var r=t("./_stream_transform");var n=t("core-util-is");n.inherits=t("inherits");n.inherits(e,r);function e(t){if(!(this instanceof e))return new e(t);r.call(this,t)}e.prototype._transform=function(e,r,t){t(null,e)}},{"./_stream_transform":117,"core-util-is":119,inherits:109}],116:[function(e,t,r){(function(n){t.exports=r;var k=e("isarray");var o=e("buffer").Buffer;r.ReadableState=b;var l=e("events").EventEmitter;if(!l.listenerCount)l.listenerCount=function(e,t){return e.listeners(t).length};var a=e("stream");var h=e("core-util-is");h.inherits=e("inherits");var i;h.inherits(r,a);function b(t,n){t=t||{};var r=t.highWaterMark;this.highWaterMark=r||r===0?r:16*1024;this.highWaterMark=~~this.highWaterMark;this.buffer=[];this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=false;this.ended=false;this.endEmitted=false;this.reading=false;this.calledRead=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.objectMode=!!t.objectMode;this.defaultEncoding=t.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(t.encoding){if(!i)i=e("string_decoder/").StringDecoder;this.decoder=new i(t.encoding);this.encoding=t.encoding}}function r(e){if(!(this instanceof r))return new r(e);this._readableState=new b(e,this);this.readable=true;a.call(this)}r.prototype.push=function(t,e){var r=this._readableState;if(typeof t==="string"&&!r.objectMode){e=e||r.defaultEncoding;if(e!==r.encoding){t=new o(t,e);e=""}}return y(this,r,t,e,false)};r.prototype.unshift=function(e){var t=this._readableState;return y(this,t,e,"",true)};function y(r,e,t,o,n){var i=P(e,t);if(i){r.emit("error",i)}else if(t===null||t===undefined){e.reading=false;if(!e.ended)I(r,e)}else if(e.objectMode||t&&t.length>0){if(e.ended&&!n){var a=new Error("stream.push() after EOF");r.emit("error",a)}else if(e.endEmitted&&n){var a=new Error("stream.unshift() after end event");r.emit("error",a)}else{if(e.decoder&&!n&&!o)t=e.decoder.write(t);e.length+=e.objectMode?1:t.length;if(n){e.buffer.unshift(t)}else{e.reading=false;e.buffer.push(t)}if(e.needReadable)s(r);T(r,e)}}else if(!n){e.reading=false}return w(e)}function w(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||e.length===0)}r.prototype.setEncoding=function(t){if(!i)i=e("string_decoder/").StringDecoder;this._readableState.decoder=new i(t);this._readableState.encoding=t};var E=8388608;function A(e){if(e>=E){e=E}else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function g(t,e){if(e.length===0&&e.ended)return 0;if(e.objectMode)return t===0?0:1;if(t===null||isNaN(t)){if(e.flowing&&e.buffer.length)return e.buffer[0].length;else return e.length}if(t<=0)return 0;if(t>e.highWaterMark)e.highWaterMark=A(t);if(t>e.length){if(!e.ended){e.needReadable=true;return 0}else return e.length}return t}r.prototype.read=function(t){var e=this._readableState;e.calledRead=true;var i=t;var r;if(typeof t!=="number"||t>0)e.emittedReadable=false;if(t===0&&e.needReadable&&(e.length>=e.highWaterMark||e.ended)){s(this);return null}t=g(t,e);if(t===0&&e.ended){r=null;if(e.length>0&&e.decoder){r=p(t,e);e.length-=r.length}if(e.length===0)d(this);return r}var n=e.needReadable;if(e.length-t<=e.highWaterMark)n=true;if(e.ended||e.reading)n=false;if(n){e.reading=true;e.sync=true;if(e.length===0)e.needReadable=true;this._read(e.highWaterMark);e.sync=false}if(n&&!e.reading)t=g(i,e);if(t>0)r=p(t,e);else r=null;if(r===null){e.needReadable=true;t=0}e.length-=t;if(e.length===0&&!e.ended)e.needReadable=true;if(e.ended&&!e.endEmitted&&e.length===0)d(this);return r};function P(r,e){var t=null;if(!o.isBuffer(e)&&"string"!==typeof e&&e!==null&&e!==undefined&&!r.objectMode){t=new TypeError("Invalid non-string/buffer chunk")}return t}function I(r,e){if(e.decoder&&!e.ended){var t=e.decoder.end();if(t&&t.length){e.buffer.push(t);e.length+=e.objectMode?1:t.length}}e.ended=true;if(e.length>0)s(r);else d(r)}function s(t){var e=t._readableState;e.needReadable=false;if(e.emittedReadable)return;e.emittedReadable=true;if(e.sync)n.nextTick(function(){m(t)});else m(t)}function m(e){e.emit("readable")}function T(t,e){if(!e.readingMore){e.readingMore=true;n.nextTick(function(){x(t,e)})}}function x(r,e){var t=e.length;while(!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark){r.read(0);if(t===e.length)break;else t=e.length}e.readingMore=false}r.prototype._read=function(e){this.emit("error",new Error("not implemented"))};r.prototype.pipe=function(e,d){var r=this;var t=this._readableState;switch(t.pipesCount){case 0:t.pipes=e;break;case 1:t.pipes=[t.pipes,e];break;default:t.pipes.push(e);break}t.pipesCount+=1;var v=(!d||d.end!==false)&&e!==n.stdout&&e!==n.stderr;var h=v?y:u;if(t.endEmitted)n.nextTick(h);else r.once("end",h);e.on("unpipe",m);function m(e){if(e!==r)return;u()}function y(){e.end()}var p=S(r);e.on("drain",p);function u(){e.removeListener("close",s);e.removeListener("finish",a);e.removeListener("drain",p);e.removeListener("error",i);e.removeListener("unpipe",m);r.removeListener("end",y);r.removeListener("end",u);if(!e._writableState||e._writableState.needDrain)p()}function i(t){o();e.removeListener("error",i);if(l.listenerCount(e,"error")===0)e.emit("error",t)}if(!e._events||!e._events.error)e.on("error",i);else if(k(e._events.error))e._events.error.unshift(i);else e._events.error=[i,e._events.error];function s(){e.removeListener("finish",a);o()}e.once("close",s);function a(){e.removeListener("close",s);o()}e.once("finish",a);function o(){r.unpipe(e)}e.emit("pipe",r);if(!t.flowing){this.on("readable",f);t.flowing=true;n.nextTick(function(){c(r)})}return e};function S(e){return function(){var r=this;var t=e._readableState;t.awaitDrain--;if(t.awaitDrain===0)c(e)}}function c(t){var e=t._readableState;var r;e.awaitDrain=0;function n(t,i,a){var n=t.write(r);if(false===n){e.awaitDrain++}}while(e.pipesCount&&null!==(r=t.read())){if(e.pipesCount===1)n(e.pipes,0,null);else v(e.pipes,n);t.emit("data",r);if(e.awaitDrain>0)return}if(e.pipesCount===0){e.flowing=false;if(l.listenerCount(t,"data")>0)u(t);return}e.ranOut=true}function f(){if(this._readableState.ranOut){this._readableState.ranOut=false;c(this)}}r.prototype.unpipe=function(t){var e=this._readableState;if(e.pipesCount===0)return this;if(e.pipesCount===1){if(t&&t!==e.pipes)return this;if(!t)t=e.pipes;e.pipes=null;e.pipesCount=0;this.removeListener("readable",f);e.flowing=false;if(t)t.emit("unpipe",this);return this}if(!t){var n=e.pipes;var i=e.pipesCount;e.pipes=null;e.pipesCount=0;this.removeListener("readable",f);e.flowing=false;for(var r=0;r<i;r++)n[r].emit("unpipe",this);return this}var r=C(e.pipes,t);if(r===-1)return this;e.pipes.splice(r,1);e.pipesCount-=1;if(e.pipesCount===1)e.pipes=e.pipes[0];t.emit("unpipe",this);return this};r.prototype.on=function(t,r){var n=a.prototype.on.call(this,t,r);if(t==="data"&&!this._readableState.flowing)u(this);if(t==="readable"&&this.readable){var e=this._readableState;if(!e.readableListening){e.readableListening=true;e.emittedReadable=false;e.needReadable=true;if(!e.reading){this.read(0)}else if(e.length){s(this,e)}}}return n};r.prototype.addListener=r.prototype.on;r.prototype.resume=function(){u(this);this.read(0);this.emit("resume")};r.prototype.pause=function(){u(this,true);this.emit("pause")};function u(e,i){var s=e._readableState;if(s.flowing){throw new Error("Cannot switch to old mode now.")}var t=i||false;var r=false;e.readable=true;e.pipe=a.prototype.pipe;e.on=e.addListener=a.prototype.on;e.on("readable",function(){r=true;var n;while(!t&&null!==(n=e.read()))e.emit("data",n);if(n===null){r=false;e._readableState.needReadable=true}});e.pause=function(){t=true;this.emit("pause")};e.resume=function(){t=false;if(r)n.nextTick(function(){e.emit("readable")});else this.read(0);this.emit("resume")};e.emit("readable")}r.prototype.wrap=function(e){var t=this._readableState;var i=false;var r=this;e.on("end",function(){if(t.decoder&&!t.ended){var e=t.decoder.end();if(e&&e.length)r.push(e)}r.push(null)});e.on("data",function(n){if(t.decoder)n=t.decoder.write(n);if(t.objectMode&&(n===null||n===undefined))return;else if(!t.objectMode&&(!n||!n.length))return;var a=r.push(n);if(!a){i=true;e.pause()}});for(var n in e){if(typeof e[n]==="function"&&typeof this[n]==="undefined"){this[n]=function(t){return function(){return e[t].apply(e,arguments)}}(n)}}var a=["error","close","destroy","pause","resume"];v(a,function(t){e.on(t,r.emit.bind(r,t))});r._read=function(t){if(i){i=false;e.resume()}};return r};r._fromList=p;function p(r,a){var e=a.buffer;var l=a.length;var u=!!a.decoder;var c=!!a.objectMode;var t;if(e.length===0)return null;if(l===0)t=null;else if(c)t=e.shift();else if(!r||r>=l){if(u)t=e.join("");else t=o.concat(e,l);e.length=0}else{if(r<e[0].length){var n=e[0];t=n.slice(0,r);e[0]=n.slice(r)}else if(r===e[0].length){t=e.shift()}else{if(u)t="";else t=new o(r);var s=0;for(var f=0,p=e.length;f<p&&s<r;f++){var n=e[0];var i=Math.min(r-s,n.length);if(u)t+=n.slice(0,i);else n.copy(t,s,0,i);if(i<n.length)e[0]=n.slice(i);else e.shift();s+=i}}}return t}function d(t){var e=t._readableState;if(e.length>0)throw new Error("endReadable called on non-empty stream");if(!e.endEmitted&&e.calledRead){e.ended=true;n.nextTick(function(){if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end")}})}}function v(t,r){for(var e=0,n=t.length;e<n;e++){r(t[e],e)}}function C(t,r){for(var e=0,n=t.length;e<n;e++){if(t[e]===r)return e}return-1}}).call(this,e("_process"))},{_process:112,buffer:104,"core-util-is":119,events:108,inherits:109,isarray:110,stream:124,"string_decoder/":125}],117:[function(t,a,l){a.exports=e;var r=t("./_stream_duplex");var n=t("core-util-is");n.inherits=t("inherits");n.inherits(e,r);function s(t,e){this.afterTransform=function(t,r){return o(e,t,r)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null}function o(e,a,n){var r=e._transformState;r.transforming=false;var i=r.writecb;if(!i)return e.emit("error",new Error("no writecb in Transform class"));r.writechunk=null;r.writecb=null;if(n!==null&&n!==undefined)e.push(n);if(i)i(a);var t=e._readableState;t.reading=false;if(t.needReadable||t.length<t.highWaterMark){e._read(t.highWaterMark)}}function e(t){if(!(this instanceof e))return new e(t);r.call(this,t);var a=this._transformState=new s(t,this);var n=this;this._readableState.needReadable=true;this._readableState.sync=false;this.once("finish",function(){if("function"===typeof this._flush)this._flush(function(e){i(n,e)
});else i(n)})}e.prototype.push=function(e,t){this._transformState.needTransform=false;return r.prototype.push.call(this,e,t)};e.prototype._transform=function(e,t,r){throw new Error("not implemented")};e.prototype._write=function(r,n,i){var e=this._transformState;e.writecb=i;e.writechunk=r;e.writeencoding=n;if(!e.transforming){var t=this._readableState;if(e.needTransform||t.needReadable||t.length<t.highWaterMark)this._read(t.highWaterMark)}};e.prototype._read=function(t){var e=this._transformState;if(e.writechunk!==null&&e.writecb&&!e.transforming){e.transforming=true;this._transform(e.writechunk,e.writeencoding,e.afterTransform)}else{e.needTransform=true}};function i(e,t){if(t)return e.emit("error",t);var r=e._writableState;var i=e._readableState;var n=e._transformState;if(r.length)throw new Error("calling transform done when ws.length != 0");if(n.transforming)throw new Error("calling transform done when still transforming");return e.push(null)}},{"./_stream_duplex":114,"core-util-is":119,inherits:109}],118:[function(e,t,r){(function(n){t.exports=r;var i=e("buffer").Buffer;r.WritableState=o;var a=e("core-util-is");a.inherits=e("inherits");var s=e("stream");a.inherits(r,s);function d(e,t,r){this.chunk=e;this.encoding=t;this.callback=r}function o(e,r){e=e||{};var t=e.highWaterMark;this.highWaterMark=t||t===0?t:16*1024;this.objectMode=!!e.objectMode;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var n=e.decodeStrings===false;this.decodeStrings=!n;this.defaultEncoding=e.defaultEncoding||"utf8";this.length=0;this.writing=false;this.sync=true;this.bufferProcessing=false;this.onwrite=function(e){y(r,e)};this.writecb=null;this.writelen=0;this.buffer=[];this.errorEmitted=false}function r(t){var n=e("./_stream_duplex");if(!(this instanceof r)&&!(this instanceof n))return new r(t);this._writableState=new o(t,this);this.writable=true;s.call(this)}r.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))};function v(t,i,r){var e=new Error("write after end");t.emit("error",e);n.nextTick(function(){r(e)})}function E(a,s,e,o){var t=true;if(!i.isBuffer(e)&&"string"!==typeof e&&e!==null&&e!==undefined&&!s.objectMode){var r=new TypeError("Invalid non-string/buffer chunk");a.emit("error",r);n.nextTick(function(){o(r)});t=false}return t}r.prototype.write=function(n,e,t){var r=this._writableState;var a=false;if(typeof e==="function"){t=e;e=null}if(i.isBuffer(n))e="buffer";else if(!e)e=r.defaultEncoding;if(typeof t!=="function")t=function(){};if(r.ended)v(this,r,t);else if(E(this,r,n,t))a=S(this,r,n,e,t);return a};function x(t,e,r){if(!t.objectMode&&t.decodeStrings!==false&&typeof e==="string"){e=new i(e,r)}return e}function S(o,e,t,r,n){t=x(e,t,r);if(i.isBuffer(t))r="buffer";var a=e.objectMode?1:t.length;e.length+=a;var s=e.length<e.highWaterMark;if(!s)e.needDrain=true;if(e.writing)e.buffer.push(new d(t,r,n));else l(o,e,a,t,r,n);return s}function l(t,e,r,n,i,a){e.writelen=r;e.writecb=a;e.writing=true;e.sync=true;t._write(n,i,e.onwrite);e.sync=false}function m(t,a,i,e,r){if(i)n.nextTick(function(){r(e)});else r(e);t._writableState.errorEmitted=true;t.emit("error",e)}function h(e){e.writing=false;e.writecb=null;e.length-=e.writelen;e.writelen=0}function y(t,a){var e=t._writableState;var s=e.sync;var r=e.writecb;h(e);if(a)m(t,e,s,a,r);else{var i=f(t,e);if(!i&&!e.bufferProcessing&&e.buffer.length)b(t,e);if(s){n.nextTick(function(){u(t,e,i,r)})}else{u(t,e,i,r)}}}function u(e,t,r,n){if(!r)g(e,t);n();if(r)c(e,t)}function g(t,e){if(e.length===0&&e.needDrain){e.needDrain=false;t.emit("drain")}}function b(i,e){e.bufferProcessing=true;for(var t=0;t<e.buffer.length;t++){var r=e.buffer[t];var n=r.chunk;var a=r.encoding;var s=r.callback;var o=e.objectMode?1:n.length;l(i,e,o,n,a,s);if(e.writing){t++;break}}e.bufferProcessing=false;if(t<e.buffer.length)e.buffer=e.buffer.slice(t);else e.buffer.length=0}r.prototype._write=function(t,r,e){e(new Error("not implemented"))};r.prototype.end=function(e,t,r){var n=this._writableState;if(typeof e==="function"){r=e;e=null;t=null}else if(typeof t==="function"){r=t;t=null}if(typeof e!=="undefined"&&e!==null)this.write(e,t);if(!n.ending&&!n.finished)p(this,n,r)};function f(t,e){return e.ending&&e.length===0&&!e.finished&&!e.writing}function c(e,t){var r=f(e,t);if(r){t.finished=true;e.emit("finish")}return r}function p(r,e,t){e.ending=true;c(r,e);if(t){if(e.finished)n.nextTick(t);else r.once("finish",t)}e.ended=true}}).call(this,e("_process"))},{"./_stream_duplex":114,_process:112,buffer:104,"core-util-is":119,inherits:109,stream:124}],119:[function(t,r,e){(function(c){function u(e){return Array.isArray(e)}e.isArray=u;function n(e){return typeof e==="boolean"}e.isBoolean=n;function i(e){return e===null}e.isNull=i;function a(e){return e==null}e.isNullOrUndefined=a;function s(e){return typeof e==="number"}e.isNumber=s;function o(e){return typeof e==="string"}e.isString=o;function l(e){return typeof e==="symbol"}e.isSymbol=l;function v(e){return e===void 0}e.isUndefined=v;function f(e){return t(e)&&r(e)==="[object RegExp]"}e.isRegExp=f;function t(e){return typeof e==="object"&&e!==null}e.isObject=t;function p(e){return t(e)&&r(e)==="[object Date]"}e.isDate=p;function d(e){return t(e)&&(r(e)==="[object Error]"||e instanceof Error)}e.isError=d;function m(e){return typeof e==="function"}e.isFunction=m;function h(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}e.isPrimitive=h;function y(e){return c.isBuffer(e)}e.isBuffer=y;function r(e){return Object.prototype.toString.call(e)}}).call(this,t("buffer").Buffer)},{buffer:104}],120:[function(e,t,r){t.exports=e("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":115}],121:[function(t,r,e){var n=t("stream");e=r.exports=t("./lib/_stream_readable.js");e.Stream=n;e.Readable=e;e.Writable=t("./lib/_stream_writable.js");e.Duplex=t("./lib/_stream_duplex.js");e.Transform=t("./lib/_stream_transform.js");e.PassThrough=t("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":114,"./lib/_stream_passthrough.js":115,"./lib/_stream_readable.js":116,"./lib/_stream_transform.js":117,"./lib/_stream_writable.js":118,stream:124}],122:[function(e,t,r){t.exports=e("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":117}],123:[function(e,t,r){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":118}],124:[function(t,n,a){n.exports=e;var r=t("events").EventEmitter;var i=t("inherits");i(e,r);e.Readable=t("readable-stream/readable.js");e.Writable=t("readable-stream/writable.js");e.Duplex=t("readable-stream/duplex.js");e.Transform=t("readable-stream/transform.js");e.PassThrough=t("readable-stream/passthrough.js");e.Stream=e;function e(){r.call(this)}e.prototype.pipe=function(t,s){var e=this;function o(r){if(t.writable){if(false===t.write(r)&&e.pause){e.pause()}}}e.on("data",o);function l(){if(e.readable&&e.resume){e.resume()}}t.on("drain",l);if(!t._isStdio&&(!s||s.end!==false)){e.on("end",u);e.on("close",f)}var i=false;function u(){if(i)return;i=true;t.end()}function f(){if(i)return;i=true;if(typeof t.destroy==="function")t.destroy()}function a(e){n();if(r.listenerCount(this,"error")===0){throw e}}e.on("error",a);t.on("error",a);function n(){e.removeListener("data",o);t.removeListener("drain",l);e.removeListener("end",u);e.removeListener("close",f);e.removeListener("error",a);t.removeListener("error",a);e.removeListener("end",n);e.removeListener("close",n);t.removeListener("close",n)}e.on("end",n);e.on("close",n);t.on("close",n);t.emit("pipe",e);return t}},{events:108,inherits:109,"readable-stream/duplex.js":113,"readable-stream/passthrough.js":120,"readable-stream/readable.js":121,"readable-stream/transform.js":122,"readable-stream/writable.js":123}],125:[function(r,u,n){var t=r("buffer").Buffer;var i=t.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function a(e){if(e&&!i(e)){throw new Error("Unknown encoding: "+e)}}var e=n.StringDecoder=function(e){this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,"");a(e);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=l;break;default:this.write=s;return}this.charBuffer=new t(6);this.charReceived=0;this.charLength=0};e.prototype.write=function(e){var t="";while(this.charLength){var a=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;e.copy(this.charBuffer,this.charReceived,0,a);this.charReceived+=a;if(this.charReceived<this.charLength){return""}e=e.slice(a,e.length);t=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var i=t.charCodeAt(t.length-1);if(i>=55296&&i<=56319){this.charLength+=this.surrogateSize;t="";continue}this.charReceived=this.charLength=0;if(e.length===0){return t}break}this.detectIncompleteChar(e);var r=e.length;if(this.charLength){e.copy(this.charBuffer,0,e.length-this.charReceived,r);r-=this.charReceived}t+=e.toString(this.encoding,0,r);var r=t.length-1;var i=t.charCodeAt(r);if(i>=55296&&i<=56319){var n=this.surrogateSize;this.charLength+=n;this.charReceived+=n;this.charBuffer.copy(this.charBuffer,n,0,n);e.copy(this.charBuffer,0,0,n);return t.substring(0,r)}return t};e.prototype.detectIncompleteChar=function(t){var e=t.length>=3?3:t.length;for(;e>0;e--){var r=t[t.length-e];if(e==1&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e};e.prototype.end=function(e){var t="";if(e&&e.length)t=this.write(e);if(this.charReceived){var r=this.charReceived;var n=this.charBuffer;var i=this.encoding;t+=n.slice(0,r).toString(i)}return t};function s(e){return e.toString(this.encoding)}function o(e){this.charReceived=e.length%2;this.charLength=this.charReceived?2:0}function l(e){this.charReceived=e.length%3;this.charLength=this.charReceived?3:0}},{buffer:104}],126:[function(t,e,r){e.exports=function n(e){return e&&typeof e==="object"&&typeof e.copy==="function"&&typeof e.fill==="function"&&typeof e.readUInt8==="function"}},{}],127:[function(t,r,e){(function(a,_){var w=/%[sdj%]/g;e.format=function(s){if(!p(s)){var l=[];for(var e=0;e<arguments.length;e++){l.push(n(arguments[e]))}return l.join(" ")}var e=1;var t=arguments;var u=t.length;var a=String(s).replace(w,function(r){if(r==="%%")return"%";if(e>=u)return r;switch(r){case"%s":return String(t[e++]);case"%d":return Number(t[e++]);case"%j":try{return JSON.stringify(t[e++])}catch(n){return"[Circular]"}default:return r}});for(var r=t[e];e<u;r=t[++e]){if(o(r)||!i(r)){a+=" "+r}else{a+=" "+n(r)}}return a};e.deprecate=function(n,t){if(r(_.process)){return function(){return e.deprecate(n,t).apply(this,arguments)}}if(a.noDeprecation===true){return n}var i=false;function s(){if(!i){if(a.throwDeprecation){throw new Error(t)}else if(a.traceDeprecation){console.trace(t)}else{console.error(t)}i=true}return n.apply(this,arguments)}return s};var f={};var g;e.debuglog=function(t){if(r(g))g=a.env.NODE_DEBUG||"";t=t.toUpperCase();if(!f[t]){if(new RegExp("\\b"+t+"\\b","i").test(g)){var n=a.pid;f[t]=function(){var r=e.format.apply(e,arguments);console.error("%s %d: %s",t,n,r)}}else{f[t]=function(){}}}return f[t]};function n(i,n){var t={seen:[],stylize:I};if(arguments.length>=3)t.depth=arguments[2];if(arguments.length>=4)t.colors=arguments[3];if(y(n)){t.showHidden=n}else if(n){e._extend(t,n)}if(r(t.showHidden))t.showHidden=false;if(r(t.depth))t.depth=2;if(r(t.colors))t.colors=false;if(r(t.customInspect))t.customInspect=true;if(t.colors)t.stylize=C;return c(t,i,t.depth)}e.inspect=n;n.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};n.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function C(t,r){var e=n.styles[r];if(e){return"["+n.colors[e][0]+"m"+t+"["+n.colors[e][1]+"m"}else{return t}}function I(e,t){return e}function D(t){var e={};t.forEach(function(t,r){e[t]=true});return e}function c(r,t,a){if(r.customInspect&&t&&l(t.inspect)&&t.inspect!==e.inspect&&!(t.constructor&&t.constructor.prototype===t)){var o=t.inspect(a,r);if(!p(o)){o=c(r,o,a)}return o}var v=A(r,t);if(v){return v}var n=Object.keys(t);var g=D(n);if(r.showHidden){n=Object.getOwnPropertyNames(t)}if(s(t)&&(n.indexOf("message")>=0||n.indexOf("description")>=0)){return d(t)}if(n.length===0){if(l(t)){var E=t.name?": "+t.name:"";return r.stylize("[Function"+E+"]","special")}if(u(t)){return r.stylize(RegExp.prototype.toString.call(t),"regexp")}if(b(t)){return r.stylize(Date.prototype.toString.call(t),"date")}if(s(t)){return d(t)}}var i="",h=false,f=["{","}"];if(S(t)){h=true;f=["[","]"]}if(l(t)){var x=t.name?": "+t.name:"";i=" [Function"+x+"]"}if(u(t)){i=" "+RegExp.prototype.toString.call(t)}if(b(t)){i=" "+Date.prototype.toUTCString.call(t)}if(s(t)){i=" "+d(t)}if(n.length===0&&(!h||t.length==0)){return f[0]+i+f[1]}if(a<0){if(u(t)){return r.stylize(RegExp.prototype.toString.call(t),"regexp")}else{return r.stylize("[Object]","special")}}r.seen.push(t);var y;if(h){y=P(r,t,a,g,n)}else{y=n.map(function(e){return m(r,t,a,g,e,h)})}r.seen.pop();return j(y,i,f)}function A(t,e){if(r(e))return t.stylize("undefined","undefined");if(p(e)){var n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(x(e))return t.stylize(""+e,"number");if(y(e))return t.stylize(""+e,"boolean");if(o(e))return t.stylize("null","null")}function d(e){return"["+Error.prototype.toString.call(e)+"]"}function P(n,e,i,a,s){var t=[];for(var r=0,o=e.length;r<o;++r){if(E(e,String(r))){t.push(m(n,e,i,a,String(r),true))}else{t.push("")}}s.forEach(function(r){if(!r.match(/^\d+$/)){t.push(m(n,e,i,a,r,true))}});return t}function m(n,s,l,f,a,u){var e,t,i;i=Object.getOwnPropertyDescriptor(s,a)||{value:s[a]};if(i.get){if(i.set){t=n.stylize("[Getter/Setter]","special")}else{t=n.stylize("[Getter]","special")}}else{if(i.set){t=n.stylize("[Setter]","special")}}if(!E(f,a)){e="["+a+"]"}if(!t){if(n.seen.indexOf(i.value)<0){if(o(l)){t=c(n,i.value,null)}else{t=c(n,i.value,l-1)}if(t.indexOf("\n")>-1){if(u){t=t.split("\n").map(function(e){return" "+e}).join("\n").substr(2)}else{t="\n"+t.split("\n").map(function(e){return" "+e}).join("\n")}}}else{t=n.stylize("[Circular]","special")}}if(r(e)){if(u&&a.match(/^\d+$/)){return t}e=JSON.stringify(""+a);if(e.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){e=e.substr(1,e.length-2);e=n.stylize(e,"name")}else{e=e.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");e=n.stylize(e,"string")}}return e+": "+t}function j(t,r,e){var n=0;var i=t.reduce(function(t,e){n++;if(e.indexOf("\n")>=0)n++;return t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(i>60){return e[0]+(r===""?"":r+"\n ")+" "+t.join(",\n ")+" "+e[1]}return e[0]+r+" "+t.join(", ")+" "+e[1]}function S(e){return Array.isArray(e)}e.isArray=S;function y(e){return typeof e==="boolean"}e.isBoolean=y;function o(e){return e===null}e.isNull=o;function T(e){return e==null}e.isNullOrUndefined=T;function x(e){return typeof e==="number"}e.isNumber=x;function p(e){return typeof e==="string"}e.isString=p;function k(e){return typeof e==="symbol"}e.isSymbol=k;function r(e){return e===void 0}e.isUndefined=r;function u(e){return i(e)&&v(e)==="[object RegExp]"}e.isRegExp=u;function i(e){return typeof e==="object"&&e!==null}e.isObject=i;function b(e){return i(e)&&v(e)==="[object Date]"}e.isDate=b;function s(e){return i(e)&&(v(e)==="[object Error]"||e instanceof Error)}e.isError=s;function l(e){return typeof e==="function"}e.isFunction=l;function L(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}e.isPrimitive=L;e.isBuffer=t("./support/isBuffer");function v(e){return Object.prototype.toString.call(e)}function h(e){return e<10?"0"+e.toString(10):e.toString(10)}var M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function O(){var e=new Date;var t=[h(e.getHours()),h(e.getMinutes()),h(e.getSeconds())].join(":");return[e.getDate(),M[e.getMonth()],t].join(" ")}e.log=function(){console.log("%s - %s",O(),e.format.apply(e,arguments))};e.inherits=t("inherits");e._extend=function(t,e){if(!e||!i(e))return t;var r=Object.keys(e);var n=r.length;while(n--){t[r[n]]=e[r[n]]}return t};function E(e,t){return Object.prototype.hasOwnProperty.call(e,t)}}).call(this,t("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":126,_process:112,inherits:109}],128:[function(t,e,r){(function(t){!function(t,F,n){"use strict";var M="Object",Er="Function",R="Array",ot="String",ut="Number",ht="RegExp",wt="Date",yr="Map",rr="Set",kr="WeakMap",pr="WeakSet",j="Symbol",Tt="Promise",er="Math",Ur="Arguments",i="prototype",Ft="constructor",G="toString",Ar=G+"Tag",ar="toLocaleString",qr="hasOwnProperty",ur="forEach",tt="iterator",At="@@"+tt,vr="process",gr="createElement",Sr=t[Er],s=t[M],L=t[R],m=t[ot],_r=t[ut],et=t[ht],Qr=t[wt],Wt=t[yr],fr=t[rr],Jt=t[kr],dr=t[pr],E=t[j],d=t[er],Pt=t.TypeError,Xr=t.setTimeout,Ot=t.setImmediate,zt=t.clearImmediate,Bt=t[vr],Lr=Bt&&Bt.nextTick,xt=t.document,jr=xt&&xt.documentElement,$r=t.navigator,Vt=t.define,p=L[i],T=s[i],gt=Sr[i],vt=1/0,yt=".";function c(e){return e!=null&&(typeof e=="object"||typeof e=="function")}function v(e){return typeof e=="function"}var st=l(/./.test,/\[native code\]\s*\}\s*$/,1);var Gr={Undefined:1,Null:1,Array:1,String:1,Arguments:1,Function:1,Error:1,Boolean:1,Number:1,Date:1,RegExp:1},Hr=T[G];function U(e,t,r){if(e&&!o(e=r?e:e[i],dt))a(e,dt,t)}function mt(e){return e==n?e===n?"Undefined":"Null":Hr.call(e).slice(8,-1)}function Nt(t){var r=mt(t),e;return r==M&&(e=t[dt])?o(Gr,e)?"~"+e:e:r}var $=gt.call,ir=gt.apply,K;function jt(){var e=arguments.length,r=L(e),t=0,n=lt._,i=false;while(e>t)if((r[t]=arguments[t++])===n)i=true;return or(this,r,e,i,n,false)}function or(e,t,n,r,i,a,s){N(e);return function(){var f=a?s:this,c=arguments.length,l=0,u=0,o;if(!r&&!c)return V(e,t,f);o=t.slice();if(r)for(;n>l;l++)if(o[l]===i)o[l]=arguments[u++];while(c>u)o.push(arguments[u++]);return V(e,o,f)}}function l(e,t,r){N(e);if(~r&&t===n)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,n){return e.call(t,r,n)};case 3:return function(r,n,i){return e.call(t,r,n,i)}}return function(){return e.apply(t,arguments)}}function V(t,e,r){var i=r===n;switch(e.length|0){case 0:return i?t():t.call(r);case 1:return i?t(e[0]):t.call(r,e[0]);case 2:return i?t(e[0],e[1]):t.call(r,e[0],e[1]);case 3:return i?t(e[0],e[1],e[2]):t.call(r,e[0],e[1],e[2]);case 4:return i?t(e[0],e[1],e[2],e[3]):t.call(r,e[0],e[1],e[2],e[3]);case 5:return i?t(e[0],e[1],e[2],e[3],e[4]):t.call(r,e[0],e[1],e[2],e[3],e[4])}return t.apply(r,e)}function Wr(e,n){var t=rt(e[i]),r=ir.call(e,t,n);return c(r)?r:t}var rt=s.create,nt=s.getPrototypeOf,Mt=s.setPrototypeOf,k=s.defineProperty,tn=s.defineProperties,J=s.getOwnPropertyDescriptor,bt=s.keys,nr=s.getOwnPropertyNames,wr=s.getOwnPropertySymbols,o=l($,T[qr],2),_t=s;function I(e){return _t(S(e))}function Rr(e){return e}function ft(){return this}function kt(e,t){if(o(e,t))return e[t]}function tr(e){return wr?nr(e).concat(wr(e)):nr(e)}var lr=s.assign||function(o,f){var e=s(S(o)),l=arguments.length,t=1;while(l>t){var r=_t(arguments[t++]),n=bt(r),u=n.length,i=0,a;while(u>i)e[a=n[i++]]=r[a]}return e};function Zt(i,a){var e=I(i),t=bt(e),s=t.length,r=0,n;while(s>r)if(e[n=t[r++]]===a)return n}function Q(e){return m(e).split(",")}var cr=p.push,Yr=p.unshift,Kr=p.slice,Zr=p.splice,en=p.indexOf,B=p[ur];function br(e){var r=e==1,a=e==2,o=e==3,t=e==4,i=e==6,u=e==5||i;return function(v){var h=s(S(this)),g=arguments[1],p=_t(h),b=l(v,g,3),y=w(p.length),f=0,d=r?L(y):a?[]:n,c,m;for(;y>f;f++)if(u||f in p){c=p[f];m=b(c,f,h);if(e){if(r)d[f]=m;else if(m)switch(e){case 3:return true;case 5:return c;case 6:return f;case 2:d.push(c)}else if(t)return false}}return i?-1:o||t?t:d}}function Vr(e){return function(n){var r=I(this),i=w(r.length),t=X(arguments[1],i);if(e&&n!=n){for(;i>t;t++)if(Gt(r[t]))return e||t}else for(;i>t;t++)if(e||t in r){if(r[t]===n)return e||t}return!e&&-1}}function It(e,t){return typeof e=="function"?e:t}var Ct=9007199254740991,Br=d.ceil,Ir=d.floor,Cr=d.max,q=d.min,Tr=d.random,Pr=d.trunc||function(e){return(e>0?Ir:Br)(e)};function Gt(e){return e!=e}function Lt(e){return isNaN(e)?0:Pr(e)}function w(e){return e>0?q(Lt(e),Ct):0}function X(e,t){var e=Lt(e);return e<0?Cr(e+t,0):q(e,t)}function Dt(t,e,r){var n=c(e)?function(t){return e[t]}:e;return function(e){return m(r?e:this).replace(t,n)}}function Xt(e){return function(o){var r=m(S(this)),t=Lt(o),s=r.length,i,a;if(t<0||t>=s)return e?"":n;i=r.charCodeAt(t);return i<55296||i>56319||t+1===s||(a=r.charCodeAt(t+1))<56320||a>57343?e?r.charAt(t):i:e?r.slice(t,t+2):(i-55296<<10)+(a-56320)+65536}}var Fr="Reduce of empty object with no initial value";function W(r,e,t){if(!r)throw Pt(t?e+t:e)}function S(e){if(e==n)throw Pt("Function called on null or undefined");return e}function N(e){W(v(e),e," is not a function!");return e}function P(e){W(c(e),e," is not an object!");return e}function Rt(e,t,r){W(e instanceof t,r,": use the 'new' operator!")}function Et(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}}function mr(e,t,r){e[t]=r;return e}function hr(e){return z?function(t,r,n){return k(t,r,Et(e,n))}:mr}function qt(e){return j+"("+e+")_"+(++Nr+Tr())[G](36)}function D(e,t){return E&&E[e]||(t?E:x)(j+yt+e)}var z=!!function(){try{return k({},yt,T)}catch(e){}}(),Nr=0,a=hr(1),b=E?mr:a,x=E||qt;function H(e,t){for(var r in t)a(e,r,t[r]);return e}var St=D("unscopables"),$t=p[St]||{};var it=D(tt),dt=D(Ar),Jr=At in p,f=x("iter"),O=1,C=2,Z={},Mr={},Dr=it in p,Or="keys"in p&&!("next"in[].keys());ct(Mr,ft);function ct(e,t){a(e,it,t);Jr&&a(e,At,t)}function at(e,t,r,n){e[i]=rt(n||Mr,{next:Et(1,r)});U(e,t+" Iterator")}function Ut(n,r,a,s){var e=n[i],t=kt(e,it)||kt(e,At)||s&&kt(e,s)||a;if(F){ct(e,t);if(t!==a){var l=nt(t.call(new n));U(l,r+" Iterator",true);o(e,At)&&ct(l,ft)}}Z[r]=t;Z[r+" Iterator"]=ft;return t}function Ht(a,e,s,l,o,u){function n(e){return function(){return new s(this,e)}}at(s,e,l);var i=n(O+C),t=n(C);if(o==C)t=Ut(a,e,t,"values");else i=Ut(a,e,i,"entries");if(o){r(A+y*Or,e,{entries:i,keys:u?t:n(O),values:t})}}function u(e,t){return{value:t,done:!!e}}function Yt(n){var e=s(n),r=t[j],i=!!(r&&r[tt]&&r[tt]in e);return i||it in e||o(Z,Nt(e))}function Y(e){var r=t[j],n=r&&r[tt]&&e[r[tt]],i=n||e[it]||Z[Nt(e)];return P(i.call(e))}function Qt(e,t,r){return r?V(e,t):e(t)}function pt(r,e,n,i){var a=Y(r),s=l(n,i,e?2:1),t;while(!(t=a.next()).done)if(Qt(s,t.value,e)===false)return}var xr=mt(Bt)==vr,g={},lt=F?t:g,zr=t.core,y=1,_=2,h=4,A=8,sr=16,Kt=32;function r(s,o,p){var r,f,e,u,c=s&_,n=c?t:s&h?t[o]:(t[o]||T)[i],d=c?g:g[o]||(g[o]={});if(c)p=o;for(r in p){f=!(s&y)&&n&&r in n&&(!v(n[r])||st(n[r]));e=(f?n:p)[r];if(s&sr&&f)u=l(e,t);else if(s&Kt&&!F&&n[r]==e){u=function(t){return this instanceof e?new e(t):e(t)};u[i]=e[i]}else u=s&A&&v(e)?l($,e):e;if(d[r]!=e)a(d,r,u);if(F&&n&&!f){if(c)n[r]=e;else delete n[r]&&a(n,r,e)}}}if(typeof e!="undefined"&&e.exports)e.exports=g;if(v(Vt)&&Vt.amd)Vt(function(){return g});if(!xr||F){g.noConflict=function(){t.core=zr;return g};t.core=g}r(_+y,{global:t});!function(n,e,t){if(!st(E)){E=function(r){W(!(this instanceof E),j+" is not a "+Ft);var e=qt(r);z&&t&&k(T,e,{configurable:true,set:function(t){a(this,e,t)}});return b(rt(E[i]),n,e)};a(E[i],G,function(){return this[n]})}r(_+Kt,{Symbol:E});var s={"for":function(t){return o(e,t+="")?e[t]:e[t]=E(t)},iterator:it,keyFor:jt.call(Zt,e),toStringTag:dt=D(Ar,true),unscopables:St,pure:x,set:b,useSetter:function(){t=true},useSimple:function(){t=false}};B.call(Q("hasInstance,isConcatSpreadable,match,replace,search,"+"species,split,toPrimitive"),function(e){s[e]=D(e)});r(h,j,s);U(E,j);r(_,{Reflect:{ownKeys:tr}})}(x("tag"),{},true);!function(D,j,nt,E){var K=t.RangeError,lt=_r.isInteger||function(e){return!c(e)&&j(e)&&Ir(e)===e},V=d.sign||function pt(e){return(e=+e)==0||e!=e?e:e<0?-1:1},tt=d.pow,rt=d.abs,v=d.exp,x=d.log,N=d.sqrt,ft=m.fromCharCode,ct=Xt(true);var it={assign:lr,is:function(e,t){return e===t?e!==0||1/e===1/t:e!=e&&t!=t}};"__proto__"in T&&function(t,e){try{e=l($,J(T,"__proto__").set,2);e({},p)}catch(r){t=true}it.setPrototypeOf=Mt=Mt||function(n,r){P(n);W(r===null||c(r),r,": can't set as prototype!");if(t)n.__proto__=r;else e(n,r);return n}}();r(h,M,it);function at(e){return!j(e=+e)||e==0?e:e<0?-at(-e):x(e+N(e*e+1))}r(h,ut,{EPSILON:tt(2,-52),isFinite:function(e){return typeof e=="number"&&j(e)},isInteger:lt,isNaN:Gt,isSafeInteger:function(e){return lt(e)&&rt(e)<=Ct},MAX_SAFE_INTEGER:Ct,MIN_SAFE_INTEGER:-Ct,parseFloat:parseFloat,parseInt:parseInt});r(h,er,{acosh:function(e){return e<1?NaN:x(e+N(e*e-1))},asinh:at,atanh:function(e){return e==0?+e:x((1+ +e)/(1-e))/2},cbrt:function(e){return V(e)*tt(rt(e),1/3)},clz32:function(e){return(e>>>=0)?32-e[G](2).length:32},cosh:function(e){return(v(e)+v(-e))/2},expm1:function(e){return e==0?+e:e>-1e-6&&e<1e-6?+e+e*e/2:v(e)-1},fround:function(e){return new Float32Array([e])[0]},hypot:function(n,i){var t=0,r=arguments.length,e;while(r--){e=+arguments[r];if(e==vt||e==-vt)return vt;t+=e*e}return N(t)},imul:function(a,s){var e=65535,t=+a,r=+s,n=e&t,i=e&r;return 0|n*i+((e&t>>>16)*i+n*(e&r>>>16)<<16>>>0)},log1p:function(e){return e>-1e-8&&e<1e-8?e-e*e/2:x(1+ +e)},log10:function(e){return x(e)/d.LN10},log2:function(e){return x(e)/d.LN2},sign:V,sinh:function(e){return e==0?+e:(v(e)-v(-e))/2},tanh:function(e){return j(e)?e==0?+e:(v(e)-v(-e))/(v(e)+v(-e)):V(e)},trunc:Pr});U(d,er,true);function H(e){if(mt(e)==ht)throw Pt()}r(h,ot,{fromCodePoint:function(i){var t=[],n=arguments.length,r=0,e;while(n>r){e=+arguments[r++];if(X(e,1114111)!==e)throw K(e+" is not a valid code point");t.push(e<65536?ft(e):ft(((e-=65536)>>10)+55296,e%1024+56320))}return t.join("")},raw:function(n){var r=I(n.raw),i=w(r.length),a=arguments.length,t=[],e=0;while(i>e){t.push(m(r[e++]));if(e<a)t.push(m(arguments[e]))}return t.join("")}});r(A,ot,{codePointAt:Xt(false),endsWith:function(e){H(e);var t=m(S(this)),r=arguments[1],i=w(t.length),a=r===n?i:q(w(r),i);e+="";return t.slice(a-e.length,a)===e},includes:function(e){H(e);return!!~m(S(this)).indexOf(e,arguments[1])},repeat:function(n){var t=m(S(this)),r="",e=Lt(n);if(0>e||e==vt)throw K("Count can't be negative");for(;e>0;(e>>>=1)&&(t+=t))if(e&1)r+=t;return r},startsWith:function(e){H(e);var t=m(S(this)),r=w(q(arguments[1],t.length));e+="";return t.slice(r,r+e.length)===e}});Ht(m,ot,function(e){b(this,f,{o:m(e),i:0})},function(){var e=this[f],r=e.o,n=e.i,t;if(n>=r.length)return u(1);t=ct.call(r,n);e.i+=t.length;return u(0,t)});r(h,R,{from:function(d){var t=s(S(d)),r=new(It(this,L)),u=arguments[1],c=arguments[2],i=u!==n,o=i?l(u,c,2):n,e=0,f;if(Yt(t))for(var p=Y(t),a;!(a=p.next()).done;e++){r[e]=i?o(a.value,e):a.value}else for(f=w(t.length);f>e;e++){r[e]=i?o(t[e],e):t[e]}r.length=e;return r},of:function(){var e=0,t=arguments.length,r=new(It(this,L))(t);while(t>e)r[e]=arguments[e++];r.length=t;return r}});r(A,R,{copyWithin:function(u,f){var r=s(S(this)),i=w(r.length),e=X(u,i),t=X(f,i),l=arguments[2],c=l===n?i:X(l,i),a=q(c-t,i-e),o=1;if(t<e&&e<t+a){o=-1;t=t+a-1;e=e+a-1}while(a-->0){if(t in r)r[e]=r[t];else delete r[e];e+=o;t+=o}return r},fill:function(a){var e=s(S(this)),t=w(e.length),r=X(arguments[1],t),i=arguments[2],o=i===n?t:X(i,t);while(o>r)e[r++]=a;return e},find:br(5),findIndex:br(6)});Ht(L,R,function(e,t){b(this,f,{o:I(e),i:0,k:t})},function(){var t=this[f],r=t.o,i=t.k,e=t.i++;if(!r||e>=r.length)return t.o=n,u(1);if(i==O)return u(0,e);if(i==C)return u(0,r[e]);return u(0,[e,r[e]])},C);Z[Ur]=Z[R];U(t.JSON,"JSON",true);function e(n,t){var e=s[n],i=g[M][n],a=0,o={};if(!i||st(i)){o[n]=t==1?function(t){return c(t)?e(t):t}:t==2?function(t){return c(t)?e(t):true}:t==3?function(t){return c(t)?e(t):false}:t==4?function(t,r){return e(I(t),r)}:function(t){return e(I(t))};try{e(yt)}catch(l){a=1}r(h+y*a,M,o)}}e("freeze",1);e("seal",1);e("preventExtensions",1);e("isFrozen",2);e("isSealed",2);e("isExtensible",3);e("getOwnPropertyDescriptor",4);e("getPrototypeOf");e("keys");e("getOwnPropertyNames");function _(e,t){return new et(mt(e)==ht&&t!==n?e.source:e,t)}if(F){nt[dt]=yt;if(mt(nt)!=yt)a(T,G,function(){return"[object "+Nt(this)+"]"});E in gt||k(gt,E,{configurable:true,get:function(){var e=m(this).match(/^\s*function ([^ (]*)/),t=e?e[1]:"";o(this,E)||k(this,E,Et(5,t));return t},set:function(e){o(this,E)||k(this,E,Et(0,e))}});if(z&&!function(){try{return et(/a/g,"i")=="/a/i"}catch(e){}}()){B.call(nr(et),function(e){e in _||k(_,e,{configurable:true,get:function(){return et[e]},set:function(t){et[e]=t}})});D[Ft]=_;_[i]=D;a(t,ht,_)}if(/./g.flags!="g")k(D,"flags",{configurable:true,get:Dt(/^.*\/(\w*)$/,"$1")});B.call(Q("find,findIndex,fill,copyWithin,entries,keys,values"),function(e){$t[e]=true});St in p||a(p,St,$t)}}(et[i],isFinite,{},"name");v(Ot)&&v(zt)||function(c){var p=t.postMessage,u=t.addEventListener,f=t.MessageChannel,i=0,r={},e,a,s;Ot=function(t){var n=[],a=1;while(arguments.length>a)n.push(arguments[a++]);r[++i]=function(){V(v(t)?t:Sr(t),n)};e(i);return i};zt=function(e){delete r[e]};function n(e){if(o(r,e)){var t=r[e];delete r[e];t()}}function d(e){n(e.data)}if(xr){e=function(e){Lr(jt.call(n,e))}}else if(u&&v(p)&&!t.importScripts){e=function(e){p(e,"*")};u("message",d,false)}else if(v(f)){a=new f;s=a.port2;a.port1.onmessage=d;e=l(s.postMessage,s,1)}else if(xt&&c in xt[gr]("script")){e=function(e){jr.appendChild(xt[gr]("script"))[c]=function(){jr.removeChild(this);n(e)}}}else{e=function(e){Xr(jt.call(n,e),0)}}}("onreadystatechange");r(_+sr,{setImmediate:Ot,clearImmediate:zt});!function(e,t){v(e)&&v(e.resolve)&&e.resolve(t=new e(function(){}))==t||function(f,s){function o(t){var e;if(c(t))e=t.then;return v(e)?e:false}function r(t){var e=t.chain;e.length&&f(function(){var r=t.msg,i=t.state==1,n=0;while(e.length>n)!function(e){var n=i?e.ok:e.fail,t,a;try{if(n){t=n===true?r:n(r);if(t===e.P){e.rej(Pt(Tt+"-chain cycle"))}else if(a=o(t)){a.call(t,e.res,e.rej)}else e.res(t)}else e.rej(r)}catch(s){e.rej(s)}}(e[n++]);e.length=0})}function u(i){var e=this,a,n;if(e.done)return;e.done=true;e=e.def||e;try{if(a=o(i)){n={def:e,done:false};a.call(i,l(u,n,1),l(t,n,1))}else{e.msg=i;e.state=1;r(e)}}catch(s){t.call(n||{def:e,done:false},s)}}function t(t){var e=this;if(e.done)return;e.done=true;e=e.def||e;e.msg=t;e.state=2;r(e)}e=function(i){N(i);Rt(this,e,Tt);var r={chain:[],state:0,done:false,msg:n};a(this,s,r);try{i(l(u,r,1),l(t,r,1))}catch(o){t.call(r,o)}};H(e[i],{then:function(n,i){var e={ok:v(n)?n:true,fail:v(i)?i:false},a=e.P=new this[Ft](function(t,r){e.res=N(t);e.rej=N(r)}),t=this[s];t.chain.push(e);t.state&&r(t);return a},"catch":function(e){return this.then(n,e)}});H(e,{all:function(r){var t=this,e=[];return new t(function(a,s){pt(r,false,cr,e);var n=e.length,i=L(n);if(n)B.call(e,function(e,r){t.resolve(e).then(function(e){i[r]=e;--n||a(i)},s)});else a(i)})},race:function(t){var e=this;return new e(function(r,n){pt(t,false,function(t){e.resolve(t).then(r,n)})})},reject:function(e){return new this(function(r,t){t(e)})},resolve:function(e){return c(e)&&nt(e)===this[i]?e:new this(function(t,r){t(e)})}})}(Lr||Ot,x("def"));U(e,Tt);r(_+y*!st(e),{Promise:e})}(t[Tt]);!function(){var e=x("uid"),p=x("data"),t=x("weak"),d=x("last"),s=x("first"),m=z?x("size"):"size",g=0;function v(t,l,L,P,h,c){var x=h?"set":"add",E=t&&t[i],T={};function w(e,t){if(t!=n)pt(t,h,e[x],e);return e}function v(e,t){var r=E[e];F&&a(E,e,function(e,n){var i=r.call(this,e===0?0:e,n);
return t?this:i})}if(!st(t)||!(c||!Or&&o(E,"entries"))){t=c?function(r){Rt(this,t,l);b(this,e,g++);w(this,r)}:function(r){var e=this;Rt(e,t,l);b(e,p,rt(null));b(e,m,0);b(e,d,n);b(e,s,n);w(e,r)};H(H(t[i],L),P);c||k(t[i],"size",{get:function(){return S(this[m])}})}else{var j=t,I=new t,M=I[x](c?{}:-0,1),A;if(!Dr||!t.length){t=function(e){Rt(this,t,l);return w(new j,e)};t[i]=E}c||I[ur](function(t,e){A=1/e===-vt});if(A){v("delete");v("has");h&&v("get")}if(A||M!==I)v(x,true)}U(t,l);T[l]=t;r(_+Kt+y*!st(t),T);c||Ht(t,l,function(e,t){b(this,f,{o:e,k:t})},function(){var t=this[f],r=t.o,i=t.k,e=t.l;while(e&&e.r)e=e.p;if(!r||!(t.l=e=e?e.n:r[s]))return t.o=n,u(1);if(i==O)return u(0,e.k);if(i==C)return u(0,e.v);return u(0,[e.k,e.v])},h?O+C:C,!h);return t}function h(t,r){if(!c(t))return(typeof t=="string"?"S":"P")+t;if(!o(t,e)){if(r)a(t,e,++g);else return""}return"O"+t[e]}function E(e,a,o){var r=h(a,true),n=e[p],i=e[d],t;if(r in n)n[r].v=o;else{t=n[r]={k:a,v:o,p:i};if(!e[s])e[s]=t;if(i)i.n=t;e[d]=t;e[m]++}return e}function w(e,i){var a=e[p],t=a[i],r=t.n,n=t.p;delete a[i];t.r=true;if(n)n.n=r;if(r)r.p=n;if(e[s]==t)e[s]=r;if(e[d]==t)e[d]=n;e[m]--}var I={clear:function(){for(var e in this[p])w(this,e)},"delete":function(r){var e=h(r),t=e in this[p];if(t)w(this,e);return t},forEach:function(t){var r=l(t,arguments[1],3),e;while(e=e?e.n:this[s]){r(e.v,e.k,this);while(e&&e.r)e=e.p}},has:function(e){return h(e)in this[p]}};Wt=v(Wt,yr,{get:function(t){var e=this[p][h(t)];return e&&e.v},set:function(e,t){return E(this,e===0?0:e,t)}},I,true);fr=v(fr,rr,{add:function(e){return E(this,e=e===0?0:e,e)}},I);function A(n,r,i){o(P(r),t)||a(r,t,{});r[t][n[e]]=i;return n}function T(r){return c(r)&&o(r,t)&&o(r[t],this[e])}var L={"delete":function(r){return T.call(this,r)&&delete r[t][this[e]]},has:T};Jt=v(Jt,kr,{get:function(r){if(c(r)&&o(r,t))return r[t][this[e]]},set:function(e,t){return A(this,e,t)}},L,true,true);dr=v(dr,pr,{add:function(e){return A(this,e,true)}},L,false,true)}();!function(){function e(e){var t=[],r;for(r in e)t.push(r);b(this,f,{o:e,a:t,i:0})}at(e,M,function(){var e=this[f],t=e.a,r;do{if(e.i>=t.length)return u(1)}while(!((r=t[e.i++])in e.o));return u(0,r)});function t(e){return function(t){P(t);try{return e.apply(n,arguments),true}catch(r){return false}}}function i(t,r){var a=arguments.length<3?t:arguments[2],e=J(P(t),r),s;if(e)return e.get?e.get.call(a):e.value;return c(s=nt(t))?i(s,r,a):n}function a(n,t,i){var r=arguments.length<4?n:arguments[3],e=J(P(n),t),s;if(e){if(e.writable===false)return false;if(e.set)return e.set.call(r,i),true}if(c(s=nt(n)))return a(s,t,i,r);e=J(r,t)||Et(0);e.value=i;return k(r,t,e),true}var o={apply:l($,ir,3),construct:Wr,defineProperty:t(k),deleteProperty:function(e,t){var r=J(P(e),t);return r&&!r.configurable?false:delete e[t]},enumerate:function(t){return new e(P(t))},get:i,getOwnPropertyDescriptor:J,getPrototypeOf:nt,has:function(e,t){return t in e},isExtensible:s.isExtensible||function(e){return!!P(e)},ownKeys:tr,preventExtensions:t(s.preventExtensions||Rr),set:a};if(Mt)o.setPrototypeOf=function(e,t){return Mt(P(e),t),true};r(_,{Reflect:{}});r(h,"Reflect",o)}();!function(){r(A,R,{includes:Vr(true)});r(A,ot,{at:Xt(true)});function e(e){return function(a){var s=I(a),r=bt(a),n=r.length,t=0,i=L(n),o;if(e)while(n>t)i[t]=[o=r[t++],s[o]];else while(n>t)i[t]=s[r[t++]];return i}}r(h,M,{values:e(false),entries:e(true)});r(h,ht,{escape:Dt(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(e){K=D(e+"Get",true);var t=D(e+rr,true),n=D(e+"Delete",true);r(h,j,{referenceGet:K,referenceSet:t,referenceDelete:n});a(gt,K,ft);function s(r){if(r){var e=r[i];a(e,K,e.get);a(e,t,e.set);a(e,n,e["delete"])}}s(Wt);s(Jt)}("reference");!function(v){function t(e){var t=rt(null);if(e!=n){if(Yt(e)){for(var a=Y(e),i,r;!(i=a.next()).done;){r=i.value;t[r[0]]=r[1]}}else lr(t,e)}return t}t[i]=null;function d(e,t){b(this,f,{o:I(e),a:bt(e),i:0,k:t})}at(d,v,function(){var e=this[f],r=e.o,n=e.a,i=e.k,t;do{if(e.i>=n.length)return u(1)}while(!o(r,t=n[e.i++]));if(i==O)return u(0,t);if(i==C)return u(0,r[t]);return u(0,[t,r[t]])});function a(e){return function(t){return new d(t,e)}}function e(e){var i=e==1,r=e==4;return function(p,d,m){var h=l(d,m,3),c=I(p),u=i||e==7||e==2?new(It(this,t)):n,a,f,s;for(a in c)if(o(c,a)){f=c[a];s=h(f,a,p);if(e){if(i)u[a]=s;else if(s)switch(e){case 2:u[a]=f;break;case 3:return true;case 5:return f;case 6:return a;case 7:u[s[0]]=s[1]}else if(r)return false}}return e==3||r?r:u}}function m(e){return function(p,d,a){N(d);var i=I(p),l=bt(i),m=l.length,u=0,r,f,c;if(e)r=a==n?new(It(this,t)):s(a);else if(arguments.length<3){W(m,Fr);r=i[l[u++]]}else r=s(a);while(m>u)if(o(i,f=l[u++])){c=d(r,i[f],f,p);if(e){if(c===false)break}else r=c}return r}}var h=e(6);function g(t,e){return(e==e?Zt(t,e):h(t,Gt))!==n}var p={keys:a(O),values:a(C),entries:a(O+C),forEach:e(0),map:e(1),filter:e(2),some:e(3),every:e(4),find:e(5),findKey:h,mapPairs:e(7),reduce:m(false),turn:m(true),keyOf:Zt,includes:g,has:o,get:kt,set:hr(0),isDict:function(e){return c(e)&&nt(e)===t[i]}};if(K)for(var E in p)!function(e){function t(){for(var t=[this],r=0;r<arguments.length;)t.push(arguments[r++]);return V(e,t)}e[K]=function(){return t}}(p[E]);r(_+y,{Dict:H(t,p)})}("Dict");!function(e,a){function t(r,n){if(!(this instanceof t))return new t(r,n);this[f]=Y(r);this[e]=!!n}at(t,"Wrapper",function(){return this[f].next()});var s=t[i];ct(s,function(){return this[f]});function o(r){function t(t,r,n){this[f]=Y(t);this[e]=t[e];this[a]=l(r,n,t[e]?2:1)}at(t,"Chain",r,s);ct(t[i],ft);return t}var c=o(function(){var t=this[f].next();return t.done?t:u(0,Qt(this[a],t.value,this[e]))});var p=o(function(){for(;;){var t=this[f].next();if(t.done||Qt(this[a],t.value,this[e]))return t}});H(s,{of:function(t,r){pt(this,this[e],t,r)},array:function(e,r){var t=[];pt(e!=n?this.map(e,r):this,false,cr,t);return t},filter:function(e,t){return new p(this,e,t)},map:function(e,t){return new c(this,e,t)}});t.isIterable=Yt;t.getIterator=Y;r(_+y,{$for:t})}("entries",x("fn"));!function(e,i){g._=lt._=lt._||{};r(A+y,Er,{part:jt,by:function(s){var e=this,i=lt._,o=false,t=arguments.length,u=s===i,r=+!u,f=r,n,a;if(u){n=e;e=$}else n=s;if(t<2)return l(e,n,-1);a=L(t-f);while(t>r)if((a[r-f]=arguments[r++])===i)o=true;return or(e,a,t,o,i,true,n)},only:function(e,t){var r=N(this),n=w(e),i=arguments.length>1;return function(){var a=q(n,arguments.length),s=L(a),e=0;while(a>e)s[e]=arguments[e++];return V(r,s,i?t:this)}}});function t(s){var t=this,r={};return a(t,e,function(e){if(e===n||!(e in t))return i.call(t);return o(r,e)?r[e]:r[e]=l(t[e],t,-1)})[e](s)}a(lt._,G,function(){return e});a(T,e,t);z||a(p,e,t)}(z?qt("tie"):ar,T[ar]);!function(){function e(e,t){var r=tr(I(t)),a=r.length,n=0,i;while(a>n)k(e,i=r[n++],J(t,i));return e}r(h+y,M,{isObject:c,classof:Nt,define:e,make:function(t,r){return e(rt(t),r)}})}();r(A+y,R,{turn:function(t,r){N(t);var i=r==n?[]:s(r),a=_t(this),o=w(a.length),e=0;while(o>e)if(t(i,a[e],e++,this)===false)break;return i}});if(F)$t.turn=true;!function(t){function e(e,r){B.call(Q(e),function(e){if(e in p)t[e]=l($,p[e],r)})}e("pop,reverse,shift,keys,values,entries",1);e("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);e("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");r(h,R,t)}({});!function(e){function t(e){b(this,f,{l:w(e),i:0})}at(t,ut,function(){var e=this[f],t=e.i++;return t<e.l?u(0,t):u(1)});Ut(_r,ut,function(){return new t(this)});e.random=function(e){var t=+this,r=e==n?0:+e,i=q(t,r);return Tr()*(Cr(t,r)-i)+i};B.call(Q("round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,"+"acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc"),function(t){var r=d[t];if(r)e[t]=function(){var e=[+this],t=0;while(arguments.length>t)e.push(arguments[t++]);return V(r,e)}});r(A+y,ut,e)}({});!function(){var e={"&":"&","<":"<",">":">",'"':""","'":"'"},n={},t;for(t in e)n[e[t]]=t;r(A+y,ot,{escapeHTML:Dt(/[&<>"']/g,e),unescapeHTML:Dt(/&(?:amp|lt|gt|quot|apos);/g,n)})}();!function(d,p,t,n,u,s,l,i,f){function c(r){return function(h,p){var y=this,c=t[o(t,p)?p:n];function a(e){return y[r+e]()}return m(h).replace(d,function(t){switch(t){case"s":return a(u);case"ss":return e(a(u));case"m":return a(s);case"mm":return e(a(s));case"h":return a(l);case"hh":return e(a(l));case"D":return a(wt);case"DD":return e(a(wt));case"W":return c[0][a("Day")];case"N":return a(i)+1;case"NN":return e(a(i)+1);case"M":return c[2][a(i)];case"MM":return c[1][a(i)];case"Y":return a(f);case"YY":return e(a(f)%100)}return t})}}function e(e){return e>9?e:"0"+e}function a(n,e){function r(r){var t=[];B.call(Q(e.months),function(e){t.push(e.replace(p,"$"+r))});return t}t[n]=[Q(e.weekdays),r(1),r(2)];return g}r(A+y,wt,{format:c("get"),formatUTC:c("getUTC")});a(n,{weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",months:"January,February,March,April,May,June,July,August,September,October,November,December"});a("ru",{weekdays:"Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота",months:"Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,"+"Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь"});g.locale=function(e){return o(t,e)?n=e:n};g.addLocale=a}(/\b\w\w?\b/g,/:(.*)\|(.*)$/,{},"en","Seconds","Minutes","Hours","Month","FullYear")}(typeof window!="undefined"&&window.Math===Math?window:t,false)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],129:[function(r,n,t){(function(n,r){"use strict";if(typeof e==="function"&&e.amd){e(["exports"],r)}else if(typeof t!=="undefined"){r(t)}else{r(n.estraverse={})}})(this,function(a){"use strict";var f,s,o,p,h,u,t,n,i;function v(){}s=Array.isArray;if(!s){s=function I(e){return Object.prototype.toString.call(e)==="[object Array]"}}function d(r){var n={},e,t;for(e in r){if(r.hasOwnProperty(e)){t=r[e];if(typeof t==="object"&&t!==null){n[e]=d(t)}else{n[e]=t}}}return n}function k(t){var r={},e;for(e in t){if(t.hasOwnProperty(e)){r[e]=t[e]}}return r}v(k);function x(i,a){var t,e,r,n;e=i.length;r=0;while(e){t=e>>>1;n=r+t;if(a(i[n])){e=t}else{r=n+1;e-=t+1}}return r}function g(i,a){var t,e,r,n;e=i.length;r=0;while(e){t=e>>>1;n=r+t;if(a(i[n])){r=n+1;e-=t+1}else{e=t}}return r}v(g);h=Object.create||function(){function e(){}return function(t){e.prototype=t;return new e}}();u=Object.keys||function(r){var e=[],t;for(t in r){e.push(t)}return e};function b(e,t){u(t).forEach(function(r){e[r]=t[r]});return e}f={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"};p={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]};t={};n={};i={};o={Break:t,Skip:n,Remove:i};function l(e,t){this.parent=e;this.key=t}l.prototype.replace=function C(e){this.parent[this.key]=e};l.prototype.remove=function A(){if(s(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function r(e,t,r,n){this.node=e;this.path=t;this.wrap=r;this.ref=n}function e(){}e.prototype.path=function T(){var e,n,t,i,r,a;function o(r,e){if(s(e)){for(t=0,i=e.length;t<i;++t){r.push(e[t])}}else{r.push(e)}}if(!this.__current.path){return null}r=[];for(e=2,n=this.__leavelist.length;e<n;++e){a=this.__leavelist[e];o(r,a.path)}o(r,this.__current.path);return r};e.prototype.type=function(){var e=this.current();return e.type||this.__current.wrap};e.prototype.parents=function P(){var e,r,t;t=[];for(e=1,r=this.__leavelist.length;e<r;++e){t.push(this.__leavelist[e].node)}return t};e.prototype.current=function L(){return this.__current.node};e.prototype.__execute=function _(t,r){var n,e;e=undefined;n=this.__current;this.__current=r;this.__state=null;if(t){e=t.call(this,r.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=n;return e};e.prototype.notify=function j(e){this.__state=e};e.prototype.skip=function(){this.notify(n)};e.prototype["break"]=function(){this.notify(t)};e.prototype.remove=function(){this.notify(i)};e.prototype.__initialize=function(t,e){this.visitor=e;this.root=t;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=e.fallback==="iteration";this.__keys=p;if(e.keys){this.__keys=b(h(this.__keys),e.keys)}};function c(e){if(e==null){return false}return typeof e==="object"&&typeof e.type==="string"}function y(e,t){return(e===f.ObjectExpression||e===f.ObjectPattern)&&"properties"===t}e.prototype.traverse=function M(E,b){var o,h,e,d,v,f,p,m,a,l,i,g;this.__initialize(E,b);g={};o=this.__worklist;h=this.__leavelist;o.push(new r(E,null,null,null));h.push(new r(null,null,null,null));while(o.length){e=o.pop();if(e===g){e=h.pop();f=this.__execute(b.leave,e);if(this.__state===t||f===t){return}continue}if(e.node){f=this.__execute(b.enter,e);if(this.__state===t||f===t){return}o.push(g);h.push(e);if(this.__state===n||f===n){continue}d=e.node;v=e.wrap||d.type;l=this.__keys[v];if(!l){if(this.__fallback){l=u(d)}else{throw new Error("Unknown node type "+v+".")}}m=l.length;while((m-=1)>=0){p=l[m];i=d[p];if(!i){continue}if(s(i)){a=i.length;while((a-=1)>=0){if(!i[a]){continue}if(y(v,l[m])){e=new r(i[a],[p,a],"Property",null)}else if(c(i[a])){e=new r(i[a],[p,a],null,null)}else{continue}o.push(e)}}else if(c(i)){o.push(new r(i,p,null,null))}}}}};e.prototype.replace=function O(x,S){function k(t){var r,n,e,i;if(t.ref.remove()){n=t.ref.key;i=t.ref.parent;r=p.length;while(r--){e=p[r];if(e.ref&&e.ref.parent===i){if(e.ref.key<n){break}--e.ref.key}}}}var p,E,m,g,a,e,b,f,d,o,w,v,h;this.__initialize(x,S);w={};p=this.__worklist;E=this.__leavelist;v={root:x};e=new r(x,null,null,new l(v,"root"));p.push(e);E.push(e);while(p.length){e=p.pop();if(e===w){e=E.pop();a=this.__execute(S.leave,e);if(a!==undefined&&a!==t&&a!==n&&a!==i){e.ref.replace(a)}if(this.__state===i||a===i){k(e)}if(this.__state===t||a===t){return v.root}continue}a=this.__execute(S.enter,e);if(a!==undefined&&a!==t&&a!==n&&a!==i){e.ref.replace(a);e.node=a}if(this.__state===i||a===i){k(e);e.node=null}if(this.__state===t||a===t){return v.root}m=e.node;if(!m){continue}p.push(w);E.push(e);if(this.__state===n||a===n){continue}g=e.wrap||m.type;d=this.__keys[g];if(!d){if(this.__fallback){d=u(m)}else{throw new Error("Unknown node type "+g+".")}}b=d.length;while((b-=1)>=0){h=d[b];o=m[h];if(!o){continue}if(s(o)){f=o.length;while((f-=1)>=0){if(!o[f]){continue}if(y(g,d[b])){e=new r(o[f],[h,f],"Property",new l(o,f))}else if(c(o[f])){e=new r(o[f],[h,f],null,new l(o,f))}else{continue}p.push(e)}}else if(c(o)){p.push(new r(o,h,null,new l(m,h)))}}}return v.root};function m(t,r){var n=new e;return n.traverse(t,r)}function S(t,r){var n=new e;return n.replace(t,r)}function w(e,r){var t;t=x(r,function n(t){return t.range[0]>e.range[0]});e.extendedRange=[e.range[0],e.range[1]];if(t!==r.length){e.extendedRange[1]=r[t].range[0]}t-=1;if(t>=0){e.extendedRange[0]=r[t].range[1]}return e}function E(n,i,l){var t=[],s,a,r,e;if(!n.range){throw new Error("attachComments needs range information")}if(!l.length){if(i.length){for(r=0,a=i.length;r<a;r+=1){s=d(i[r]);s.extendedRange=[0,n.range[0]];t.push(s)}n.leadingComments=t}return n}for(r=0,a=i.length;r<a;r+=1){t.push(w(d(i[r]),l))}e=0;m(n,{enter:function(r){var n;while(e<t.length){n=t[e];if(n.extendedRange[1]>r.range[0]){break}if(n.extendedRange[1]===r.range[0]){if(!r.leadingComments){r.leadingComments=[]}r.leadingComments.push(n);t.splice(e,1)}else{e+=1}}if(e===t.length){return o.Break}if(t[e].extendedRange[0]>r.range[1]){return o.Skip}}});e=0;m(n,{leave:function(r){var n;while(e<t.length){n=t[e];if(r.range[1]<n.extendedRange[0]){break}if(r.range[1]===n.extendedRange[0]){if(!r.trailingComments){r.trailingComments=[]}r.trailingComments.push(n);t.splice(e,1)}else{e+=1}}if(e===t.length){return o.Break}if(t[e].extendedRange[0]>r.range[1]){return o.Skip}}});return n}a.version="1.8.0";a.Syntax=f;a.traverse=m;a.replace=S;a.attachComments=E;a.VisitorKeys=p;a.VisitorOption=o;a.Controller=e})},{}],130:[function(t,e,r){(function(){"use strict";function n(e){if(e==null){return false}switch(e.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return true}return false}function i(e){if(e==null){return false}switch(e.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return true}return false}function t(e){if(e==null){return false}switch(e.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return true}return false}function a(e){return t(e)||e!=null&&e.type==="FunctionDeclaration"}function r(e){switch(e.type){case"IfStatement":if(e.alternate!=null){return e.alternate}return e.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return e.body}return null}function s(t){var e;if(t.type!=="IfStatement"){return false}if(t.alternate==null){return false}e=t.consequent;do{if(e.type==="IfStatement"){if(e.alternate==null){return true}}e=r(e)}while(e);return false}e.exports={isExpression:n,isStatement:t,isIterationStatement:i,isSourceElement:a,isProblematicIfStatement:s,trailingStatement:r}})()},{}],131:[function(t,e,r){(function(){"use strict";var t,r;t={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")};function n(e){return e>=48&&e<=57}function i(e){return n(e)||97<=e&&e<=102||65<=e&&e<=70}function a(e){return e>=48&&e<=55}r=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279];function s(e){return e===32||e===9||e===11||e===12||e===160||e>=5760&&r.indexOf(e)>=0}function o(e){return e===10||e===13||e===8232||e===8233}function l(e){return e>=97&&e<=122||e>=65&&e<=90||e===36||e===95||e===92||e>=128&&t.NonAsciiIdentifierStart.test(String.fromCharCode(e))}function u(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===36||e===95||e===92||e>=128&&t.NonAsciiIdentifierPart.test(String.fromCharCode(e))}e.exports={isDecimalDigit:n,isHexDigit:i,isOctalDigit:a,isWhiteSpace:s,isLineTerminator:o,isIdentifierStart:l,isIdentifierPart:u}})()},{}],132:[function(e,t,r){(function(){"use strict";var i=e("./code");function l(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return true;default:return false}}function a(e,t){if(!t&&e==="yield"){return false}return r(e,t)}function r(e,t){if(t&&l(e)){return true}switch(e.length){case 2:return e==="if"||e==="in"||e==="do";case 3:return e==="var"||e==="for"||e==="new"||e==="try";case 4:return e==="this"||e==="else"||e==="case"||e==="void"||e==="with"||e==="enum";case 5:return e==="while"||e==="break"||e==="catch"||e==="throw"||e==="const"||e==="yield"||e==="class"||e==="super";case 6:return e==="return"||e==="typeof"||e==="delete"||e==="switch"||e==="export"||e==="import";case 7:return e==="default"||e==="finally"||e==="extends";case 8:return e==="function"||e==="continue"||e==="debugger";case 10:return e==="instanceof";default:return false}}function s(e,t){return e==="null"||e==="true"||e==="false"||a(e,t)}function o(e,t){return e==="null"||e==="true"||e==="false"||r(e,t)}function u(e){return e==="eval"||e==="arguments"}function n(t){var r,n,e;if(t.length===0){return false}e=t.charCodeAt(0);if(!i.isIdentifierStart(e)||e===92){return false}for(r=1,n=t.length;r<n;++r){e=t.charCodeAt(r);if(!i.isIdentifierPart(e)||e===92){return false}}return true}function f(e,t){return n(e)&&!s(e,t)}function c(e,t){return n(e)&&!o(e,t)}t.exports={isKeywordES5:a,isKeywordES6:r,isReservedWordES5:s,isReservedWordES6:o,isRestrictedWord:u,isIdentifierName:n,isIdentifierES5:f,isIdentifierES6:c}})()},{"./code":131}],133:[function(e,r,t){(function(){"use strict";t.ast=e("./ast");t.code=e("./code");t.keyword=e("./keyword")})()},{"./ast":130,"./code":131,"./keyword":132}],134:[function(t,r,e){"use strict";e.reservedVars={arguments:false,NaN:false};e.ecmaIdentifiers={Array:false,Boolean:false,Date:false,decodeURI:false,decodeURIComponent:false,encodeURI:false,encodeURIComponent:false,Error:false,eval:false,EvalError:false,Function:false,hasOwnProperty:false,isFinite:false,isNaN:false,JSON:false,Map:false,Math:false,Number:false,Object:false,Proxy:false,Promise:false,parseInt:false,parseFloat:false,RangeError:false,ReferenceError:false,RegExp:false,Set:false,String:false,SyntaxError:false,TypeError:false,URIError:false,WeakMap:false,WeakSet:false};e.newEcmaIdentifiers={Set:false,Map:false,WeakMap:false,WeakSet:false,Proxy:false,Promise:false,Reflect:false,Symbol:false,System:false};e.browser={Audio:false,Blob:false,addEventListener:false,applicationCache:false,atob:false,blur:false,btoa:false,cancelAnimationFrame:false,CanvasGradient:false,CanvasPattern:false,CanvasRenderingContext2D:false,CSS:false,clearInterval:false,clearTimeout:false,close:false,closed:false,CustomEvent:false,DOMParser:false,defaultStatus:false,Document:false,document:false,Element:false,ElementTimeControl:false,Event:false,event:false,FileReader:false,FormData:false,focus:false,frames:false,getComputedStyle:false,HTMLElement:false,HTMLAnchorElement:false,HTMLBaseElement:false,HTMLBlockquoteElement:false,HTMLBodyElement:false,HTMLBRElement:false,HTMLButtonElement:false,HTMLCanvasElement:false,HTMLDirectoryElement:false,HTMLDivElement:false,HTMLDListElement:false,HTMLFieldSetElement:false,HTMLFontElement:false,HTMLFormElement:false,HTMLFrameElement:false,HTMLFrameSetElement:false,HTMLHeadElement:false,HTMLHeadingElement:false,HTMLHRElement:false,HTMLHtmlElement:false,HTMLIFrameElement:false,HTMLImageElement:false,HTMLInputElement:false,HTMLIsIndexElement:false,HTMLLabelElement:false,HTMLLayerElement:false,HTMLLegendElement:false,HTMLLIElement:false,HTMLLinkElement:false,HTMLMapElement:false,HTMLMenuElement:false,HTMLMetaElement:false,HTMLModElement:false,HTMLObjectElement:false,HTMLOListElement:false,HTMLOptGroupElement:false,HTMLOptionElement:false,HTMLParagraphElement:false,HTMLParamElement:false,HTMLPreElement:false,HTMLQuoteElement:false,HTMLScriptElement:false,HTMLSelectElement:false,HTMLStyleElement:false,HTMLTableCaptionElement:false,HTMLTableCellElement:false,HTMLTableColElement:false,HTMLTableElement:false,HTMLTableRowElement:false,HTMLTableSectionElement:false,HTMLTextAreaElement:false,HTMLTitleElement:false,HTMLUListElement:false,HTMLVideoElement:false,history:false,Image:false,Intl:false,length:false,localStorage:false,location:false,matchMedia:false,MessageChannel:false,MessageEvent:false,MessagePort:false,MouseEvent:false,moveBy:false,moveTo:false,MutationObserver:false,name:false,Node:false,NodeFilter:false,NodeList:false,navigator:false,onbeforeunload:true,onblur:true,onerror:true,onfocus:true,onload:true,onresize:true,onunload:true,open:false,openDatabase:false,opener:false,Option:false,parent:false,print:false,requestAnimationFrame:false,removeEventListener:false,resizeBy:false,resizeTo:false,screen:false,scroll:false,scrollBy:false,scrollTo:false,sessionStorage:false,setInterval:false,setTimeout:false,SharedWorker:false,status:false,SVGAElement:false,SVGAltGlyphDefElement:false,SVGAltGlyphElement:false,SVGAltGlyphItemElement:false,SVGAngle:false,SVGAnimateColorElement:false,SVGAnimateElement:false,SVGAnimateMotionElement:false,SVGAnimateTransformElement:false,SVGAnimatedAngle:false,SVGAnimatedBoolean:false,SVGAnimatedEnumeration:false,SVGAnimatedInteger:false,SVGAnimatedLength:false,SVGAnimatedLengthList:false,SVGAnimatedNumber:false,SVGAnimatedNumberList:false,SVGAnimatedPathData:false,SVGAnimatedPoints:false,SVGAnimatedPreserveAspectRatio:false,SVGAnimatedRect:false,SVGAnimatedString:false,SVGAnimatedTransformList:false,SVGAnimationElement:false,SVGCSSRule:false,SVGCircleElement:false,SVGClipPathElement:false,SVGColor:false,SVGColorProfileElement:false,SVGColorProfileRule:false,SVGComponentTransferFunctionElement:false,SVGCursorElement:false,SVGDefsElement:false,SVGDescElement:false,SVGDocument:false,SVGElement:false,SVGElementInstance:false,SVGElementInstanceList:false,SVGEllipseElement:false,SVGExternalResourcesRequired:false,SVGFEBlendElement:false,SVGFEColorMatrixElement:false,SVGFEComponentTransferElement:false,SVGFECompositeElement:false,SVGFEConvolveMatrixElement:false,SVGFEDiffuseLightingElement:false,SVGFEDisplacementMapElement:false,SVGFEDistantLightElement:false,SVGFEFloodElement:false,SVGFEFuncAElement:false,SVGFEFuncBElement:false,SVGFEFuncGElement:false,SVGFEFuncRElement:false,SVGFEGaussianBlurElement:false,SVGFEImageElement:false,SVGFEMergeElement:false,SVGFEMergeNodeElement:false,SVGFEMorphologyElement:false,SVGFEOffsetElement:false,SVGFEPointLightElement:false,SVGFESpecularLightingElement:false,SVGFESpotLightElement:false,SVGFETileElement:false,SVGFETurbulenceElement:false,SVGFilterElement:false,SVGFilterPrimitiveStandardAttributes:false,SVGFitToViewBox:false,SVGFontElement:false,SVGFontFaceElement:false,SVGFontFaceFormatElement:false,SVGFontFaceNameElement:false,SVGFontFaceSrcElement:false,SVGFontFaceUriElement:false,SVGForeignObjectElement:false,SVGGElement:false,SVGGlyphElement:false,SVGGlyphRefElement:false,SVGGradientElement:false,SVGHKernElement:false,SVGICCColor:false,SVGImageElement:false,SVGLangSpace:false,SVGLength:false,SVGLengthList:false,SVGLineElement:false,SVGLinearGradientElement:false,SVGLocatable:false,SVGMPathElement:false,SVGMarkerElement:false,SVGMaskElement:false,SVGMatrix:false,SVGMetadataElement:false,SVGMissingGlyphElement:false,SVGNumber:false,SVGNumberList:false,SVGPaint:false,SVGPathElement:false,SVGPathSeg:false,SVGPathSegArcAbs:false,SVGPathSegArcRel:false,SVGPathSegClosePath:false,SVGPathSegCurvetoCubicAbs:false,SVGPathSegCurvetoCubicRel:false,SVGPathSegCurvetoCubicSmoothAbs:false,SVGPathSegCurvetoCubicSmoothRel:false,SVGPathSegCurvetoQuadraticAbs:false,SVGPathSegCurvetoQuadraticRel:false,SVGPathSegCurvetoQuadraticSmoothAbs:false,SVGPathSegCurvetoQuadraticSmoothRel:false,SVGPathSegLinetoAbs:false,SVGPathSegLinetoHorizontalAbs:false,SVGPathSegLinetoHorizontalRel:false,SVGPathSegLinetoRel:false,SVGPathSegLinetoVerticalAbs:false,SVGPathSegLinetoVerticalRel:false,SVGPathSegList:false,SVGPathSegMovetoAbs:false,SVGPathSegMovetoRel:false,SVGPatternElement:false,SVGPoint:false,SVGPointList:false,SVGPolygonElement:false,SVGPolylineElement:false,SVGPreserveAspectRatio:false,SVGRadialGradientElement:false,SVGRect:false,SVGRectElement:false,SVGRenderingIntent:false,SVGSVGElement:false,SVGScriptElement:false,SVGSetElement:false,SVGStopElement:false,SVGStringList:false,SVGStylable:false,SVGStyleElement:false,SVGSwitchElement:false,SVGSymbolElement:false,SVGTRefElement:false,SVGTSpanElement:false,SVGTests:false,SVGTextContentElement:false,SVGTextElement:false,SVGTextPathElement:false,SVGTextPositioningElement:false,SVGTitleElement:false,SVGTransform:false,SVGTransformList:false,SVGTransformable:false,SVGURIReference:false,SVGUnitTypes:false,SVGUseElement:false,SVGVKernElement:false,SVGViewElement:false,SVGViewSpec:false,SVGZoomAndPan:false,TextDecoder:false,TextEncoder:false,TimeEvent:false,top:false,URL:false,WebGLActiveInfo:false,WebGLBuffer:false,WebGLContextEvent:false,WebGLFramebuffer:false,WebGLProgram:false,WebGLRenderbuffer:false,WebGLRenderingContext:false,WebGLShader:false,WebGLShaderPrecisionFormat:false,WebGLTexture:false,WebGLUniformLocation:false,WebSocket:false,window:false,Worker:false,XDomainRequest:false,XMLHttpRequest:false,XMLSerializer:false,XPathEvaluator:false,XPathException:false,XPathExpression:false,XPathNamespace:false,XPathNSResolver:false,XPathResult:false};
e.devel={alert:false,confirm:false,console:false,Debug:false,opera:false,prompt:false};e.worker={importScripts:true,postMessage:true,self:true,FileReaderSync:true};e.nonstandard={escape:false,unescape:false};e.couch={require:false,respond:false,getRow:false,emit:false,send:false,start:false,sum:false,log:false,exports:false,module:false,provides:false};e.node={__filename:false,__dirname:false,GLOBAL:false,global:false,module:false,require:false,Buffer:true,console:true,exports:true,process:true,setTimeout:true,clearTimeout:true,setInterval:true,clearInterval:true,setImmediate:true,clearImmediate:true};e.browserify={__filename:false,__dirname:false,global:false,module:false,require:false,Buffer:true,exports:true,process:true};e.phantom={phantom:true,require:true,WebPage:true,console:true,exports:true};e.qunit={asyncTest:false,deepEqual:false,equal:false,expect:false,module:false,notDeepEqual:false,notEqual:false,notPropEqual:false,notStrictEqual:false,ok:false,propEqual:false,QUnit:false,raises:false,start:false,stop:false,strictEqual:false,test:false,"throws":false};e.rhino={defineClass:false,deserialize:false,gc:false,help:false,importClass:false,importPackage:false,java:false,load:false,loadClass:false,Packages:false,print:false,quit:false,readFile:false,readUrl:false,runCommand:false,seal:false,serialize:false,spawn:false,sync:false,toint32:false,version:false};e.shelljs={target:false,echo:false,exit:false,cd:false,pwd:false,ls:false,find:false,cp:false,rm:false,mv:false,mkdir:false,test:false,cat:false,sed:false,grep:false,which:false,dirs:false,pushd:false,popd:false,env:false,exec:false,chmod:false,config:false,error:false,tempdir:false};e.typed={ArrayBuffer:false,ArrayBufferView:false,DataView:false,Float32Array:false,Float64Array:false,Int16Array:false,Int32Array:false,Int8Array:false,Uint16Array:false,Uint32Array:false,Uint8Array:false,Uint8ClampedArray:false};e.wsh={ActiveXObject:true,Enumerator:true,GetObject:true,ScriptEngine:true,ScriptEngineBuildVersion:true,ScriptEngineMajorVersion:true,ScriptEngineMinorVersion:true,VBArray:true,WSH:true,WScript:true,XDomainRequest:true};e.dojo={dojo:false,dijit:false,dojox:false,define:false,require:false};e.jquery={$:false,jQuery:false};e.mootools={$:false,$$:false,Asset:false,Browser:false,Chain:false,Class:false,Color:false,Cookie:false,Core:false,Document:false,DomReady:false,DOMEvent:false,DOMReady:false,Drag:false,Element:false,Elements:false,Event:false,Events:false,Fx:false,Group:false,Hash:false,HtmlTable:false,IFrame:false,IframeShim:false,InputValidator:false,instanceOf:false,Keyboard:false,Locale:false,Mask:false,MooTools:false,Native:false,Options:false,OverText:false,Request:false,Scroller:false,Slick:false,Slider:false,Sortables:false,Spinner:false,Swiff:false,Tips:false,Type:false,typeOf:false,URI:false,Window:false};e.prototypejs={$:false,$$:false,$A:false,$F:false,$H:false,$R:false,$break:false,$continue:false,$w:false,Abstract:false,Ajax:false,Class:false,Enumerable:false,Element:false,Event:false,Field:false,Form:false,Hash:false,Insertion:false,ObjectRange:false,PeriodicalExecuter:false,Position:false,Prototype:false,Selector:false,Template:false,Toggle:false,Try:false,Autocompleter:false,Builder:false,Control:false,Draggable:false,Draggables:false,Droppables:false,Effect:false,Sortable:false,SortableObserver:false,Sound:false,Scriptaculous:false};e.yui={YUI:false,Y:false,YUI_config:false};e.mocha={describe:false,it:false,before:false,after:false,beforeEach:false,afterEach:false,suite:false,test:false,setup:false,teardown:false};e.jasmine={jasmine:false,describe:false,it:false,xit:false,beforeEach:false,afterEach:false,setFixtures:false,loadFixtures:false,spyOn:false,expect:false,runs:false,waitsFor:false,waits:false}},{}],135:[function(n,t,r){(function(n){(function(){var f;var L=[],M=[];var Z=0;var T=+new Date+"";var _=75;var U=40;var F=" \f "+"\n\r\u2028\u2029"+" ";var X=/\b__p \+= '';/g,rt=/\b(__p \+=) '' \+/g,tt=/(__e\(.*?\)|\b__t\)) \+\n'';/g;var et=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;var Q=/\w*$/;var K=/^\s*function[ \n\r\t]+\w/;var B=/<%=([\s\S]+?)%>/g;var nt=RegExp("^["+F+"]*0+(?=.$)");var k=/($^)/;var D=/\bthis\b/;var H=/['\n\r\t\u2028\u2029\\]/g;var J=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"];var G=0;var x="[object Arguments]",S="[object Array]",E="[object Boolean]",b="[object Date]",V="[object Function]",g="[object Number]",u="[object Object]",v="[object RegExp]",m="[object String]";var l={};l[V]=false;l[x]=l[S]=l[E]=l[b]=l[g]=l[u]=l[v]=l[m]=true;var C={leading:false,maxWait:0,trailing:false};var R={configurable:false,enumerable:false,value:null,writable:false};var a={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};var q={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};var p=a[typeof window]&&window||this;var w=a[typeof r]&&r&&!r.nodeType&&r;var A=a[typeof t]&&t&&!t.nodeType&&t;var Y=A&&A.exports===w&&w;var d=a[typeof n]&&n;if(d&&(d.global===d||d.window===d)){p=d}function h(e,r,n){var t=(n||0)-1,i=e?e.length:0;while(++t<i){if(e[t]===r){return t}}return-1}function I(e,r){var t=typeof r;e=e.cache;if(t=="boolean"||r==null){return e[r]?0:-1}if(t!="number"&&t!="string"){t="object"}var n=t=="number"?r:T+r;e=(e=e[t])&&e[n];return t=="object"?e&&h(e,r)>-1?0:-1:e?0:-1}function W(t){var r=this.cache,e=typeof t;if(e=="boolean"||t==null){r[t]=true}else{if(e!="number"&&e!="string"){e="object"}var n=e=="number"?t:T+t,i=r[e]||(r[e]={});if(e=="object"){(i[n]||(i[n]=[])).push(t)}else{i[n]=true}}}function N(e){return e.charCodeAt(0)}function z(n,i){var a=n.criteria,s=i.criteria,r=-1,o=a.length;while(++r<o){var e=a[r],t=s[r];if(e!==t){if(e>t||typeof e=="undefined"){return 1}if(e<t||typeof t=="undefined"){return-1}}}return n.index-i.index}function j(e){var i=-1,n=e.length,a=e[0],s=e[n/2|0],o=e[n-1];if(a&&typeof a=="object"&&s&&typeof s=="object"&&o&&typeof o=="object"){return false}var t=O();t["false"]=t["null"]=t["true"]=t["undefined"]=false;var r=O();r.array=e;r.cache=t;r.push=W;while(++i<n){r.push(e[i])}return r}function $(e){return"\\"+q[e]}function o(){return L.pop()||[]}function O(){return M.pop()||{array:null,cache:null,criteria:null,"false":false,index:0,"null":false,number:null,object:null,push:null,string:null,"true":false,undefined:false,value:null}}function s(e){e.length=0;if(L.length<U){L.push(e)}}function y(e){var t=e.cache;if(t){y(t)}e.array=e.cache=e.criteria=e.object=e.number=e.string=e.value=null;if(M.length<U){M.push(e)}}function i(t,e,r){e||(e=0);if(typeof r=="undefined"){r=t?t.length:0}var n=-1,i=r-e||0,a=Array(i<0?0:i);while(++n<i){a[n]=t[e+n]}return a}function P(t){t=t?c.defaults(p.Object(),t,c.pick(p,J)):p;var W=t.Array,ai=t.Boolean,Qt=t.Date,Rt=t.Function,At=t.Math,ni=t.Number,ht=t.Object,Ct=t.RegExp,lt=t.String,st=t.TypeError;var yt=[];var ir=ht.prototype;var ri=t._;var A=ir.toString;var ei=Ct("^"+lt(A).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var Zn=At.ceil,_t=t.clearTimeout,Un=At.floor,Rn=Rt.prototype.toString,mt=ft(mt=ht.getPrototypeOf)&&mt,L=ir.hasOwnProperty,gt=yt.push,xt=t.setTimeout,fr=yt.splice,On=yt.unshift;var pr=function(){try{var t={},e=ft(e=ht.defineProperty)&&e,r=e(t,t,t)&&e}catch(n){}return r}();var Pt=ft(Pt=ht.create)&&Pt,Jt=ft(Jt=W.isArray)&&Jt,Mn=t.isFinite,Ln=t.isNaN,jt=ft(jt=ht.keys)&&jt,Y=At.max,Et=At.min,er=t.parseInt,lr=At.random;var ot={};ot[S]=W;ot[E]=ai;ot[b]=Qt;ot[V]=Rt;ot[u]=ht;ot[g]=ni;ot[v]=Ct;ot[m]=lt;function e(e){return e&&typeof e=="object"&&!d(e)&&L.call(e,"__wrapped__")?e:new pt(e)}function pt(e,t){this.__chain__=!!t;this.__wrapped__=e}pt.prototype=e.prototype;var kt=e.support={};kt.funcDecomp=!ft(t.WinRTError)&&D.test(P);kt.funcNames=typeof Rt.name=="string";e.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:B,variable:"",imports:{_:e}};function Tn(e){var t=e[0],n=e[2],a=e[4];function r(){if(n){var e=i(n);gt.apply(e,arguments)}if(this instanceof r){var s=vt(t.prototype),o=t.apply(s,e||arguments);return w(o)?o:s}return t.apply(a,e||arguments)}Wt(r,e);return r}function Zt(e,c,h,n,a){if(h){var t=h(e);if(typeof t!="undefined"){return t}}var S=w(e);if(S){var p=A.call(e);if(!l[p]){return e}var u=ot[p];switch(p){case E:case b:return new u(+e);case g:case m:return new u(e);case v:t=u(e.source,Q.exec(e));t.lastIndex=e.lastIndex;return t}}else{return e}var f=d(e);if(c){var x=!n;n||(n=o());a||(a=o());var y=n.length;while(y--){if(n[y]==e){return a[y]}}t=f?u(e.length):{}}else{t=f?i(e):Nt({},e)}if(f){if(L.call(e,"index")){t.index=e.index}if(L.call(e,"input")){t.input=e.input}}if(!c){return t}n.push(e);a.push(t);(f?M:r)(e,function(e,r){t[r]=Zt(e,c,h,n,a)});if(x){s(n);s(a)}return t}function vt(e,t){return w(e)?Pt(e):{}}if(!Pt){vt=function(){function e(){}return function(r){if(w(r)){e.prototype=r;var n=new e;e.prototype=null}return n||t.Object()}}()}function q(e,r,i){if(typeof e!="function"){return Gt}if(typeof r=="undefined"||!("prototype"in e)){return e}var t=e.__bindData__;if(typeof t=="undefined"){if(kt.funcNames){t=!e.name}t=t||!kt.funcDecomp;if(!t){var n=Rn.call(e);if(!kt.funcNames){t=!K.test(n)}if(!t){t=D.test(n);Wt(e,t)}}}if(t===false||t!==true&&t[1]&1){return e}switch(i){case 1:return function(t){return e.call(r,t)};case 2:return function(t,n){return e.call(r,t,n)};case 3:return function(t,n,i){return e.call(r,t,n,i)};case 4:return function(t,n,i,a){return e.call(r,t,n,i,a)}}return yr(e,r)}function kr(e){var r=e[0],t=e[1],o=e[2],a=e[3],s=e[4],u=e[5];var f=t&1,c=t&2,l=t&4,p=t&8,d=r;function n(){var m=f?s:this;if(o){var e=i(o);gt.apply(e,arguments)}if(a||l){e||(e=i(arguments));if(a){gt.apply(e,a)}if(l&&e.length<u){t|=16&~32;return kr([r,p?t:t&~3,e,null,s,u])}}e||(e=arguments);if(c){r=m[d]}if(this instanceof n){m=vt(r.prototype);var h=r.apply(m,e);return w(h)?h:m}return r.apply(m,e)}Wt(n,e);return n}function bt(t,e){var i=-1,r=Lt(),a=t?t.length:0,n=a>=_&&r===h,s=[];if(n){var o=j(e);if(o){r=I;e=o}else{n=false}}while(++i<a){var l=t[i];if(r(e,l)<0){s.push(l)}}if(n){y(e)}return s}function ut(r,a,n,u){var i=(u||0)-1,f=r?r.length:0,t=[];while(++i<f){var e=r[i];if(e&&typeof e=="object"&&typeof e.length=="number"&&(d(e)||Tt(e))){if(!a){e=ut(e,a,n)}var s=-1,o=e.length,l=t.length;t.length+=o;while(++s<o){t[l++]=e[s]}}else if(!n){t.push(e)}}return t}function dt(e,t,h,c,r,l){if(h){var i=h(e,t);if(typeof i!="undefined"){return!!i}}if(e===t){return e!==0||1/e==1/t}var O=typeof e,M=typeof t;if(e===e&&!(e&&a[O])&&!(t&&a[M])){return false}if(e==null||t==null){return e===t}var d=A.call(e),k=A.call(t);if(d==x){d=u}if(k==x){k=u}if(d!=k){return false}switch(d){case E:case b:return+e==+t;case g:return e!=+e?t!=+t:e==0?1/e==1/t:e==+t;case v:case m:return e==lt(t)}var T=d==S;if(!T){var C=L.call(e,"__wrapped__"),I=L.call(t,"__wrapped__");if(C||I){return dt(C?e.__wrapped__:e,I?t.__wrapped__:t,h,c,r,l)}if(d!=u){return false}var w=e.constructor,y=t.constructor;if(w!=y&&!(n(w)&&w instanceof w&&n(y)&&y instanceof y)&&("constructor"in e&&"constructor"in t)){return false}}var j=!r;r||(r=o());l||(l=o());var p=r.length;while(p--){if(r[p]==e){return l[p]==t}}var f=0;i=true;r.push(e);l.push(t);if(T){p=e.length;f=t.length;i=f==p;if(i||c){while(f--){var P=p,_=t[f];if(c){while(P--){if(i=dt(e[P],_,h,c,r,l)){break}}}else if(!(i=dt(e[f],_,h,c,r,l))){break}}}}else{at(t,function(n,t,a){if(L.call(a,t)){f++;return i=L.call(e,t)&&dt(e[t],n,h,c,r,l)}});if(i&&!c){at(e,function(r,e,t){if(L.call(t,e)){return i=--f>-1}})}}r.pop();l.pop();if(j){s(r);s(l)}return i}function sr(i,a,e,t,n){(d(a)?M:r)(a,function(a,u){var f,c,s=a,r=i[u];if(a&&((c=d(a))||tr(a))){var o=t.length;while(o--){if(f=t[o]==a){r=n[o];break}}if(!f){var l;if(e){s=e(r,a);if(l=typeof s!="undefined"){r=s}}if(!l){r=c?d(r)?r:[]:tr(r)?r:{}}t.push(a);n.push(r);if(!l){sr(r,a,e,t,n)}}}else{if(e){s=e(r,a);if(typeof s=="undefined"){s=a}}if(typeof s!="undefined"){r=s}}i[u]=r})}function Kt(e,t){return e+Un(lr()*(t-e+1))}function $t(r,c,t){var n=-1,u=Lt(),p=r?r.length:0,f=[];var i=!c&&p>=_&&u===h,e=t||i?o():f;if(i){var d=j(e);u=I;e=d}while(++n<p){var a=r[n],l=t?t(a,n,r):a;if(c?!n||e[e.length-1]!==l:u(e,l)<0){if(t||i){e.push(l)}f.push(a)}}if(i){s(e.array);y(e)}else if(t){s(e)}return f}function Yt(t){return function(n,i,u){var a={};i=e.createCallback(i,u,3);var s=-1,o=n?n.length:0;if(typeof o=="number"){while(++s<o){var l=n[s];t(a,l,i(l,s,n),n)}}else{r(n,function(e,n,r){t(a,e,i(e,n,r),r)})}return a}}function it(r,t,a,s,u,f){var c=t&1,m=t&2,p=t&4,h=t&8,o=t&16,l=t&32;if(!m&&!n(r)){throw new st}if(o&&!a.length){t&=~16;o=a=false}if(l&&!s.length){t&=~32;l=s=false}var e=r&&r.__bindData__;if(e&&e!==true){e=i(e);if(e[2]){e[2]=i(e[2])}if(e[3]){e[3]=i(e[3])}if(c&&!(e[1]&1)){e[4]=u}if(!c&&e[1]&1){t|=8}if(p&&!(e[1]&4)){e[5]=f}if(o){gt.apply(e[2]||(e[2]=[]),a)}if(l){On.apply(e[3]||(e[3]=[]),s)}e[1]|=t;return it.apply(null,e)}var d=t==1||t===17?Tn:kr;return d([r,t,a,s,u,f])}function An(e){return Bt[e]}function Lt(){var t=(t=e.indexOf)===br?h:t;return t}function ft(e){return typeof e=="function"&&ei.test(e)}var Wt=!pr?or:function(e,t){R.value=t;pr(e,"__bindData__",R)};function gr(e){var t,r;if(!(e&&A.call(e)==u)||(t=e.constructor,n(t)&&!(t instanceof t))){return false}at(e,function(t,e){r=e});return typeof r=="undefined"||L.call(e,r)}function bn(e){return Ar[e]}function Tt(e){return e&&typeof e=="object"&&typeof e.length=="number"&&A.call(e)==x||false}var d=Jt||function(e){return e&&typeof e=="object"&&typeof e.length=="number"&&A.call(e)==S||false};var vn=function(n){var t,r=n,e=[];if(!r)return e;if(!a[typeof n])return e;for(t in r){if(L.call(r,t)){e.push(t)}}return e};var U=!jt?vn:function(e){if(!w(e)){return[]}return jt(e)};var Bt={"&":"&","<":"<",">":">",'"':""","'":"'"};var Ar=vr(Bt);var un=Ct("("+U(Ar).join("|")+")","g"),on=Ct("["+U(Bt).join("")+"]","g");var Nt=function(f,d,c){var n,e=f,i=e;if(!e)return i;var r=arguments,l=0,t=typeof c=="number"?2:r.length;if(t>3&&typeof r[t-2]=="function"){var o=q(r[--t-1],r[t--],2)}else if(t>2&&typeof r[t-1]=="function"){o=r[--t]}while(++l<t){e=r[l];if(e&&a[typeof e]){var u=-1,s=a[typeof e]&&U(e),p=s?s.length:0;while(++u<p){n=s[u];i[n]=o?o(i[n],e[n]):e[n]}}}return i};function nn(n,e,t,r){if(typeof e!="boolean"&&e!=null){r=t;t=e;e=false}return Zt(n,e,typeof t=="function"&&q(t,r,1))}function rn(t,e,r){return Zt(t,true,typeof e=="function"&&q(e,r,1))}function tn(r,e){var t=vt(r);return e?Nt(t,e):t}var Ut=function(l,p,f){var t,e=l,r=e;if(!e)return r;var i=arguments,s=0,u=typeof f=="number"?2:i.length;while(++s<u){e=i[s];if(e&&a[typeof e]){var o=-1,n=a[typeof e]&&U(e),c=n?n.length:0;while(++o<c){t=n[o];if(typeof r[t]=="undefined")r[t]=e[t]}}}return r};function Zr(i,t,a){var n;t=e.createCallback(t,a,3);r(i,function(r,e,i){if(t(r,e,i)){n=e;return false}});return n}function Qr(n,t,i){var r;t=e.createCallback(t,i,3);mr(n,function(n,e,i){if(t(n,e,i)){r=e;return false}});return r}var at=function(i,e,s){var n,t=i,r=t;if(!t)return r;if(!a[typeof t])return r;e=e&&typeof s=="undefined"?e:q(e,s,3);for(n in t){if(e(t[n],n,i)===false)return r}return r};function zr(t,r,i){var e=[];at(t,function(t,r){e.push(r,t)});var n=e.length;r=q(r,i,3);while(n--){if(r(e[n--],e[n],t)===false){break}}return t}var r=function(s,t,o){var n,e=s,r=e;if(!e)return r;if(!a[typeof e])return r;t=t&&typeof o=="undefined"?t:q(t,o,3);var l=-1,i=a[typeof e]&&U(e),u=i?i.length:0;while(++l<u){n=i[l];if(t(e[n],n,s)===false)return r}return r};function mr(e,t,a){var r=U(e),n=r.length;t=q(t,a,3);while(n--){var i=r[n];if(t(e[i],i,e)===false){break}}return e}function It(t){var e=[];at(t,function(t,r){if(n(t)){e.push(r)}});return e.sort()}function Hr(e,t){return e?L.call(e,t):false}function vr(e){var t=-1,r=U(e),a=r.length,n={};while(++t<a){var i=r[t];n[e[i]]=i}return n}function Jr(e){return e===true||e===false||e&&typeof e=="object"&&A.call(e)==E||false}function Gr(e){return e&&typeof e=="object"&&A.call(e)==b||false}function Xr(e){return e&&e.nodeType===1||false}function Ur(e){var i=true;if(!e){return i}var t=A.call(e),a=e.length;if(t==S||t==m||t==x||t==u&&typeof a=="number"&&n(e.splice)){return!a}r(e,function(){return i=false});return i}function Br(t,r,e,n){return dt(t,r,typeof e=="function"&&q(e,n,2))}function _r(e){return Mn(e)&&!Ln(parseFloat(e))}function n(e){return typeof e=="function"}function w(e){return!!(e&&a[typeof e])}function wn(e){return Tr(e)&&e!=+e}function Lr(e){return e===null}function Tr(e){return typeof e=="number"||e&&typeof e=="object"&&A.call(e)==g||false}var tr=!mt?gr:function(e){if(!(e&&A.call(e)==u)){return false}var r=e.valueOf,t=ft(r)&&(t=mt(r))&&mt(t);return t?e==t||mt(e)==t:gr(e)};function yi(e){return e&&typeof e=="object"&&A.call(e)==v||false}function St(e){return typeof e=="string"||e&&typeof e=="object"&&A.call(e)==m||false}function jr(e){return typeof e=="undefined"}function Mr(i,t,a){var n={};t=e.createCallback(t,a,3);r(i,function(r,e,i){n[e]=t(r,e,i)});return n}function Or(r){var t=arguments,e=2;if(!w(r)){return r}if(typeof t[2]!="number"){e=t.length}if(e>3&&typeof t[e-2]=="function"){var n=q(t[--e-1],t[e--],2)}else if(e>2&&typeof t[e-1]=="function"){n=t[--e]}var f=i(arguments,1,e),a=-1,l=o(),u=o();while(++a<e){sr(r,f[a],n,l,u)}s(l);s(u);return r}function Dr(n,r,o){var i={};if(typeof r!="function"){var t=[];at(n,function(r,e){t.push(e)});t=bt(t,ut(arguments,true,false,1));var a=-1,l=t.length;while(++a<l){var s=t[a];i[s]=n[s]}}else{r=e.createCallback(r,o,3);at(n,function(e,t,n){if(!r(e,t,n)){i[t]=e}})}return i}function Rr(t){var e=-1,r=U(t),n=r.length,i=W(n);while(++e<n){var a=r[e];i[e]=[a,t[a]]}return i}function Nr(t,r,o){var n={};if(typeof r!="function"){var a=-1,s=ut(arguments,true,false,1),l=w(t)?s.length:0;while(++a<l){var i=s[a];if(i in t){n[i]=t[i]}}}else{r=e.createCallback(r,o,3);at(t,function(e,t,i){if(r(e,t,i)){n[t]=e}})}return n}function Fr(n,i,t,o){var a=d(n);if(t==null){if(a){t=[]}else{var s=n&&n.constructor,l=s&&s.prototype;t=vt(l)}}if(i){i=e.createCallback(i,o,4);(a?M:r)(n,function(e,r,n){return i(t,e,r,n)})}return t}function Mt(t){var e=-1,r=U(t),n=r.length,i=W(n);while(++e<n){i[e]=t[r[e]]}return i}function Vr(r){var e=arguments,t=-1,n=ut(e,true,false,1),i=e[2]&&e[2][e[1]]===r?1:n.length,a=W(i);while(++t<i){a[t]=r[n[t]]}return a}function xr(e,n,t){var o=-1,a=Lt(),s=e?e.length:0,i=false;t=(t<0?Y(0,s+t):t)||0;if(d(e)){i=a(e,n,t)>-1}else if(typeof s=="number"){i=(St(e)?e.indexOf(n,t):a(e,n,t))>-1}else{r(e,function(e){if(++o>=t){return!(i=e===n)}})}return i}var qr=Yt(function(e,r,t){L.call(e,t)?e[t]++:e[t]=1});function Er(t,n,o){var i=true;n=e.createCallback(n,o,3);var a=-1,s=t?t.length:0;if(typeof s=="number"){while(++a<s){if(!(i=!!n(t[a],a,t))){break}}}else{r(t,function(e,t,r){return i=!!n(e,t,r)})}return i}function Dt(t,n,l){var i=[];n=e.createCallback(n,l,3);var a=-1,s=t?t.length:0;if(typeof s=="number"){while(++a<s){var o=t[a];if(n(o,a,t)){i.push(o)}}}else{r(t,function(e,t,r){if(n(e,t,r)){i.push(e)}})}return i}function zt(t,n,l){n=e.createCallback(n,l,3);var i=-1,a=t?t.length:0;if(typeof a=="number"){while(++i<a){var s=t[i];if(n(s,i,t)){return s}}}else{var o;r(t,function(e,t,r){if(n(e,t,r)){o=e;return false}});return o}}function Wr(n,t,i){var r;t=e.createCallback(t,i,3);Ot(n,function(e,n,i){if(t(e,n,i)){r=e;return false}});return r}function M(e,t,i){var n=-1,a=e?e.length:0;t=t&&typeof i=="undefined"?t:q(t,i,3);if(typeof a=="number"){while(++n<a){if(t(e[n],n,e)===false){break}}}else{r(e,t)}return e}function Ot(e,n,a){var t=e?e.length:0;n=n&&typeof a=="undefined"?n:q(n,a,3);if(typeof t=="number"){while(t--){if(n(e[t],t,e)===false){break}}}else{var i=U(e);t=i.length;r(e,function(a,e,r){e=i?i[--t]:--t;return n(r[e],e,r)})}return e}var Yr=Yt(function(e,r,t){(L.call(e,t)?e[t]:e[t]=[]).push(r)});var $r=Yt(function(e,t,r){e[r]=t});function Kr(e,t){var a=i(arguments,2),s=-1,o=typeof t=="function",r=e?e.length:0,n=W(typeof r=="number"?r:0);M(e,function(e){n[++s]=(o?t:e[t]).apply(e,a)});return n}function wt(t,i,o){var n=-1,s=t?t.length:0;i=e.createCallback(i,o,3);if(typeof s=="number"){var a=W(s);while(++n<s){a[n]=i(t[n],n,t)}}else{a=[];r(t,function(e,t,r){a[++n]=i(e,t,r)})}return a}function ur(r,t,i){var a=-Infinity,n=a;if(typeof t!="function"&&i&&i[t]===r){t=null}if(t==null&&d(r)){var s=-1,l=r.length;while(++s<l){var o=r[s];if(o>n){n=o}}}else{t=t==null&&St(r)?N:e.createCallback(t,i,3);M(r,function(e,i,s){var r=t(e,i,s);if(r>a){a=r;n=e}})}return n}function en(r,t,i){var a=Infinity,n=a;if(typeof t!="function"&&i&&i[t]===r){t=null}if(t==null&&d(r)){var s=-1,l=r.length;while(++s<l){var o=r[s];if(o<n){n=o}}}else{t=t==null&&St(r)?N:e.createCallback(t,i,3);M(r,function(e,i,s){var r=t(e,i,s);if(r<a){a=r;n=e}})}return n}var Vt=wt;function Ht(n,i,t,l){if(!n)return t;var s=arguments.length<3;i=e.createCallback(i,l,4);var a=-1,o=n.length;if(typeof o=="number"){if(s){t=n[++a]}while(++a<o){t=i(t,n[a],a,n)}}else{r(n,function(e,r,n){t=s?(s=false,e):i(t,e,r,n)})}return t}function ar(i,t,r,a){var n=arguments.length<3;t=e.createCallback(t,a,4);Ot(i,function(e,i,a){r=n?(n=false,e):t(r,e,i,a)});return r}function an(r,t,n){t=e.createCallback(t,n,3);return Dt(r,function(e,r,n){return!t(e,r,n)})}function sn(e,r,n){if(e&&typeof e.length!="number"){e=Mt(e)}if(r==null||n){return e?e[Kt(0,e.length-1)]:f}var t=nr(e);t.length=Et(Y(0,r),t.length);return t}function nr(t){var r=-1,n=t?t.length:0,e=W(typeof n=="number"?n:0);M(t,function(n){var t=Kt(0,++r);e[r]=e[t];e[t]=n});return e}function ln(e){var t=e?e.length:0;return typeof t=="number"?t:U(e).length}function rr(t,n,o){var i;n=e.createCallback(n,o,3);var a=-1,s=t?t.length:0;if(typeof s=="number"){while(++a<s){if(i=n(t[a],a,t)){break}}}else{r(t,function(e,t,r){return!(i=n(e,t,r))})}return!!i}function fn(i,n,f){var u=-1,a=d(n),t=i?i.length:0,r=W(typeof t=="number"?t:0);if(!a){n=e.createCallback(n,f,3)}M(i,function(t,i,s){var e=r[++u]=O();if(a){e.criteria=wt(n,function(e){return t[e]})}else{(e.criteria=o())[0]=n(t,i,s)}e.index=u;e.value=t});t=r.length;r.sort(z);while(t--){var l=r[t];r[t]=l.value;if(!a){s(l.criteria)}y(l)}return r}function cn(e){if(e&&typeof e.length=="number"){return i(e)}return Mt(e)}var pn=Dt;function dn(e){var t=-1,i=e?e.length:0,r=[];while(++t<i){var n=e[t];if(n){r.push(n)}}return r}function mn(e){return bt(e,ut(arguments,true,true,1))}function hn(t,n,i){var r=-1,a=t?t.length:0;n=e.createCallback(n,i,3);while(++r<a){if(n(t[r],r,t)){return r}}return-1}function yn(t,n,i){var r=t?t.length:0;n=e.createCallback(n,i,3);while(r--){if(n(t[r],r,t)){return r}}return-1}function Xt(t,r,s){var n=0,o=t?t.length:0;if(typeof r!="number"&&r!=null){var a=-1;r=e.createCallback(r,s,3);while(++a<o&&r(t[a],a,t)){n++}}else{n=r;if(n==null||s){return t?t[0]:f}}return i(t,0,Et(Y(0,n),o))}function gn(t,e,r,n){if(typeof e!="boolean"&&e!=null){n=r;r=typeof e!="function"&&n&&n[e]===t?null:e;e=false}if(r!=null){t=wt(t,r,n)}return ut(t,e)}function br(t,r,e){if(typeof e=="number"){var i=t?t.length:0;e=e<0?Y(0,i+e):e||0}else if(e){var n=hr(t,r);return t[n]===r?n:-1}return h(t,r,e)}function En(r,t,o){var n=0,a=r?r.length:0;if(typeof t!="number"&&t!=null){var s=a;t=e.createCallback(t,o,3);while(s--&&t(r[s],s,r)){n++}}else{n=t==null||o?1:t||n}return i(r,0,Et(Y(0,a-n),a))}function xn(){var a=[],r=-1,i=arguments.length,n=o(),u=Lt(),m=u===h,l=o();while(++r<i){var e=arguments[r];if(d(e)||Tt(e)){a.push(e);n.push(m&&e.length>=_&&j(r?a[r]:l))}}var f=a[0],c=-1,v=f?f.length:0,p=[];e:while(++c<v){var t=n[0];e=f[c];if((t?I(t,e):u(l,e))<0){r=i;(t||l).push(e);while(--r){t=n[r];if((t?I(t,e):u(a[r],e))<0){continue e}}p.push(e)}}while(i--){t=n[i];if(t){y(t)}}s(n);s(l);return p}function Sn(t,r,o){var n=0,a=t?t.length:0;if(typeof r!="number"&&r!=null){var s=a;r=e.createCallback(r,o,3);while(s--&&r(t[s],s,t)){n++}}else{n=r;if(n==null||o){return t?t[a-1]:f}}return i(t,Y(0,a-n))}function Pr(r,n,t){var e=r?r.length:0;if(typeof t=="number"){e=(t<0?Y(0,e+t):Et(t,e-1))+1}while(e--){if(r[e]===n){return e}}return-1}function kn(e){var r=arguments,n=0,a=r.length,i=e?e.length:0;while(++n<a){var t=-1,s=r[n];while(++t<i){if(e[t]===s){fr.call(e,t--,1);i--}}}return e}function In(e,r,t){e=+e||0;t=typeof t=="number"?t:+t||1;if(r==null){r=e;e=0}var n=-1,i=Y(0,Zn((r-e)/(t||1))),a=W(i);while(++n<i){a[n]=e;e+=t}return a}function Cn(t,n,o){var r=-1,i=t?t.length:0,a=[];n=e.createCallback(n,o,3);while(++r<i){var s=t[r];if(n(s,r,t)){a.push(s);fr.call(t,r--,1);i--}}return a}function Ft(r,t,s){if(typeof t!="number"&&t!=null){var n=0,a=-1,o=r?r.length:0;t=e.createCallback(t,s,3);while(++a<o&&t(r[a],a,r)){n++}}else{n=t==null||s?1:Y(0,t)}return i(r,n)}function hr(n,i,t,o){var r=0,a=n?n.length:r;t=t?e.createCallback(t,o,1):Gt;i=t(i);while(r<a){var s=r+a>>>1;t(n[s])<i?r=s+1:a=s}return r}function Pn(){return $t(ut(arguments,true,true))}function wr(i,t,r,n){if(typeof t!="boolean"&&t!=null){n=r;r=typeof t!="function"&&n&&n[t]===i?null:t;t=false}if(r!=null){r=e.createCallback(r,n,3)}return $t(i,t,r)}function _n(e){return bt(e,i(arguments,1))}function jn(){var r=-1,n=arguments.length;while(++r<n){var e=arguments[r];if(d(e)||Tt(e)){var t=t?$t(bt(t,e).concat(bt(e,t))):e}}return t||[]}function Sr(){var e=arguments.length>1?arguments:arguments[0],t=-1,r=e?ur(Vt(e,"length")):0,n=W(r<0?0:r);while(++t<r){n[t]=Vt(e,t)}return n}function cr(e,t){var n=-1,a=e?e.length:0,i={};if(!t&&a&&!d(e[0])){t=[]}while(++n<a){var r=e[n];if(t){i[r]=t[n]}else if(r){i[r[0]]=r[1]}}return i}function Dn(t,e){if(!n(e)){throw new st}return function(){if(--t<1){return e.apply(this,arguments)}}}function yr(e,t){return arguments.length>2?it(e,17,i(arguments,2),null,t):it(e,1,null,null,t)}function Nn(e){var t=arguments.length>1?ut(arguments,true,false,1):It(e),r=-1,i=t.length;while(++r<i){var n=t[r];e[n]=it(e[n],1,null,null,e)}return e}function Fn(e,t){return arguments.length>2?it(t,19,i(arguments,2),null,e):it(t,3,null,null,e)}function Bn(){var e=arguments,t=e.length;while(t--){if(!n(e[t])){throw new st}}return function(){var t=arguments,r=e.length;while(r--){t=[e[r].apply(this,t)]}return t[0]}}function Vn(t,e){e=typeof e=="number"?e:+e||t.length;return it(t,4,null,null,null,e)}function dr(l,s,a){var r,t,u,o,i,e,m,p=0,d=false,c=true;if(!n(l)){throw new st}s=Y(0,s)||0;if(a===true){var h=true;c=false}else if(w(a)){h=a.leading;d="maxWait"in a&&(Y(s,a.maxWait)||0);c="trailing"in a?a.trailing:c}var y=function(){var n=s-(ct()-o);if(n<=0){if(t){_t(t)}var a=m;t=e=m=f;if(a){p=ct();u=l.apply(i,r);if(!e&&!t){r=i=null}}}else{e=xt(y,n)}};var v=function(){if(e){_t(e)}t=e=m=f;if(c||d!==s){p=ct();u=l.apply(i,r);if(!e&&!t){r=i=null}}};return function(){r=arguments;o=ct();i=this;m=c&&(e||!h);if(d===false){var f=h&&!e}else{if(!t&&!h){p=o}var a=d-(o-p),n=a<=0;if(n){if(t){t=_t(t)}p=o;u=l.apply(i,r)}else if(!t){t=xt(v,a)}}if(n&&e){e=_t(e)}else if(!e&&s!==d){e=xt(y,s)}if(f){n=true;u=l.apply(i,r)}if(n&&!e&&!t){r=i=null}return u}}function qn(e){if(!n(e)){throw new st}var t=i(arguments,1);return xt(function(){e.apply(f,t)},1)}function Xn(e,t){if(!n(e)){throw new st}var r=i(arguments,2);return xt(function(){e.apply(f,r)},t)}function Gn(t,r){if(!n(t)){throw new st}var e=function(){var n=e.cache,i=r?r.apply(this,arguments):T+arguments[0];return L.call(n,i)?n[i]:n[i]=t.apply(this,arguments)};e.cache={};return e}function Jn(e){var r,t;if(!n(e)){throw new st}return function(){if(r){return t}r=true;t=e.apply(this,arguments);e=null;return t}}function Wn(e){return it(e,16,i(arguments,1))}function Hn(e){return it(e,32,null,i(arguments,1))}function zn(i,a,e){var t=true,r=true;if(!n(i)){throw new st}if(e===false){t=false}else if(w(e)){t="leading"in e?e.leading:t;r="trailing"in e?e.trailing:r}C.leading=t;C.maxWait=a;C.trailing=r;return dr(i,a,C)}function Yn(e,t){return it(t,16,[e])}function $n(e){return function(){return e}}function Kn(e,a,s){var n=typeof e;if(e==null||n=="function"){return q(e,a,s)}if(n!="object"){return Ir(e)}var r=U(e),i=r[0],t=e[i];if(r.length==1&&t===t&&!w(t)){return function(r){var e=r[i];return t===e&&(t!==0||1/t==1/e)}}return function(i){var t=r.length,n=false;while(t--){if(!(n=dt(i[r[t]],e[r[t]],null,true))){break}}return n}}function Qn(e){return e==null?"":lt(e).replace(on,An)}function Gt(e){return e}function qt(i,t,r){var s=true,o=t&&It(t);if(!t||!r&&!o.length){if(r==null){r=t}a=pt;t=i;i=e;o=It(t)}if(r===false){s=false}else if(w(r)&&"chain"in r){s=r.chain}var a=i,l=n(a);M(o,function(e){var r=i[e]=t[e];if(l){a.prototype[e]=function(){var t=this.__chain__,n=this.__wrapped__,o=[n];gt.apply(o,arguments);var e=r.apply(i,o);if(s||t){if(n===e&&w(e)){return this}e=new a(e);e.__chain__=t}return e}}})}function ti(){t._=ri;return this}function or(){}var ct=ft(ct=Qt.now)&&ct||function(){return(new Qt).getTime()};var ii=er(F+"08")==8?er:function(e,t){return er(St(e)?e.replace(nt,""):e,t||0)};function Ir(e){return function(t){return t[e]}}function si(e,t,n){var a=e==null,r=t==null;if(n==null){if(typeof e=="boolean"&&r){n=e;e=1}else if(!r&&typeof t=="boolean"){n=t;r=true}}if(a&&r){t=1}e=+e||0;if(r){t=e;e=0}else{t=+t||0}if(n||e%1||t%1){var i=lr();return Et(e+i*(t-e+parseFloat("1e-"+((i+"").length-1))),t)}return Kt(e,t)}function oi(e,t){if(e){var r=e[t];return n(r)?e[t]():r}}function li(i,u,r){var l=e.templateSettings;i=lt(i||"");r=Ut({},r,l);var p=Ut({},r.imports,l.imports),g=U(p),y=Mt(p);var s,m=0,c=r.interpolate||k,t="__p += '";var h=Ct((r.escape||k).source+"|"+c.source+"|"+(c===B?et:k).source+"|"+(r.evaluate||k).source+"|$","g");i.replace(h,function(r,n,e,l,a,o){e||(e=l);t+=i.slice(m,o).replace(H,$);if(n){t+="' +\n__e("+n+") +\n'"}if(a){s=true;t+="';\n"+a+";\n__p += '"}if(e){t+="' +\n((__t = ("+e+")) == null ? '' : __t) +\n'"}m=o+r.length;return r});t+="';\n";var n=r.variable,o=n;if(!o){n="obj";t="with ("+n+") {\n"+t+"\n}\n"}t=(s?t.replace(X,""):t).replace(rt,"$1").replace(tt,"$1;");t="function("+n+") {\n"+(o?"":n+" || ("+n+" = {});\n")+"var __t, __p = '', __e = _.escape"+(s?", __j = Array.prototype.join;\n"+"function print() { __p += __j.call(arguments, '') }\n":";\n")+t+"return __p\n}";var v="\n/*\n//# sourceURL="+(r.sourceURL||"/lodash/template/source["+G++ +"]")+"\n*/";try{var a=Rt(g,"return "+t+v).apply(f,y)}catch(d){d.source=t;throw d}if(u){return a(u)}a.source=t;return a}function ui(e,t,i){e=(e=+e)>-1?e:0;var r=-1,n=W(e);t=q(t,i,1);while(++r<e){n[r]=t(r)}return n}function fi(e){return e==null?"":lt(e).replace(un,bn)}function ci(e){var t=++Z;return lt(e==null?"":e)+t}function pi(e){e=new pt(e);e.__chain__=true;return e}function di(e,t){t(e);return e}function mi(){this.__chain__=true;return this}function hi(){return lt(this.__wrapped__)}function Cr(){return this.__wrapped__}e.after=Dn;e.assign=Nt;e.at=Vr;e.bind=yr;e.bindAll=Nn;e.bindKey=Fn;e.chain=pi;e.compact=dn;e.compose=Bn;e.constant=$n;e.countBy=qr;e.create=tn;e.createCallback=Kn;e.curry=Vn;e.debounce=dr;e.defaults=Ut;e.defer=qn;e.delay=Xn;e.difference=mn;e.filter=Dt;e.flatten=gn;e.forEach=M;e.forEachRight=Ot;e.forIn=at;e.forInRight=zr;e.forOwn=r;e.forOwnRight=mr;e.functions=It;e.groupBy=Yr;e.indexBy=$r;e.initial=En;e.intersection=xn;e.invert=vr;e.invoke=Kr;e.keys=U;e.map=wt;e.mapValues=Mr;e.max=ur;e.memoize=Gn;e.merge=Or;e.min=en;e.omit=Dr;e.once=Jn;e.pairs=Rr;e.partial=Wn;e.partialRight=Hn;e.pick=Nr;e.pluck=Vt;e.property=Ir;e.pull=kn;e.range=In;e.reject=an;e.remove=Cn;e.rest=Ft;e.shuffle=nr;e.sortBy=fn;e.tap=di;e.throttle=zn;e.times=ui;e.toArray=cn;e.transform=Fr;e.union=Pn;e.uniq=wr;e.values=Mt;e.where=pn;e.without=_n;e.wrap=Yn;e.xor=jn;e.zip=Sr;e.zipObject=cr;e.collect=wt;e.drop=Ft;e.each=M;e.eachRight=Ot;e.extend=Nt;e.methods=It;e.object=cr;e.select=Dt;e.tail=Ft;e.unique=wr;e.unzip=Sr;qt(e);e.clone=nn;e.cloneDeep=rn;e.contains=xr;e.escape=Qn;e.every=Er;e.find=zt;e.findIndex=hn;e.findKey=Zr;e.findLast=Wr;e.findLastIndex=yn;e.findLastKey=Qr;e.has=Hr;e.identity=Gt;e.indexOf=br;e.isArguments=Tt;e.isArray=d;e.isBoolean=Jr;e.isDate=Gr;e.isElement=Xr;e.isEmpty=Ur;e.isEqual=Br;e.isFinite=_r;e.isFunction=n;e.isNaN=wn;e.isNull=Lr;e.isNumber=Tr;e.isObject=w;e.isPlainObject=tr;e.isRegExp=yi;e.isString=St;e.isUndefined=jr;e.lastIndexOf=Pr;
e.mixin=qt;e.noConflict=ti;e.noop=or;e.now=ct;e.parseInt=ii;e.random=si;e.reduce=Ht;e.reduceRight=ar;e.result=oi;e.runInContext=P;e.size=ln;e.some=rr;e.sortedIndex=hr;e.template=li;e.unescape=fi;e.uniqueId=ci;e.all=Er;e.any=rr;e.detect=zt;e.findWhere=zt;e.foldl=Ht;e.foldr=ar;e.include=xr;e.inject=Ht;qt(function(){var t={};r(e,function(n,r){if(!e.prototype[r]){t[r]=n}});return t}(),false);e.first=Xt;e.last=Sn;e.sample=sn;e.take=Xt;e.head=Xt;r(e,function(r,t){var n=t!=="sample";if(!e.prototype[t]){e.prototype[t]=function(e,t){var i=this.__chain__,a=r(this.__wrapped__,e,t);return!i&&(e==null||t&&!(n&&typeof e=="function"))?a:new pt(a,i)}}});e.VERSION="2.4.1";e.prototype.chain=mi;e.prototype.toString=hi;e.prototype.value=Cr;e.prototype.valueOf=Cr;M(["join","pop","shift"],function(t){var r=yt[t];e.prototype[t]=function(){var e=this.__chain__,t=r.apply(this.__wrapped__,arguments);return e?new pt(t,e):t}});M(["push","reverse","sort","unshift"],function(t){var r=yt[t];e.prototype[t]=function(){r.apply(this.__wrapped__,arguments);return this}});M(["concat","slice","splice"],function(t){var r=yt[t];e.prototype[t]=function(){return new pt(r.apply(this.__wrapped__,arguments),this.__chain__)}});return e}var c=P();if(typeof e=="function"&&typeof e.amd=="object"&&e.amd){p._=c;e(function(){return c})}else if(w&&A){if(Y){(A.exports=c)._=c}else{w._=c}}else{p._=c}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],136:[function(b,g,f){"use strict";var o=Object;var n=Object.defineProperty;var i=Object.create;function t(e,t,r){if(n)try{n.call(o,e,t,{value:r})}catch(i){e[t]=r}else{e[t]=r}}function e(e){if(e){t(e,"call",e.call);t(e,"apply",e.apply)}return e}e(n);e(i);var r=e(Object.prototype.hasOwnProperty);var p=e(Number.prototype.toString);var c=e(String.prototype.slice);var l=function(){};function a(e){if(i){return i.call(o,e)}l.prototype=e||null;return new l}var d=Math.random;var s=a(null);function u(){do var e=y(c.call(p.call(d(),36),2));while(r.call(s,e));return s[e]=e}function y(t){var e={};e[t]=true;return Object.keys(e)[0]}t(f,"makeUniqueKey",u);var v=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function E(i){for(var e=v(i),t=0,n=0,a=e.length;t<a;++t){if(!r.call(s,e[t])){if(t>n){e[n]=e[t]}++n}}e.length=n;return e};function m(e){return a(null)}function h(n){var e=u();var i=a(null);n=n||m;function o(a){var r;function s(e,t){if(e===i){return t?r=null:r||(r=n(a))}}t(a,e,s)}function s(t){if(!r.call(t,e))o(t);return t[e](i)}s.forget=function(t){if(r.call(t,e))t[e](i,true)};return s}t(f,"makeAccessor",h)},{}],137:[function(r,E,y){var t=r("assert");var o=r("./types");var h=o.namedTypes;var m=o.builtInTypes.array;var v=o.builtInTypes.object;var l=r("./lines");var i=l.fromString;var u=l.Lines;var c=l.concat;var a=r("./util").comparePos;var f=r("private").makeUniqueKey();function p(e,t){if(!e){return}if(t){if(h.Node.check(e)&&h.SourceLocation.check(e.loc)){for(var r=t.length-1;r>=0;--r){if(a(t[r].loc.end,e.loc.start)<=0){break}}t.splice(r+1,0,e);return}}else if(e[f]){return e[f]}var n;if(m.check(e)){n=Object.keys(e)}else if(v.check(e)){n=o.getFieldNames(e)}else{return}if(!t){Object.defineProperty(e,f,{value:t=[],enumerable:false})}for(var r=0,i=n.length;r<i;++r){p(e[n[r]],t)}return t}function d(u,e){var s=p(u);var r=0,n=s.length;while(r<n){var i=r+n>>1;var t=s[i];if(a(t.loc.start,e.loc.start)<=0&&a(e.loc.end,t.loc.end)<=0){d(e.enclosingNode=t,e);return}if(a(t.loc.end,e.loc.start)<=0){var o=t;r=i+1;continue}if(a(e.loc.end,t.loc.start)<=0){var l=t;n=i;continue}throw new Error("Comment location overlaps with node location")}if(o){e.precedingNode=o}if(l){e.followingNode=l}}y.attach=function(a,s,i){if(!m.check(a)){return}var r=[];a.forEach(function(a){a.loc.lines=i;d(s,a);var o=a.precedingNode;var f=a.enclosingNode;var l=a.followingNode;if(o&&l){var c=r.length;if(c>0){var u=r[c-1];t.strictEqual(u.precedingNode===a.precedingNode,u.followingNode===a.followingNode);if(u.followingNode!==a.followingNode){n(r,i)}}r.push(a)}else if(o){n(r,i);e.forNode(o).addTrailing(a)}else if(l){n(r,i);e.forNode(l).addLeading(a)}else if(f){n(r,i);e.forNode(f).addDangling(a)}else{throw new Error("AST contains no nodes at all?")}});n(r,i)};function n(r,u){var s=r.length;if(s===0){return}var o=r[0].precedingNode;var a=r[0].followingNode;var l=a.loc.start;for(var n=s;n>0;--n){var i=r[n-1];t.strictEqual(i.precedingNode,o);t.strictEqual(i.followingNode,a);var f=u.sliceString(i.loc.end,l);if(/\S/.test(f)){break}l=i.loc.start}while(n<=s&&(i=r[n])&&i.type==="Line"&&i.loc.start.column>a.loc.start.column){++n}r.forEach(function(t,r){if(r<n){e.forNode(o).addTrailing(t)}else{e.forNode(a).addLeading(t)}});r.length=0}function e(){t.ok(this instanceof e);this.leading=[];this.dangling=[];this.trailing=[]}var s=e.prototype;e.forNode=function x(r){var t=r.comments;if(!t){Object.defineProperty(r,"comments",{value:t=new e,enumerable:false})}return t};s.forEach=function S(e,t){this.leading.forEach(e,t);this.trailing.forEach(e,t)};s.addLeading=function w(e){this.leading.push(e)};s.addDangling=function k(e){this.dangling.push(e)};s.addTrailing=function I(e){e.trailing=true;if(e.type==="Block"){this.trailing.push(e)}else{this.leading.push(e)}};function g(e,o){var n=e.loc;var a=n&&n.lines;var r=[];if(e.type==="Block"){r.push("/*",i(e.value,o),"*/")}else if(e.type==="Line"){r.push("//",i(e.value,o))}else t.fail(e.type);if(e.trailing){r.push("\n")}else if(a instanceof u){var s=a.slice(n.end,a.skipSpaces(n.end));if(s.length===1){r.push(s)}else{r.push(new Array(s.length).join("\n"))}}else{r.push("\n")}return c(r).stripMargin(n?n.start.column:0)}function b(e,o){var r=e.loc;var a=r&&r.lines;var n=[];if(a instanceof u){var l=a.skipSpaces(r.start,true)||a.firstPos();var s=a.slice(l,r.start);if(s.length===1){n.push(s)}else{n.push(new Array(s.length).join("\n"))}}if(e.type==="Block"){n.push("/*",i(e.value,o),"*/")}else if(e.type==="Line"){n.push("//",i(e.value,o),"\n")}else t.fail(e.type);return c(n).stripMargin(r?r.start.column:0,true)}y.printComments=function(e,r,a){if(r){t.ok(r instanceof u)}else{r=i("")}if(!e||!(e.leading.length+e.trailing.length)){return r}var n=[];e.leading.forEach(function(e){n.push(g(e,a))});n.push(r);e.trailing.forEach(function(e){t.strictEqual(e.type,"Block");n.push(b(e,a))});return c(n)}},{"./lines":138,"./types":144,"./util":145,assert:103,"private":136}],138:[function(i,w,p){var t=i("assert");var x=i("source-map");var h=i("./options").normalize;var v=i("private").makeUniqueKey();var S=i("./types");var m=S.builtInTypes.string;var y=i("./util").comparePos;var E=i("./mapping");function r(e){return e[v]}function n(i,e){t.ok(this instanceof n);t.ok(i.length>0);if(e){m.assert(e)}else{e=null}Object.defineProperty(this,v,{value:{infos:i,mappings:[],name:e,cachedSourceMap:null}});if(e){r(this).mappings.push(new E(this,{start:this.firstPos(),end:this.lastPos()}))}}p.Lines=n;var e=n.prototype;Object.defineProperties(e,{length:{get:function(){return r(this).infos.length}},name:{get:function(){return r(this).name}}});function l(e){return{line:e.line,indent:e.indent,sliceStart:e.sliceStart,sliceEnd:e.sliceEnd}}var c={};var f=c.hasOwnProperty;var g=10;function d(a,r){var e=0;var o=a.length;for(var i=0;i<o;++i){var n=a.charAt(i);if(n===" "){e+=1}else if(n===" "){t.strictEqual(typeof r,"number");t.ok(r>0);var s=Math.ceil(e/r)*r;if(s===e){e+=r}else{e=s}}else if(n==="\r"){}else{t.fail("unexpected whitespace character",n)}}return e}p.countSpaces=d;var b=/^\s*/;function u(e,r){if(e instanceof n)return e;e+="";var i=r&&r.tabWidth;var a=e.indexOf(" ")<0;var s=!r&&a&&e.length<=g;t.ok(i||a,"No tab width specified but encountered tabs in string\n"+e);if(s&&f.call(c,e))return c[e];var o=new n(e.split("\n").map(function(e){var t=b.exec(e)[0];return{line:e,indent:d(t,i),sliceStart:t.length,sliceEnd:e.length}}),h(r).sourceFileName);if(s)c[e]=o;return o}p.fromString=u;function o(e){return!/\S/.test(e)}e.toString=function(e){return this.sliceString(this.firstPos(),this.lastPos(),e)};e.getSourceMap=function(a,s){if(!a){return null}var e=this;function o(e){e=e||{};m.assert(a);e.file=a;if(s){m.assert(s);e.sourceRoot=s}return e}var n=r(e);if(n.cachedSourceMap){return o(n.cachedSourceMap.toJSON())}var i=new x.SourceMapGenerator(o());var l={};n.mappings.forEach(function(r){var n=r.sourceLines.skipSpaces(r.sourceLoc.start)||r.sourceLines.lastPos();var a=e.skipSpaces(r.targetLoc.start)||e.lastPos();while(y(n,r.sourceLoc.end)<0&&y(a,r.targetLoc.end)<0){var u=r.sourceLines.charAt(n);var c=e.charAt(a);t.strictEqual(u,c);var s=r.sourceLines.name;i.addMapping({source:s,original:{line:n.line,column:n.column},generated:{line:a.line,column:a.column}});if(!f.call(l,s)){var o=r.sourceLines.toString();i.setSourceContent(s,o);l[s]=o}e.nextPos(a,true);r.sourceLines.nextPos(n,true)}});n.cachedSourceMap=i;return i.toJSON()};e.bootstrapCharAt=function(e){t.strictEqual(typeof e,"object");t.strictEqual(typeof e.line,"number");t.strictEqual(typeof e.column,"number");var i=e.line,n=e.column,a=this.toString().split("\n"),r=a[i-1];if(typeof r==="undefined")return"";if(n===r.length&&i<a.length)return"\n";if(n>=r.length)return"";return r.charAt(n)};e.charAt=function(n){t.strictEqual(typeof n,"object");t.strictEqual(typeof n.line,"number");t.strictEqual(typeof n.column,"number");var a=n.line,o=n.column,l=r(this),u=l.infos,i=u[a-1],e=o;if(typeof i==="undefined"||e<0)return"";var s=this.getIndentAt(a);if(e<s)return" ";e+=i.sliceStart-s;if(e===i.sliceEnd&&a<this.length)return"\n";if(e>=i.sliceEnd)return"";return i.line.charAt(e)};e.stripMargin=function(e,i){if(e===0)return this;t.ok(e>0,"negative margin: "+e);if(i&&this.length===1)return this;var a=r(this);var s=new n(a.infos.map(function(t,r){if(t.line&&(r>0||!i)){t=l(t);t.indent=Math.max(0,t.indent-e)}return t}));if(a.mappings.length>0){var o=r(s).mappings;t.strictEqual(o.length,0);a.mappings.forEach(function(t){o.push(t.indent(e,i,true))})}return s};e.indent=function(e){if(e===0)return this;var i=r(this);var a=new n(i.infos.map(function(t){if(t.line){t=l(t);t.indent+=e}return t}));if(i.mappings.length>0){var s=r(a).mappings;t.strictEqual(s.length,0);i.mappings.forEach(function(t){s.push(t.indent(e))})}return a};e.indentTail=function(e){if(e===0)return this;if(this.length<2)return this;var i=r(this);var a=new n(i.infos.map(function(t,r){if(r>0&&t.line){t=l(t);t.indent+=e}return t}));if(i.mappings.length>0){var s=r(a).mappings;t.strictEqual(s.length,0);i.mappings.forEach(function(t){s.push(t.indent(e,true))})}return a};e.getIndentAt=function(e){t.ok(e>=1,"no line "+e+" (line numbers start from 1)");var n=r(this),i=n.infos[e-1];return Math.max(i.indent,0)};e.guessTabWidth=function(){var i=r(this);if(f.call(i,"cachedTabWidth")){return i.cachedTabWidth}var t=[];var s=0;for(var a=1,p=this.length;a<=p;++a){var n=i.infos[a-1];var d=n.line.slice(n.sliceStart,n.sliceEnd);if(o(d)){continue}var l=Math.abs(n.indent-s);t[l]=~~t[l]+1;s=n.indent}var u=-1;var c=2;for(var e=1;e<t.length;e+=1){if(f.call(t,e)&&t[e]>u){u=t[e];c=e}}return i.cachedTabWidth=c};e.isOnlyWhitespace=function(){return o(this.toString())};e.isPrecededOnlyByWhitespace=function(t){var a=r(this);var e=a.infos[t.line-1];var s=Math.max(e.indent,0);var n=t.column-s;if(n<=0){return true}var i=e.sliceStart;var l=Math.min(i+n,e.sliceEnd);var u=e.line.slice(i,l);return o(u)};e.getLineLength=function(e){var n=r(this),t=n.infos[e-1];return this.getIndentAt(e)+t.sliceEnd-t.sliceStart};e.nextPos=function(e,t){var r=Math.max(e.line,0),n=Math.max(e.column,0);if(n<this.getLineLength(r)){e.column+=1;return t?!!this.skipSpaces(e,false,true):true}if(r<this.length){e.line+=1;e.column=0;return t?!!this.skipSpaces(e,false,true):true}return false};e.prevPos=function(e,n){var t=e.line,r=e.column;if(r<1){t-=1;if(t<1)return false;r=this.getLineLength(t)}else{r=Math.min(r-1,this.getLineLength(t))}e.line=t;e.column=r;return n?!!this.skipSpaces(e,true,true):true};e.firstPos=function(){return{line:1,column:0}};e.lastPos=function(){return{line:this.length,column:this.getLineLength(this.length)}};e.skipSpaces=function(e,t,r){if(e){e=r?e:{line:e.line,column:e.column}}else if(t){e=this.lastPos()}else{e=this.firstPos()}if(t){while(this.prevPos(e)){if(!o(this.charAt(e))&&this.nextPos(e)){return e}}return null}else{while(o(this.charAt(e))){if(!this.nextPos(e)){return null}}return e}};e.trimLeft=function(){var e=this.skipSpaces(this.firstPos(),false,true);return e?this.slice(e):a};e.trimRight=function(){var e=this.skipSpaces(this.lastPos(),true,true);return e?this.slice(this.firstPos(),e):a};e.trim=function(){var e=this.skipSpaces(this.firstPos(),false,true);if(e===null)return a;var r=this.skipSpaces(this.lastPos(),true,true);t.notStrictEqual(r,null);return this.slice(e,r)};e.eachPos=function(n,t,r){var e=this.firstPos();if(t){e.line=t.line,e.column=t.column}if(r&&!this.skipSpaces(e,false,true)){return}do n.call(this,e);while(this.nextPos(e,r))};e.bootstrapSlice=function(t,r){var e=this.toString().split("\n").slice(t.line-1,r.line);e.push(e.pop().slice(0,r.column));e[0]=e[0].slice(t.column);return u(e.join("\n"))};e.slice=function(i,e){if(!e){if(!i){return this}e=this.lastPos()}var o=r(this);var a=o.infos.slice(i.line-1,e.line);if(i.line===e.line){a[0]=s(a[0],i.column,e.column)}else{t.ok(i.line<e.line);a[0]=s(a[0],i.column);a.push(s(a.pop(),0,e.column))}var l=new n(a);if(o.mappings.length>0){var u=r(l).mappings;t.strictEqual(u.length,0);o.mappings.forEach(function(r){var t=r.slice(this,i,e);if(t){u.push(t)}},this)}return l};function s(n,i,r){var a=n.sliceStart;var s=n.sliceEnd;var e=Math.max(n.indent,0);var o=e+s-a;if(typeof r==="undefined"){r=o}i=Math.max(i,0);r=Math.min(r,o);r=Math.max(r,i);if(r<e){e=r;s=a}else{s-=o-r}o=r;o-=i;if(i<e){e-=i}else{i-=e;e=0;a+=i}t.ok(e>=0);t.ok(a<=s);t.strictEqual(o,e+s-a);if(n.indent===e&&n.sliceStart===a&&n.sliceEnd===s){return n}return{line:n.line,indent:e,sliceStart:a,sliceEnd:s}}e.bootstrapSliceString=function(e,t,r){return this.slice(e,t).toString(r)};e.sliceString=function(a,t,i){if(!t){if(!a){return this}t=this.lastPos()}i=h(i);var v=r(this).infos;var f=[];var m=i.tabWidth;for(var n=a.line;n<=t.line;++n){var e=v[n-1];if(n===a.line){if(n===t.line){e=s(e,a.column,t.column)}else{e=s(e,a.column)}}else if(n===t.line){e=s(e,0,t.column)}var c=Math.max(e.indent,0);var y=e.line.slice(0,e.sliceStart);if(i.reuseWhitespace&&o(y)&&d(y,i.tabWidth)===c){f.push(e.line.slice(0,e.sliceEnd));continue}var l=0;var p=c;if(i.useTabs){l=Math.floor(c/m);p-=l*m}var u="";if(l>0){u+=new Array(l+1).join(" ")}if(p>0){u+=new Array(p+1).join(" ")}u+=e.line.slice(e.sliceStart,e.sliceEnd);f.push(u)}return f.join("\n")};e.isEmpty=function(){return this.length<2&&this.getLineLength(1)<1};e.join=function(c){var o=this;var p=r(o);var t=[];var i=[];var e;function s(r){if(r===null)return;if(e){var n=r.infos[0];var a=new Array(n.indent+1).join(" ");var s=t.length;var o=Math.max(e.indent,0)+e.sliceEnd-e.sliceStart;e.line=e.line.slice(0,e.sliceEnd)+a+n.line.slice(n.sliceStart,n.sliceEnd);e.sliceEnd=e.line.length;if(r.mappings.length>0){r.mappings.forEach(function(e){i.push(e.add(s,o))})}}else if(r.mappings.length>0){i.push.apply(i,r.mappings)}r.infos.forEach(function(r,n){if(!e||n>0){e=l(r);t.push(e)}})}function d(e,t){if(t>0)s(p);s(e)}c.map(function(t){var e=u(t);if(e.isEmpty())return null;return r(e)}).forEach(o.isEmpty()?s:d);if(t.length<1)return a;var f=new n(t);r(f).mappings=i;return f};p.concat=function(e){return a.join(e)};e.concat=function(n){var r=arguments,e=[this];e.push.apply(e,r);t.strictEqual(e.length,r.length+1);return a.join(e)};var a=u("")},{"./mapping":139,"./options":140,"./types":144,"./util":145,assert:103,"private":136,"source-map":178}],139:[function(o,c,h){var e=o("assert");var l=o("./types");var m=l.builtInTypes.string;var s=l.builtInTypes.number;var p=l.namedTypes.SourceLocation;var i=l.namedTypes.Position;var u=o("./lines");var r=o("./util").comparePos;function n(i,r,t){e.ok(this instanceof n);e.ok(i instanceof u.Lines);p.assert(r);if(t){e.ok(s.check(t.start.line)&&s.check(t.start.column)&&s.check(t.end.line)&&s.check(t.end.column))}else{t=r}Object.defineProperties(this,{sourceLines:{value:i},sourceLoc:{value:r},targetLoc:{value:t}})}var a=n.prototype;c.exports=n;a.slice=function(c,a,o){e.ok(c instanceof u.Lines);i.assert(a);if(o){i.assert(o)}else{o=c.lastPos()}var p=this.sourceLines;var l=this.sourceLoc;var s=this.targetLoc;function f(t){var n=l[t];var i=s[t];var r=a;if(t==="end"){r=o}else{e.strictEqual(t,"start")}return d(p,n,c,i,r)}if(r(a,s.start)<=0){if(r(s.end,o)<=0){s={start:t(s.start,a.line,a.column),end:t(s.end,a.line,a.column)}}else if(r(o,s.start)<=0){return null}else{l={start:l.start,end:f("end")};s={start:t(s.start,a.line,a.column),end:t(o,a.line,a.column)}}}else{if(r(s.end,a)<=0){return null}if(r(s.end,o)<=0){l={start:f("start"),end:l.end};s={start:{line:1,column:0},end:t(s.end,a.line,a.column)}}else{l={start:f("start"),end:f("end")};s={start:{line:1,column:0},end:t(o,a.line,a.column)}}}return new n(this.sourceLines,l,s)};a.add=function(e,t){return new n(this.sourceLines,this.sourceLoc,{start:f(this.targetLoc.start,e,t),end:f(this.targetLoc.end,e,t)})};function f(e,t,r){return{line:e.line+t-1,column:e.line===1?e.column+r:e.column}}a.subtract=function(e,r){return new n(this.sourceLines,this.sourceLoc,{start:t(this.targetLoc.start,e,r),end:t(this.targetLoc.end,e,r)})};function t(e,t,r){return{line:e.line-t+1,column:e.line===t?e.column-r:e.column}}a.indent=function(t,r,s){if(t===0){return this}var e=this.targetLoc;var i=e.start.line;var a=e.end.line;if(r&&i===1&&a===1){return this}e={start:e.start,end:e.end};if(!r||i>1){var o=e.start.column+t;e.start={line:i,column:s?Math.max(0,o):o}}if(!r||a>1){var l=e.end.column+t;e.end={line:a,column:s?Math.max(0,l):l}}return new n(this.sourceLines,this.sourceLoc,e)};function d(a,f,s,c,l){e.ok(a instanceof u.Lines);e.ok(s instanceof u.Lines);i.assert(f);i.assert(c);i.assert(l);var p=r(c,l);if(p===0){return f}if(p<0){var n=a.skipSpaces(f);var t=s.skipSpaces(c);var o=l.line-t.line;n.line+=o;t.line+=o;if(o>0){n.column=0;t.column=0}else{e.strictEqual(o,0)}while(r(t,l)<0&&s.nextPos(t,true)){e.ok(a.nextPos(n,true));e.strictEqual(a.charAt(n),s.charAt(t))}}else{var n=a.skipSpaces(f,true);var t=s.skipSpaces(c,true);var o=l.line-t.line;n.line+=o;t.line+=o;if(o<0){n.column=a.getLineLength(n.line);t.column=s.getLineLength(t.line)}else{e.strictEqual(o,0)}while(r(l,t)<0&&s.prevPos(t,true)){e.ok(a.prevPos(n,true));e.strictEqual(a.charAt(n),s.charAt(t))}}return n}},{"./lines":138,"./types":144,"./util":145,assert:103}],140:[function(t,i,r){var e={esprima:t("esprima-fb"),tabWidth:4,useTabs:false,reuseWhitespace:true,wrapColumn:74,sourceFileName:null,sourceMapName:null,sourceRoot:null,inputSourceMap:null,range:false,tolerant:true},n=e.hasOwnProperty;r.normalize=function(r){r=r||e;function t(t){return n.call(r,t)?r[t]:e[t]}return{tabWidth:+t("tabWidth"),useTabs:!!t("useTabs"),reuseWhitespace:!!t("reuseWhitespace"),wrapColumn:Math.max(t("wrapColumn"),0),sourceFileName:t("sourceFileName"),sourceMapName:t("sourceMapName"),sourceRoot:t("sourceRoot"),inputSourceMap:t("inputSourceMap"),esprima:t("esprima"),range:t("range"),tolerant:t("tolerant")}}},{"esprima-fb":147}],141:[function(e,h,a){var l=e("assert");var t=e("./types");var r=t.namedTypes;var s=t.builders;var o=t.builtInTypes.object;var p=t.builtInTypes.array;var m=t.builtInTypes.function;var d=e("./patcher").Patcher;var c=e("./options").normalize;var f=e("./lines").fromString;var u=e("./comments").attach;a.parse=function y(o,e){e=c(e);var t=f(o,e);var l=t.toString({tabWidth:e.tabWidth,reuseWhitespace:false,useTabs:false});var r=e.esprima.parse(l,{loc:true,range:e.range,comment:true,tolerant:e.tolerant});var p=r.comments;delete r.comments;var i=s.file(r);i.loc={lines:t,indent:0,start:t.firstPos(),end:t.lastPos()};var a=new n(t).copy(i);u(p,a.program,t);return a};function n(e){l.ok(this instanceof n);this.lines=e;this.indent=0}var i=n.prototype;i.copy=function(e){if(p.check(e)){return e.map(this.copy,this)}if(!o.check(e)){return e}if(r.MethodDefinition&&r.MethodDefinition.check(e)||r.Property.check(e)&&(e.method||e.shorthand)){e.value.loc=null;if(r.FunctionExpression.check(e.value)){e.value.id=null}}var i=Object.create(Object.getPrototypeOf(e),{original:{value:e,configurable:false,enumerable:false,writable:true}});var t=e.loc;var s=this.indent;var l=s;if(t){if(t.start.line<1){t.start.line=1}if(t.end.line<1){t.end.line=1}if(this.lines.isPrecededOnlyByWhitespace(t.start)){l=this.indent=t.start.column}t.lines=this.lines;t.indent=l}var u=Object.keys(e);var f=u.length;for(var a=0;a<f;++a){var n=u[a];if(n==="loc"){i[n]=e[n]}else if(n==="comments"){}else{i[n]=this.copy(e[n])}}this.indent=s;if(e.comments){Object.defineProperty(i,"comments",{value:e.comments,enumerable:false})}return i}},{"./comments":137,"./lines":138,"./options":140,"./patcher":142,"./types":144,assert:103}],142:[function(a,k,h){var n=a("assert");var l=a("./lines");var e=a("./types");var I=e.getFieldValue;var i=e.namedTypes.Node;var y=e.namedTypes.Expression;var x=e.namedTypes.SourceLocation;var c=a("./util");var r=c.comparePos;var p=e.NodePath;var t=e.builtInTypes.object;var u=e.builtInTypes.array;var g=e.builtInTypes.string;function s(e){n.ok(this instanceof s);n.ok(e instanceof l.Lines);var t=this,i=[];t.replace=function(t,e){if(g.check(e))e=l.fromString(e);i.push({lines:e,start:t.start,end:t.end})};t.get=function(t){t=t||{start:{line:1,column:0},end:{line:e.length,column:e.getLineLength(e.length)}};var a=t.start,s=[];function o(t,i){n.ok(r(t,i)<=0);s.push(e.slice(t,i))}i.sort(function(e,t){return r(e.start,t.start)}).forEach(function(e){if(r(a,e.start)>0){}else{o(a,e.start);s.push(e.lines);a=e.end}});o(a,t.end);return l.concat(s)}}h.Patcher=s;h.getReprinter=function(e){n.ok(e instanceof p);var a=e.value;if(!i.check(a))return;var t=a.original;var r=t&&t.loc;var o=r&&r.lines;var l=[];if(!o||!v(e,l))return;return function(n){var e=new s(o);l.forEach(function(r){var t=r.oldPath.value;x.assert(t.loc,true);e.replace(t.loc,n(r.newPath).indentTail(t.loc.indent))});return e.get(r).indentTail(-t.loc.indent)}};function v(a,e){var t=a.value;i.assert(t);var r=t.original;i.assert(r);n.deepEqual(e,[]);if(t.type!==r.type){return false}var l=new p(r);var s=o(a,l,e);if(!s){e.length=0}return s}function f(e,r,i){var n=e.value;var a=r.value;if(n===a)return true;if(u.check(n))return b(e,r,i);if(t.check(n))return E(e,r,i);return false}function b(t,r,s){var n=t.value;var i=r.value;u.assert(n);var a=n.length;if(!(u.check(i)&&i.length===a))return false;for(var e=0;e<a;++e)if(!f(t.get(e),r.get(e),s))return false;return true}function E(e,r,n){var a=e.value;t.assert(a);if(a.original===null){return false}var s=r.value;if(!t.check(s))return false;if(i.check(a)){if(!i.check(s)){return false}if(!s.loc){return false}if(a.type===s.type){var l=[];if(o(e,r,l)){n.push.apply(n,l)}else{n.push({newPath:e,oldPath:r})}return true}if(y.check(a)&&y.check(s)){n.push({newPath:e,oldPath:r});return true}return false}return o(e,r,n)}var m={line:1,column:0};function d(a){var o=a.value;var t=o.loc;var i=t&&t.lines;if(i){var e=m;e.line=t.start.line;e.column=t.start.column;while(i.prevPos(e)){var s=i.charAt(e);if(s==="("){var n=a;while(n.parentPath)n=n.parentPath;return r(n.value.loc.start,e)<=0}if(s!==" "){return false}}}return false}function S(a){var o=a.value;var t=o.loc;var i=t&&t.lines;if(i){var e=m;e.line=t.end.line;e.column=t.end.column;do{var s=i.charAt(e);if(s===")"){var n=a;while(n.parentPath)n=n.parentPath;return r(e,n.value.loc.end)<=0}if(s!==" "){return false}}while(i.nextPos(e))}return false}function w(e){return d(e)&&S(e)}function o(e,r,s){var n=e.value;var a=r.value;t.assert(n);t.assert(a);if(n.original===null){return false}if(!e.canBeFirstInStatement()&&e.firstInStatement()&&!d(r))return false;if(e.needsParens(true)&&!w(r)){return false}for(var i in c.getUnionOfKeys(n,a)){if(i==="loc")continue;if(!f(e.get(i),r.get(i),s))return false}return true}},{"./lines":138,"./types":144,"./util":145,assert:103}],143:[function(i,R,M){var n=i("assert");var D=i("source-map");var _=i("./comments").printComments;var h=i("./lines");var t=h.fromString;var e=h.concat;var P=i("./options").normalize;var C=i("./patcher").getReprinter;var u=i("./types");var r=u.namedTypes;var x=u.builtInTypes.string;var j=u.builtInTypes.object;var s=u.NodePath;var f=i("./util");function o(t,e){n.ok(this instanceof o);x.assert(t);this.code=t;if(e){j.assert(e);this.map=e}}var O=o.prototype;var y=false;O.toString=function(){if(!y){console.warn("Deprecation warning: recast.print now returns an object with "+"a .code property. You appear to be treating the object as a "+"string, which might still work but is strongly discouraged.");y=true}return this.code};var v=new o("");function g(t){n.ok(this instanceof g);var u=t&&t.tabWidth;var e=P(t);n.notStrictEqual(e,t);e.sourceFileName=null;function i(t){n.ok(t instanceof s);return _(t.node.comments,a(t),e)}function a(t,o){if(o)return i(t);n.ok(t instanceof s);if(!u){var l=e.tabWidth;var a=t.node.loc;if(a&&a.lines&&a.lines.guessTabWidth){e.tabWidth=a.lines.guessTabWidth();var f=r(t);e.tabWidth=l;return f}}return r(t)}function r(e){var t=C(e);if(t)return b(e,t(r));return c(e)}function c(t){return E(t,e,i)}function l(t){return E(t,e,l)}this.print=function(t){if(!t){return v}var n=t instanceof s?t:new s(t);var r=a(n,true);return new o(r.toString(e),f.composeSourceMaps(e.inputSourceMap,r.getSourceMap(e.sourceMapName,e.sourceRoot)))};this.printGenerically=function(t){if(!t){return v}var r=t instanceof s?t:new s(t);var n=e.reuseWhitespace;e.reuseWhitespace=false;var i=new o(l(r).toString(e));e.reuseWhitespace=n;return i}}M.Printer=g;function b(r,t){return r.needsParens()?e(["(",t,")"]):t}function E(e,t,r){n.ok(e instanceof s);return b(e,I(e,t,r))}function I(i,f,s){var u=i.value;if(!u){return t("")}if(typeof u==="string"){return t(u,f)}r.Node.assert(u);switch(u.type){case"File":i=i.get("program");u=i.node;r.Program.assert(u);case"Program":return m(l(i.get("body"),f,s));case"EmptyStatement":return t("");case"ExpressionStatement":return e([s(i.get("expression")),";"]);case"BinaryExpression":case"LogicalExpression":case"AssignmentExpression":return t(" ").join([s(i.get("left")),u.operator,s(i.get("right"))]);case"MemberExpression":var o=[s(i.get("object"))];if(u.computed)o.push("[",s(i.get("property")),"]");else o.push(".",s(i.get("property")));return e(o);case"Path":return t(".").join(u.body);case"Identifier":return t(u.name,f);case"SpreadElement":case"SpreadElementPattern":case"SpreadProperty":case"SpreadPropertyPattern":return e(["...",s(i.get("argument"))]);case"FunctionDeclaration":case"FunctionExpression":var o=[];if(u.async)o.push("async ");o.push("function");if(u.generator)o.push("*");if(u.id)o.push(" ",s(i.get("id")));o.push("(",d(i,f,s),") ",s(i.get("body")));return e(o);case"ArrowFunctionExpression":var o=[];if(u.async)o.push("async ");if(u.params.length===1){o.push(s(i.get("params",0)))}else{o.push("(",d(i,f,s),")")}o.push(" => ",s(i.get("body")));return e(o);case"MethodDefinition":var o=[];if(u.static){o.push("static ")}o.push(S(u.kind,i.get("key"),i.get("value"),f,s));return e(o);case"YieldExpression":var o=["yield"];if(u.delegate)o.push("*");if(u.argument)o.push(" ",s(i.get("argument")));return e(o);case"AwaitExpression":var o=["await"];if(u.all)o.push("*");if(u.argument)o.push(" ",s(i.get("argument")));return e(o);case"ModuleDeclaration":var o=["module",s(i.get("id"))];if(u.source){n.ok(!u.body);o.push("from",s(i.get("source")))}else{o.push(s(i.get("body")))}return t(" ").join(o);case"ImportSpecifier":case"ExportSpecifier":var o=[s(i.get("id"))];if(u.name)o.push(" as ",s(i.get("name")));return e(o);case"ExportBatchSpecifier":return t("*");case"ImportNamespaceSpecifier":return e(["* as ",s(i.get("id"))]);case"ImportDefaultSpecifier":return s(i.get("id"));case"ExportDeclaration":var o=["export"];if(u["default"]){o.push(" default")}else if(u.specifiers&&u.specifiers.length>0){if(u.specifiers.length===1&&u.specifiers[0].type==="ExportBatchSpecifier"){o.push(" *")}else{o.push(" { ",t(", ").join(i.get("specifiers").map(s))," }")}if(u.source)o.push(" from ",s(i.get("source")));o.push(";");return e(o)}if(u.declaration){if(!r.Node.check(u.declaration)){console.log(JSON.stringify(u,null,2))}var R=s(i.get("declaration"));o.push(" ",R);if(c(R)!==";"){o.push(";")}}return e(o);case"ImportDeclaration":var o=["import "];if(u.specifiers&&u.specifiers.length>0){var v=false;i.get("specifiers").each(function(e){if(e.name>0){o.push(", ")}if(r.ImportDefaultSpecifier.check(e.value)||r.ImportNamespaceSpecifier.check(e.value)){n.strictEqual(v,false)}else{r.ImportSpecifier.assert(e.value);if(!v){v=true;o.push("{")}}o.push(s(e))});if(v){o.push("}")}o.push(" from ")}o.push(s(i.get("source")),";");return e(o);case"BlockStatement":var D=l(i.get("body"),f,s);if(D.isEmpty())return t("{}");return e(["{\n",D.indent(f.tabWidth),"\n}"]);case"ReturnStatement":var o=["return"];if(u.argument){var x=s(i.get("argument"));if(x.length>1&&r.XJSElement&&r.XJSElement.check(u.argument)){o.push(" (\n",x.indent(f.tabWidth),"\n)")}else{o.push(" ",x)}}o.push(";");return e(o);case"CallExpression":return e([s(i.get("callee")),w(i,f,s)]);case"ObjectExpression":case"ObjectPattern":var A=false,g=u.properties.length,o=[g>0?"{\n":"{"];i.get("properties").map(function(e){var i=e.value;var n=e.name;var r=s(e).indent(f.tabWidth);var t=r.length>1;if(t&&A){o.push("\n")}o.push(r);if(n<g-1){o.push(t?",\n\n":",\n");A=!t}});o.push(g>0?"\n}":"}");return e(o);case"PropertyPattern":return e([s(i.get("key")),": ",s(i.get("pattern"))]);case"Property":if(u.method||u.kind==="get"||u.kind==="set"){return S(u.kind,i.get("key"),i.get("value"),f,s)}if(i.node.shorthand){return s(i.get("key"))}else{return e([s(i.get("key")),": ",s(i.get("value"))])}case"ArrayExpression":case"ArrayPattern":var q=u.elements,g=q.length,o=["["];i.get("elements").each(function(e){var r=e.value;if(!r){o.push(",")}else{var t=e.name;if(t>0)o.push(" ");o.push(s(e));if(t<g-1)o.push(",")}});o.push("]");return e(o);case"SequenceExpression":return t(", ").join(i.get("expressions").map(s));case"ThisExpression":return t("this");case"Literal":if(typeof u.value!=="string")return t(u.value,f);case"ModuleSpecifier":return t(L(u),f);case"UnaryExpression":var o=[u.operator];if(/[a-z]$/.test(u.operator))o.push(" ");o.push(s(i.get("argument")));return e(o);case"UpdateExpression":var o=[s(i.get("argument")),u.operator];if(u.prefix)o.reverse();return e(o);case"ConditionalExpression":return e(["(",s(i.get("test"))," ? ",s(i.get("consequent"))," : ",s(i.get("alternate")),")"]);case"NewExpression":var o=["new ",s(i.get("callee"))];var N=u.arguments;if(N){o.push(w(i,f,s))}return e(o);case"VariableDeclaration":var o=[u.kind," "];var C=0;var b=i.get("declarations").map(function(t){var e=s(t);C=Math.max(e.length,C);return e});if(C===1){o.push(t(", ").join(b))}else if(b.length>1){o.push(t(",\n").join(b).indentTail(u.kind.length+1))}else{o.push(b[0])}var E=i.parent&&i.parent.node;if(!r.ForStatement.check(E)&&!r.ForInStatement.check(E)&&!(r.ForOfStatement&&r.ForOfStatement.check(E))){o.push(";")}return e(o);case"VariableDeclarator":return u.init?t(" = ").join([s(i.get("id")),s(i.get("init"))]):s(i.get("id"));case"WithStatement":return e(["with (",s(i.get("object")),") ",s(i.get("body"))]);case"IfStatement":var T=a(s(i.get("consequent")),f),o=["if (",s(i.get("test")),")",T];if(u.alternate)o.push(k(T)?" else":"\nelse",a(s(i.get("alternate")),f));return e(o);case"ForStatement":var P=s(i.get("init")),U=P.length>1?";\n":"; ",_="for (",F=t(U).join([P,s(i.get("test")),s(i.get("update"))]).indentTail(_.length),j=e([_,F,")"]),I=a(s(i.get("body")),f),o=[j];if(j.length>1){o.push("\n");I=I.trimLeft()}o.push(I);return e(o);case"WhileStatement":return e(["while (",s(i.get("test")),")",a(s(i.get("body")),f)]);case"ForInStatement":return e([u.each?"for each (":"for (",s(i.get("left"))," in ",s(i.get("right")),")",a(s(i.get("body")),f)]);case"ForOfStatement":return e(["for (",s(i.get("left"))," of ",s(i.get("right")),")",a(s(i.get("body")),f)]);
case"DoWhileStatement":var M=e(["do",a(s(i.get("body")),f)]),o=[M];if(k(M))o.push(" while");else o.push("\nwhile");o.push(" (",s(i.get("test")),");");return e(o);case"BreakStatement":var o=["break"];if(u.label)o.push(" ",s(i.get("label")));o.push(";");return e(o);case"ContinueStatement":var o=["continue"];if(u.label)o.push(" ",s(i.get("label")));o.push(";");return e(o);case"LabeledStatement":return e([s(i.get("label")),":\n",s(i.get("body"))]);case"TryStatement":var o=["try ",s(i.get("block"))];i.get("handlers").each(function(e){o.push(" ",s(e))});if(u.finalizer)o.push(" finally ",s(i.get("finalizer")));return e(o);case"CatchClause":var o=["catch (",s(i.get("param"))];if(u.guard)o.push(" if ",s(i.get("guard")));o.push(") ",s(i.get("body")));return e(o);case"ThrowStatement":return e(["throw ",s(i.get("argument")),";"]);case"SwitchStatement":return e(["switch (",s(i.get("discriminant")),") {\n",t("\n").join(i.get("cases").map(s)),"\n}"]);case"SwitchCase":var o=[];if(u.test)o.push("case ",s(i.get("test")),":");else o.push("default:");if(u.consequent.length>0){o.push("\n",l(i.get("consequent"),f,s).indent(f.tabWidth))}return e(o);case"DebuggerStatement":return t("debugger;");case"XJSAttribute":var o=[s(i.get("name"))];if(u.value)o.push("=",s(i.get("value")));return e(o);case"XJSIdentifier":return t(u.name,f);case"XJSNamespacedName":return t(":").join([s(i.get("namespace")),s(i.get("name"))]);case"XJSMemberExpression":return t(".").join([s(i.get("object")),s(i.get("property"))]);case"XJSSpreadAttribute":return e(["{...",s(i.get("argument")),"}"]);case"XJSExpressionContainer":return e(["{",s(i.get("expression")),"}"]);case"XJSElement":var O=s(i.get("openingElement"));if(u.openingElement.selfClosing){n.ok(!u.closingElement);return O}var B=e(i.get("children").map(function(t){var e=t.value;if(r.Literal.check(e)&&typeof e.value==="string"){if(/\S/.test(e.value)){return e.value.replace(/^\s+|\s+$/g,"")}else if(/\n/.test(e.value)){return"\n"}}return s(t)})).indentTail(f.tabWidth);var V=s(i.get("closingElement"));return e([O,B,V]);case"XJSOpeningElement":var o=["<",s(i.get("name"))];var h=[];i.get("attributes").each(function(e){h.push(" ",s(e))});var y=e(h);var X=y.length>1||y.getLineLength(1)>f.wrapColumn;if(X){h.forEach(function(t,e){if(t===" "){n.strictEqual(e%2,0);h[e]="\n"}});y=e(h).indentTail(f.tabWidth)}o.push(y,u.selfClosing?" />":">");return e(o);case"XJSClosingElement":return e(["</",s(i.get("name")),">"]);case"XJSText":return t(u.value,f);case"XJSEmptyExpression":return t("");case"TypeAnnotatedIdentifier":var o=[s(i.get("annotation"))," ",s(i.get("identifier"))];return e(o);case"ClassBody":if(u.body.length===0){return t("{}")}return e(["{\n",l(i.get("body"),f,s).indent(f.tabWidth),"\n}"]);case"ClassPropertyDefinition":var o=["static ",s(i.get("definition"))];if(!r.MethodDefinition.check(u.definition))o.push(";");return e(o);case"ClassProperty":return e([s(i.get("id")),";"]);case"ClassDeclaration":case"ClassExpression":var o=["class"];if(u.id)o.push(" ",s(i.get("id")));if(u.superClass)o.push(" extends ",s(i.get("superClass")));o.push(" ",s(i.get("body")));return e(o);case"Node":case"Printable":case"SourceLocation":case"Position":case"Statement":case"Function":case"Pattern":case"Expression":case"Declaration":case"Specifier":case"NamedSpecifier":case"Block":case"Line":throw new Error("unprintable type: "+JSON.stringify(u.type));case"ClassHeritage":case"ComprehensionBlock":case"ComprehensionExpression":case"Glob":case"TaggedTemplateExpression":case"TemplateElement":case"TemplateLiteral":case"GeneratorExpression":case"LetStatement":case"LetExpression":case"GraphExpression":case"GraphIndexExpression":case"AnyTypeAnnotation":case"BooleanTypeAnnotation":case"ClassImplements":case"DeclareClass":case"DeclareFunction":case"DeclareModule":case"DeclareVariable":case"FunctionTypeAnnotation":case"FunctionTypeParam":case"GenericTypeAnnotation":case"InterfaceDeclaration":case"InterfaceExtends":case"IntersectionTypeAnnotation":case"MemberTypeAnnotation":case"NullableTypeAnnotation":case"NumberTypeAnnotation":case"ObjectTypeAnnotation":case"ObjectTypeCallProperty":case"ObjectTypeIndexer":case"ObjectTypeProperty":case"QualifiedTypeIdentifier":case"StringLiteralTypeAnnotation":case"StringTypeAnnotation":case"TupleTypeAnnotation":case"Type":case"TypeAlias":case"TypeAnnotation":case"TypeParameterDeclaration":case"TypeParameterInstantiation":case"TypeofTypeAnnotation":case"UnionTypeAnnotation":case"VoidTypeAnnotation":case"XMLDefaultDeclaration":case"XMLAnyName":case"XMLQualifiedIdentifier":case"XMLFunctionQualifiedIdentifier":case"XMLAttributeSelector":case"XMLFilterExpression":case"XML":case"XMLElement":case"XMLList":case"XMLEscape":case"XMLText":case"XMLStartTag":case"XMLEndTag":case"XMLPointTag":case"XMLName":case"XMLAttribute":case"XMLCdata":case"XMLComment":case"XMLProcessingInstruction":default:debugger;throw new Error("unknown type: "+JSON.stringify(u.type))}return p}function l(t,o,l){var i=t.parent&&r.ClassBody&&r.ClassBody.check(t.parent.node);var a=t.filter(function(t){var e=t.value;if(!e)return false;if(e.type==="EmptyStatement")return false;if(!i){r.Statement.assert(e)}return true});var s=null;var u=a.length;var n=[];a.forEach(function(d,v){var f=l(d);var c=d.value;var b=true;var g=f.length>1;var w=v>0;var y=v<u-1;var p;var e;if(i){var c=d.value;if(r.MethodDefinition.check(c)||r.ClassPropertyDefinition.check(c)&&r.MethodDefinition.check(c.definition)){b=false}}if(b){f=m(f)}var t=o.reuseWhitespace&&A(c);var a=t&&t.lines;if(w){if(a){var h=a.skipSpaces(t.start,true);var x=h?h.line:1;var S=t.start.line-x;p=Array(S+1).join("\n")}else{p=g?"\n\n":"\n"}}else{p=""}if(y){if(a){var E=a.skipSpaces(t.end);var k=E?E.line:a.length;var I=k-t.end.line;e=Array(I+1).join("\n")}else{e=g?"\n\n":"\n"}}else{e=""}n.push(T(s,p),f);if(y){s=e}else if(e){n.push(e)}});return e(n)}function A(e){if(!e.loc){return null}if(!e.comments){return e.loc}var t=e.loc.start;var r=e.loc.end;e.comments.forEach(function(e){if(e.loc){if(f.comparePos(e.loc.start,t)<0){t=e.loc.start}if(f.comparePos(r,e.loc.end)<0){r=e.loc.end}}});return{lines:e.loc.lines,start:t,end:r}}function T(e,r){if(!e&&!r){return t("")}if(!e){return t(r)}if(!r){return t(e)}var n=t(e);var i=t(r);if(i.length>n.length){return i}return n}function S(t,l,a,u,s){var i=[];var f=l.value;var o=a.value;r.FunctionExpression.assert(o);if(o.async){i.push("async ")}if(!t||t==="init"){if(o.generator){i.push("*")}}else{n.ok(t==="get"||t==="set");i.push(t," ")}i.push(s(l),"(",d(a,u,s),") ",s(a.get("body")));return e(i)}function w(a,n,s){var i=a.get("arguments").map(s);var r=t(", ").join(i);if(r.getLineLength(1)>n.wrapColumn){r=t(",\n").join(i);return e(["(\n",r.indent(n.tabWidth),"\n)"])}return e(["(",r,")"])}function d(i,o,a){var l=i.node;r.Function.assert(l);var f=i.get("params");var u=i.get("defaults");var s=f.map(u.value?function(t){var r=a(t);var n=u.get(t.name);return n.value?e([r,"=",a(n)]):r}:a);if(l.rest){s.push(e(["...",a(i.get("rest"))]))}var n=t(", ").join(s);if(n.length>1||n.getLineLength(1)>o.wrapColumn){n=t(",\n").join(s);return e(["\n",n.indent(o.tabWidth)])}return n}function a(t,r){if(t.length>1)return e([" ",t]);return e(["\n",m(t).indent(r.tabWidth)])}function c(e){var t=e.lastPos();do{var r=e.charAt(t);if(/\S/.test(r))return r}while(e.prevPos(t))}function k(e){return c(e)==="}"}function L(e){r.Literal.assert(e);x.assert(e.value);return JSON.stringify(e.value)}function m(t){var r=c(t);if(!r||"\n};".indexOf(r)<0)return e([t,";"]);return t}},{"./comments":137,"./lines":138,"./options":140,"./patcher":142,"./types":144,"./util":145,assert:103,"source-map":178}],144:[function(r,n,i){var e=r("ast-types");var t=e.Type.def;t("File").bases("Node").build("program").field("program",t("Program"));e.finalize();n.exports=e},{"ast-types":101}],145:[function(e,u,t){var f=e("assert");var l=e("./types").getFieldValue;var r=e("source-map");var n=r.SourceMapConsumer;var i=r.SourceMapGenerator;var a=Object.prototype.hasOwnProperty;function s(){var r={};var i=arguments.length;for(var e=0;e<i;++e){var n=Object.keys(arguments[e]);var a=n.length;for(var t=0;t<a;++t){r[n[t]]=true}}return r}t.getUnionOfKeys=s;function o(e,t){return e.line-t.line||e.column-t.column}t.comparePos=o;t.composeSourceMaps=function(t,e){if(t){if(!e){return t}}else{return e||null}var s=new n(t);var l=new n(e);var r=new i({file:e.file,sourceRoot:e.sourceRoot});var o={};l.eachMapping(function(t){var n=s.originalPositionFor({line:t.originalLine,column:t.originalColumn});var e=n.source;if(e===null){return}r.addMapping({source:e,original:{line:n.line,column:n.column},generated:{line:t.generatedLine,column:t.generatedColumn},name:t.name});var i=s.sourceContentFor(e);if(i&&!a.call(o,e)){o[e]=i;r.setSourceContent(e,i)}});return r.toJSON()}},{"./types":144,assert:103,"source-map":178}],146:[function(e,r,t){(function(r){var n=e("./lib/types");var i=e("./lib/parser").parse;var a=e("./lib/printer").Printer;function s(e,t){return new a(t).print(e)}function o(e,t){return new a(t).printGenerically(e)}function l(e,t){return u(r.argv[2],e,t)}function u(t,r,n){e("fs").readFile(t,"utf-8",function(e,t){if(e){console.error(e);return}c(t,r,n)})}function f(e){r.stdout.write(e)}function c(t,r,e){var n=e&&e.writeback||f;r(i(t,e),function(t){n(s(t,e).code)})}Object.defineProperties(t,{parse:{enumerable:true,value:i},visit:{enumerable:true,value:n.visit},print:{enumerable:true,value:s},prettyPrint:{enumerable:false,value:o},types:{enumerable:false,value:n},run:{enumerable:false,value:l}})}).call(this,e("_process"))},{"./lib/parser":141,"./lib/printer":143,"./lib/types":144,_process:112,fs:102}],147:[function(r,n,t){(function(n,r){"use strict";if(typeof e==="function"&&e.amd){e(["exports"],r)}else if(typeof t!=="undefined"){r(t)}else{r(n.esprima={})}})(this,function(Et){"use strict";var u,T,Gt,i,G,s,St,Nt,Rt,$,o,g,e,h,y,v,r,f,a,p;u={BooleanLiteral:1,EOF:2,Identifier:3,Keyword:4,NullLiteral:5,NumericLiteral:6,Punctuator:7,StringLiteral:8,RegularExpression:9,Template:10,XJSIdentifier:11,XJSText:12};T={};T[u.BooleanLiteral]="Boolean";T[u.EOF]="<end>";T[u.Identifier]="Identifier";T[u.Keyword]="Keyword";T[u.NullLiteral]="Null";T[u.NumericLiteral]="Numeric";T[u.Punctuator]="Punctuator";T[u.StringLiteral]="String";T[u.XJSIdentifier]="XJSIdentifier";T[u.XJSText]="XJSText";T[u.RegularExpression]="RegularExpression";Gt=["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="];i={AnyTypeAnnotation:"AnyTypeAnnotation",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrayTypeAnnotation:"ArrayTypeAnnotation",ArrowFunctionExpression:"ArrowFunctionExpression",AssignmentExpression:"AssignmentExpression",BinaryExpression:"BinaryExpression",BlockStatement:"BlockStatement",BooleanTypeAnnotation:"BooleanTypeAnnotation",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ClassImplements:"ClassImplements",ClassProperty:"ClassProperty",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DeclareClass:"DeclareClass",DeclareFunction:"DeclareFunction",DeclareModule:"DeclareModule",DeclareVariable:"DeclareVariable",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportDeclaration:"ExportDeclaration",ExportBatchSpecifier:"ExportBatchSpecifier",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",ForStatement:"ForStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",FunctionTypeAnnotation:"FunctionTypeAnnotation",FunctionTypeParam:"FunctionTypeParam",GenericTypeAnnotation:"GenericTypeAnnotation",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",InterfaceDeclaration:"InterfaceDeclaration",InterfaceExtends:"InterfaceExtends",IntersectionTypeAnnotation:"IntersectionTypeAnnotation",LabeledStatement:"LabeledStatement",Literal:"Literal",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",NullableTypeAnnotation:"NullableTypeAnnotation",NumberTypeAnnotation:"NumberTypeAnnotation",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",ObjectTypeAnnotation:"ObjectTypeAnnotation",ObjectTypeCallProperty:"ObjectTypeCallProperty",ObjectTypeIndexer:"ObjectTypeIndexer",ObjectTypeProperty:"ObjectTypeProperty",Program:"Program",Property:"Property",QualifiedTypeIdentifier:"QualifiedTypeIdentifier",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SpreadProperty:"SpreadProperty",StringLiteralTypeAnnotation:"StringLiteralTypeAnnotation",StringTypeAnnotation:"StringTypeAnnotation",SwitchCase:"SwitchCase",SwitchStatement:"SwitchStatement",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TupleTypeAnnotation:"TupleTypeAnnotation",TryStatement:"TryStatement",TypeAlias:"TypeAlias",TypeAnnotation:"TypeAnnotation",TypeofTypeAnnotation:"TypeofTypeAnnotation",TypeParameterDeclaration:"TypeParameterDeclaration",TypeParameterInstantiation:"TypeParameterInstantiation",UnaryExpression:"UnaryExpression",UnionTypeAnnotation:"UnionTypeAnnotation",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",VoidTypeAnnotation:"VoidTypeAnnotation",WhileStatement:"WhileStatement",WithStatement:"WithStatement",XJSIdentifier:"XJSIdentifier",XJSNamespacedName:"XJSNamespacedName",XJSMemberExpression:"XJSMemberExpression",XJSEmptyExpression:"XJSEmptyExpression",XJSExpressionContainer:"XJSExpressionContainer",XJSElement:"XJSElement",XJSClosingElement:"XJSClosingElement",XJSOpeningElement:"XJSOpeningElement",XJSAttribute:"XJSAttribute",XJSSpreadAttribute:"XJSSpreadAttribute",XJSText:"XJSText",YieldExpression:"YieldExpression",AwaitExpression:"AwaitExpression"};G={Data:1,Get:2,Set:4};$={"static":"static",prototype:"prototype"};s={UnexpectedToken:"Unexpected token %0",UnexpectedNumber:"Unexpected number",UnexpectedString:"Unexpected string",UnexpectedIdentifier:"Unexpected identifier",UnexpectedReserved:"Unexpected reserved word",UnexpectedTemplate:"Unexpected quasi %0",UnexpectedEOS:"Unexpected end of input",NewlineAfterThrow:"Illegal newline after throw",InvalidRegExp:"Invalid regular expression",UnterminatedRegExp:"Invalid regular expression: missing /",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInFormalsList:"Invalid left-hand side in formals list",InvalidLHSInForIn:"Invalid left-hand side in for-in",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NoCatchOrFinally:"Missing catch or finally after try",UnknownLabel:"Undefined label '%0'",Redeclaration:"%0 '%1' has already been declared",IllegalContinue:"Illegal continue statement",IllegalBreak:"Illegal break statement",IllegalDuplicateClassProperty:"Illegal duplicate property in class definition",IllegalReturn:"Illegal return statement",IllegalSpread:"Illegal spread element",StrictModeWith:"Strict mode code may not include a with statement",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictParamDupe:"Strict mode function may not have duplicate parameter names",ParameterAfterRestParameter:"Rest parameter must be final parameter of an argument list",DefaultRestParameter:"Rest parameter can not have a default value",ElementAfterSpreadElement:"Spread must be the final element of an element list",PropertyAfterSpreadProperty:"A rest property must be the final property of an object literal",ObjectPatternAsRestParameter:"Invalid rest parameter",ObjectPatternAsSpread:"Invalid spread argument",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictDuplicateProperty:"Duplicate data property in object literal not allowed in strict mode",AccessorDataProperty:"Object literal may not have data and accessor property with the same name",AccessorGetSet:"Object literal may not have multiple get/set accessors with the same name",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictReservedWord:"Use of future reserved word in strict mode",MissingFromClause:"Missing from clause",NoAsAfterImportNamespace:"Missing as after import *",InvalidModuleSpecifier:"Invalid module specifier",NoUnintializedConst:"Const must be initialized",ComprehensionRequiresBlock:"Comprehension must have at least one block",ComprehensionError:"Comprehension Error",EachNotAllowed:"Each is not supported",InvalidXJSAttributeValue:"XJS value should be either an expression or a quoted XJS text",ExpectedXJSClosingTag:"Expected corresponding XJS closing tag for %0",AdjacentXJSElements:"Adjacent XJS elements must be wrapped in an enclosing tag",ConfusedAboutFunctionType:"Unexpected token =>. It looks like "+"you are trying to write a function type, but you ended up "+"writing a grouped type followed by an =>, which is a syntax "+"error. Remember, function type parameters are named so function "+"types look like (name1: type1, name2: type2) => returnType. You "+"probably wrote (type1) => returnType"};St={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),LeadingZeros:new RegExp("^0+(?!$)")};function J(e,t){if(!e){throw new Error("ASSERT: "+t)}}function R(e){return e>=48&&e<=57}function Dt(e){return"0123456789abcdefABCDEF".indexOf(e)>=0}function V(e){return"01234567".indexOf(e)>=0}function sr(e){return e===32||e===9||e===11||e===12||e===160||e>=5760&&" ".indexOf(String.fromCharCode(e))>0}function L(e){return e===10||e===13||e===8232||e===8233}function X(e){return e===36||e===95||e>=65&&e<=90||e>=97&&e<=122||e===92||e>=128&&St.NonAsciiIdentifierStart.test(String.fromCharCode(e))}function at(e){return e===36||e===95||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===92||e>=128&&St.NonAsciiIdentifierPart.test(String.fromCharCode(e))}function _n(e){switch(e){case"class":case"enum":case"export":case"extends":case"import":case"super":return true;default:return false}}function lt(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return true;default:return false}}function _(e){return e==="eval"||e==="arguments"}function Yn(e){if(g&<(e)){return true}switch(e.length){case 2:return e==="if"||e==="in"||e==="do";case 3:return e==="var"||e==="for"||e==="new"||e==="try"||e==="let";case 4:return e==="this"||e==="else"||e==="case"||e==="void"||e==="with"||e==="enum";case 5:return e==="while"||e==="break"||e==="catch"||e==="throw"||e==="const"||e==="class"||e==="super";case 6:return e==="return"||e==="typeof"||e==="delete"||e==="switch"||e==="export"||e==="import";case 7:return e==="default"||e==="finally"||e==="extends";case 8:return e==="function"||e==="continue"||e==="debugger";case 10:return e==="instanceof";default:return false}}function D(){var t,r,n;r=false;n=false;while(e<v){t=o.charCodeAt(e);if(n){++e;if(L(t)){n=false;if(t===13&&o.charCodeAt(e)===10){++e}++h;y=e}}else if(r){if(L(t)){if(t===13){++e}if(t!==13||o.charCodeAt(e)===10){++h;++e;y=e;if(e>=v){d({},s.UnexpectedToken,"ILLEGAL")}}}else{t=o.charCodeAt(e++);if(e>=v){d({},s.UnexpectedToken,"ILLEGAL")}if(t===42){t=o.charCodeAt(e);if(t===47){++e;r=false}}}}else if(t===47){t=o.charCodeAt(e+1);if(t===47){e+=2;n=true}else if(t===42){e+=2;r=true;if(e>=v){d({},s.UnexpectedToken,"ILLEGAL")}}else{break}}else if(sr(t)){++e}else if(L(t)){++e;if(t===13&&o.charCodeAt(e)===10){++e}++h;y=e}else{break}}}function ut(a){var t,n,i,r=0;n=a==="u"?4:2;for(t=0;t<n;++t){if(e<v&&Dt(o[e])){i=o[e++];r=r*16+"0123456789abcdef".indexOf(i.toLowerCase())}else{return""}}return String.fromCharCode(r)}function Ht(){var r,t,n,i;r=o[e];t=0;if(r==="}"){d({},s.UnexpectedToken,"ILLEGAL")}while(e<v){r=o[e++];if(!Dt(r)){break}t=t*16+"0123456789abcdef".indexOf(r.toLowerCase())}if(t>1114111||r!=="}"){d({},s.UnexpectedToken,"ILLEGAL")}if(t<=65535){return String.fromCharCode(t)}n=(t-65536>>10)+55296;i=(t-65536&1023)+56320;return String.fromCharCode(n,i)}function zt(){var t,r;t=o.charCodeAt(e++);r=String.fromCharCode(t);if(t===92){if(o.charCodeAt(e)!==117){d({},s.UnexpectedToken,"ILLEGAL")}++e;t=ut("u");if(!t||t==="\\"||!X(t.charCodeAt(0))){d({},s.UnexpectedToken,"ILLEGAL")}r=t}while(e<v){t=o.charCodeAt(e);if(!at(t)){break}++e;r+=String.fromCharCode(t);if(t===92){r=r.substr(0,r.length-1);if(o.charCodeAt(e)!==117){d({},s.UnexpectedToken,"ILLEGAL")}++e;t=ut("u");if(!t||t==="\\"||!at(t.charCodeAt(0))){d({},s.UnexpectedToken,"ILLEGAL")}r+=t}}return r}function an(){var t,r;t=e++;while(e<v){r=o.charCodeAt(e);if(r===92){e=t;return zt()}if(at(r)){++e}else{break}}return o.slice(t,e)}function pn(){var n,t,r;n=e;t=o.charCodeAt(e)===92?zt():an();if(t.length===1){r=u.Identifier}else if(Yn(t)){r=u.Keyword}else if(t==="null"){r=u.NullLiteral}else if(t==="true"||t==="false"){r=u.BooleanLiteral}else{r=u.Identifier}return{type:r,value:t,lineNumber:h,lineStart:y,range:[n,e]}}function U(){var t=e,i=o.charCodeAt(e),f,r=o[e],n,l,c;switch(i){case 40:case 41:case 59:case 44:case 123:case 125:case 91:case 93:case 58:case 63:case 126:++e;if(p.tokenize){if(i===40){p.openParenToken=p.tokens.length}else if(i===123){p.openCurlyToken=p.tokens.length}}return{type:u.Punctuator,value:String.fromCharCode(i),lineNumber:h,lineStart:y,range:[t,e]};default:f=o.charCodeAt(e+1);if(f===61){switch(i){case 37:case 38:case 42:case 43:case 45:case 47:case 60:case 62:case 94:case 124:e+=2;return{type:u.Punctuator,value:String.fromCharCode(i)+String.fromCharCode(f),lineNumber:h,lineStart:y,range:[t,e]};case 33:case 61:e+=2;if(o.charCodeAt(e)===61){++e}return{type:u.Punctuator,value:o.slice(t,e),lineNumber:h,lineStart:y,range:[t,e]};default:break}}break}n=o[e+1];l=o[e+2];c=o[e+3];if(r===">"&&n===">"&&l===">"){if(c==="="){e+=4;return{type:u.Punctuator,value:">>>=",lineNumber:h,lineStart:y,range:[t,e]}}}if(r===">"&&n===">"&&l===">"){e+=3;return{type:u.Punctuator,value:">>>",lineNumber:h,lineStart:y,range:[t,e]}}if(r==="<"&&n==="<"&&l==="="){e+=3;return{type:u.Punctuator,value:"<<=",lineNumber:h,lineStart:y,range:[t,e]}}if(r===">"&&n===">"&&l==="="){e+=3;return{type:u.Punctuator,value:">>=",lineNumber:h,lineStart:y,range:[t,e]}}if(r==="."&&n==="."&&l==="."){e+=3;return{type:u.Punctuator,value:"...",lineNumber:h,lineStart:y,range:[t,e]}}if(r===n&&"+-<>&|".indexOf(r)>=0&&!a.inType){e+=2;return{type:u.Punctuator,value:r+n,lineNumber:h,lineStart:y,range:[t,e]}}if(r==="="&&n===">"){e+=2;return{type:u.Punctuator,value:"=>",lineNumber:h,lineStart:y,range:[t,e]}}if("<>=!+-*%&|^/".indexOf(r)>=0){++e;return{type:u.Punctuator,value:r,lineNumber:h,lineStart:y,range:[t,e]}}if(r==="."){++e;return{type:u.Punctuator,value:r,lineNumber:h,lineStart:y,range:[t,e]}}d({},s.UnexpectedToken,"ILLEGAL")}function Xn(r){var t="";while(e<v){if(!Dt(o[e])){break}t+=o[e++]}if(t.length===0){d({},s.UnexpectedToken,"ILLEGAL")}if(X(o.charCodeAt(e))){d({},s.UnexpectedToken,"ILLEGAL")}return{type:u.NumericLiteral,value:parseInt("0x"+t,16),lineNumber:h,lineStart:y,range:[r,e]}}function Wn(n,i){var t,r;if(V(n)){r=true;t="0"+o[e++]}else{r=false;++e;t=""}while(e<v){if(!V(o[e])){break}t+=o[e++]}if(!r&&t.length===0){d({},s.UnexpectedToken,"ILLEGAL")}if(X(o.charCodeAt(e))||R(o.charCodeAt(e))){d({},s.UnexpectedToken,"ILLEGAL")}return{type:u.NumericLiteral,value:parseInt(t,8),octal:r,lineNumber:h,lineStart:y,range:[i,e]}}function Qt(){var r,n,t,i;t=o[e];J(R(t.charCodeAt(0))||t===".","Numeric literal must start with a decimal digit or a decimal point");n=e;r="";if(t!=="."){r=o[e++];t=o[e];if(r==="0"){if(t==="x"||t==="X"){++e;return Xn(n)}if(t==="b"||t==="B"){++e;r="";while(e<v){t=o[e];if(t!=="0"&&t!=="1"){break}r+=o[e++]}if(r.length===0){d({},s.UnexpectedToken,"ILLEGAL")}if(e<v){t=o.charCodeAt(e);if(X(t)||R(t)){d({},s.UnexpectedToken,"ILLEGAL")}}return{type:u.NumericLiteral,value:parseInt(r,2),lineNumber:h,lineStart:y,range:[n,e]}}if(t==="o"||t==="O"||V(t)){return Wn(t,n)}if(t&&R(t.charCodeAt(0))){d({},s.UnexpectedToken,"ILLEGAL")}}while(R(o.charCodeAt(e))){r+=o[e++]}t=o[e]}if(t==="."){r+=o[e++];while(R(o.charCodeAt(e))){r+=o[e++]}t=o[e]}if(t==="e"||t==="E"){r+=o[e++];t=o[e];if(t==="+"||t==="-"){r+=o[e++]}if(R(o.charCodeAt(e))){while(R(o.charCodeAt(e))){r+=o[e++]}}else{d({},s.UnexpectedToken,"ILLEGAL")}}if(X(o.charCodeAt(e))){d({},s.UnexpectedToken,"ILLEGAL")}return{type:u.NumericLiteral,value:parseFloat(r),lineNumber:h,lineStart:y,range:[n,e]}}function wr(){var r="",i,f,t,n,a,c,l=false;i=o[e];J(i==="'"||i==='"',"String literal must starts with a quote");f=e;++e;while(e<v){t=o[e++];if(t===i){i="";break}else if(t==="\\"){t=o[e++];if(!t||!L(t.charCodeAt(0))){switch(t){case"n":r+="\n";break;case"r":r+="\r";break;case"t":r+=" ";break;case"u":case"x":if(o[e]==="{"){++e;r+=Ht()}else{c=e;a=ut(t);if(a){r+=a}else{e=c;r+=t}}break;case"b":r+="\b";break;case"f":r+="\f";break;case"v":r+="";break;default:if(V(t)){n="01234567".indexOf(t);if(n!==0){l=true}if(e<v&&V(o[e])){l=true;n=n*8+"01234567".indexOf(o[e++]);if("0123".indexOf(t)>=0&&e<v&&V(o[e])){n=n*8+"01234567".indexOf(o[e++])}}r+=String.fromCharCode(n)}else{r+=t}break}}else{++h;if(t==="\r"&&o[e]==="\n"){++e}y=e}}else if(L(t.charCodeAt(0))){break}else{r+=t}}if(i!==""){d({},s.UnexpectedToken,"ILLEGAL")}return{type:u.StringLiteral,value:r,octal:l,lineNumber:h,lineStart:y,range:[f,e]}}function rr(){var r="",t,l,i,a,p,f,n,c;i=false;a=false;l=e;++e;while(e<v){t=o[e++];if(t==="`"){a=true;i=true;break}else if(t==="$"){if(o[e]==="{"){++e;i=true;break}r+=t}else if(t==="\\"){t=o[e++];if(!L(t.charCodeAt(0))){switch(t){case"n":r+="\n";break;case"r":r+="\r";break;case"t":r+=" ";break;case"u":case"x":if(o[e]==="{"){++e;r+=Ht()}else{p=e;f=ut(t);if(f){r+=f}else{e=p;r+=t}}break;case"b":r+="\b";break;case"f":r+="\f";break;case"v":r+="";break;default:if(V(t)){n="01234567".indexOf(t);if(n!==0){c=true}if(e<v&&V(o[e])){c=true;n=n*8+"01234567".indexOf(o[e++]);if("0123".indexOf(t)>=0&&e<v&&V(o[e])){n=n*8+"01234567".indexOf(o[e++])}}r+=String.fromCharCode(n)}else{r+=t}break}}else{++h;if(t==="\r"&&o[e]==="\n"){++e}y=e}}else if(L(t.charCodeAt(0))){++h;if(t==="\r"&&o[e]==="\n"){++e}y=e;r+="\n"}else{r+=t}}if(!i){d({},s.UnexpectedToken,"ILLEGAL")}return{type:u.Template,value:{cooked:r,raw:o.slice(l+1,e-(a?1:2))},tail:a,octal:c,lineNumber:h,lineStart:y,range:[l,e]}}function Ur(n){var t,r;f=null;D();t=n.head?"`":"}";if(o[e]!==t){d({},s.UnexpectedToken,"ILLEGAL")}r=rr();dt();return r}function N(){var r,t,g,i,n,a,m=false,l,b=false,c;f=null;D();g=e;t=o[e];J(t==="/","Regular expression literal must start with a slash");r=o[e++];while(e<v){t=o[e++];r+=t;if(m){if(t==="]"){m=false}}else{if(t==="\\"){t=o[e++];if(L(t.charCodeAt(0))){d({},s.UnterminatedRegExp)}r+=t}else if(t==="/"){b=true;break}else if(t==="["){m=true}else if(L(t.charCodeAt(0))){d({},s.UnterminatedRegExp)}}}if(!b){d({},s.UnterminatedRegExp)}i=r.substr(1,r.length-2);n="";while(e<v){t=o[e];if(!at(t.charCodeAt(0))){break}++e;if(t==="\\"&&e<v){t=o[e];if(t==="u"){++e;l=e;t=ut("u");if(t){n+=t;for(r+="\\u";l<e;++l){r+=o[l]}}else{e=l;n+="u";r+="\\u"}}else{r+="\\"}}else{n+=t;r+=t}}c=i;if(n.indexOf("u")>=0){c=c.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}try{a=new RegExp(c)}catch(E){d({},s.InvalidRegExp)}try{a=new RegExp(i,n)}catch(x){a=null}dt();if(p.tokenize){return{type:u.RegularExpression,value:a,regex:{pattern:i,flags:n},lineNumber:h,lineStart:y,range:[g,e]}}return{literal:r,value:a,regex:{pattern:i,flags:n},range:[g,e]}}function Ot(e){return e.type===u.Identifier||e.type===u.Keyword||e.type===u.BooleanLiteral||e.type===u.NullLiteral}function yn(){var t,e;t=p.tokens[p.tokens.length-1];if(!t){return N()}if(t.type==="Punctuator"){if(t.value===")"){e=p.tokens[p.openParenToken-1];if(e&&e.type==="Keyword"&&(e.value==="if"||e.value==="while"||e.value==="for"||e.value==="with")){return N()}return U()}if(t.value==="}"){if(p.tokens[p.openCurlyToken-3]&&p.tokens[p.openCurlyToken-3].type==="Keyword"){e=p.tokens[p.openCurlyToken-4];if(!e){return U()}}else if(p.tokens[p.openCurlyToken-4]&&p.tokens[p.openCurlyToken-4].type==="Keyword"){e=p.tokens[p.openCurlyToken-5];if(!e){return N()}}else{return U()}if(Gt.indexOf(e.value)>=0){return U()}return N()}return N()}if(t.type==="Keyword"){return N()}return U()}function tt(){var t;if(!a.inXJSChild){D()}if(e>=v){return{type:u.EOF,lineNumber:h,lineStart:y,range:[e,e]}}if(a.inXJSChild){return Pn()}t=o.charCodeAt(e);if(t===40||t===41||t===58){return U()}if(t===39||t===34){if(a.inXJSTag){return Tn()}return wr()}if(a.inXJSTag&&wn(t)){return In()}if(t===96){return rr()}if(X(t)){return pn()}if(t===46){if(R(o.charCodeAt(e+1))){return Qt()}return U()}if(R(t)){return Qt()}if(p.tokenize&&t===47){return yn()}return U()}function m(){var t;t=f;e=t.range[1];h=t.lineNumber;
y=t.lineStart;f=tt();e=t.range[1];h=t.lineNumber;y=t.lineStart;return t}function dt(){var t,r,n;t=e;r=h;n=y;f=tt();e=t;h=r;y=n}function j(){var t,r,n,i,a;t=typeof p.advance==="function"?p.advance:tt;r=e;n=h;i=y;if(f===null){f=t()}e=f.range[1];h=f.lineNumber;y=f.lineStart;a=t();e=r;h=n;y=i;return a}function ft(t){e=t.range[0];h=t.lineNumber;y=t.lineStart;f=t}function c(){if(!p.loc&&!p.range){return undefined}D();return{offset:e,line:h,col:e-y}}function Ut(){if(!p.loc&&!p.range){return undefined}return{offset:e,line:h,col:e-y}}function Zr(e){var r,n,a=p.bottomRightStack,t=a[a.length-1];if(e.type===i.Program){if(e.body.length>0){return}}if(p.trailingComments.length>0){if(p.trailingComments[0].range[0]>=e.range[1]){n=p.trailingComments;p.trailingComments=[]}else{p.trailingComments.length=0}}else{if(t&&t.trailingComments&&t.trailingComments[0].range[0]>=e.range[1]){n=t.trailingComments;delete t.trailingComments}}if(t){while(t&&t.range[0]>=e.range[0]){r=t;t=a.pop()}}if(r){if(r.leadingComments&&r.leadingComments[r.leadingComments.length-1].range[1]<=e.range[0]){e.leadingComments=r.leadingComments;delete r.leadingComments}}else if(p.leadingComments.length>0&&p.leadingComments[p.leadingComments.length-1].range[1]<=e.range[0]){e.leadingComments=p.leadingComments;p.leadingComments=[]}if(n){e.trailingComments=n}a.push(e)}function t(n,t){if(p.range){t.range=[n.offset,e]}if(p.loc){t.loc={start:{line:n.line,column:n.col},end:{line:h,column:e-y}};t=r.postProcess(t)}if(p.attachComment){Zr(t)}return t}Nt={name:"SyntaxTree",postProcess:function(e){return e},createArrayExpression:function(e){return{type:i.ArrayExpression,elements:e}},createAssignmentExpression:function(e,t,r){return{type:i.AssignmentExpression,operator:e,left:t,right:r}},createBinaryExpression:function(e,t,r){var n=e==="||"||e==="&&"?i.LogicalExpression:i.BinaryExpression;return{type:n,operator:e,left:t,right:r}},createBlockStatement:function(e){return{type:i.BlockStatement,body:e}},createBreakStatement:function(e){return{type:i.BreakStatement,label:e}},createCallExpression:function(e,t){return{type:i.CallExpression,callee:e,arguments:t}},createCatchClause:function(e,t){return{type:i.CatchClause,param:e,body:t}},createConditionalExpression:function(e,t,r){return{type:i.ConditionalExpression,test:e,consequent:t,alternate:r}},createContinueStatement:function(e){return{type:i.ContinueStatement,label:e}},createDebuggerStatement:function(){return{type:i.DebuggerStatement}},createDoWhileStatement:function(e,t){return{type:i.DoWhileStatement,body:e,test:t}},createEmptyStatement:function(){return{type:i.EmptyStatement}},createExpressionStatement:function(e){return{type:i.ExpressionStatement,expression:e}},createForStatement:function(e,t,r,n){return{type:i.ForStatement,init:e,test:t,update:r,body:n}},createForInStatement:function(e,t,r){return{type:i.ForInStatement,left:e,right:t,body:r,each:false}},createForOfStatement:function(e,t,r){return{type:i.ForOfStatement,left:e,right:t,body:r}},createFunctionDeclaration:function(t,s,r,n,a,c,o,l,u,f){var e={type:i.FunctionDeclaration,id:t,params:s,defaults:r,body:n,rest:a,generator:c,expression:o,returnType:u,typeParameters:f};if(l){e.async=true}return e},createFunctionExpression:function(t,s,r,n,a,c,o,l,u,f){var e={type:i.FunctionExpression,id:t,params:s,defaults:r,body:n,rest:a,generator:c,expression:o,returnType:u,typeParameters:f};if(l){e.async=true}return e},createIdentifier:function(e){return{type:i.Identifier,name:e,typeAnnotation:undefined,optional:undefined}},createTypeAnnotation:function(e){return{type:i.TypeAnnotation,typeAnnotation:e}},createFunctionTypeAnnotation:function(e,t,r,n){return{type:i.FunctionTypeAnnotation,params:e,returnType:t,rest:r,typeParameters:n}},createFunctionTypeParam:function(e,t,r){return{type:i.FunctionTypeParam,name:e,typeAnnotation:t,optional:r}},createNullableTypeAnnotation:function(e){return{type:i.NullableTypeAnnotation,typeAnnotation:e}},createArrayTypeAnnotation:function(e){return{type:i.ArrayTypeAnnotation,elementType:e}},createGenericTypeAnnotation:function(e,t){return{type:i.GenericTypeAnnotation,id:e,typeParameters:t}},createQualifiedTypeIdentifier:function(e,t){return{type:i.QualifiedTypeIdentifier,qualification:e,id:t}},createTypeParameterDeclaration:function(e){return{type:i.TypeParameterDeclaration,params:e}},createTypeParameterInstantiation:function(e){return{type:i.TypeParameterInstantiation,params:e}},createAnyTypeAnnotation:function(){return{type:i.AnyTypeAnnotation}},createBooleanTypeAnnotation:function(){return{type:i.BooleanTypeAnnotation}},createNumberTypeAnnotation:function(){return{type:i.NumberTypeAnnotation}},createStringTypeAnnotation:function(){return{type:i.StringTypeAnnotation}},createStringLiteralTypeAnnotation:function(e){return{type:i.StringLiteralTypeAnnotation,value:e.value,raw:o.slice(e.range[0],e.range[1])}},createVoidTypeAnnotation:function(){return{type:i.VoidTypeAnnotation}},createTypeofTypeAnnotation:function(e){return{type:i.TypeofTypeAnnotation,argument:e}},createTupleTypeAnnotation:function(e){return{type:i.TupleTypeAnnotation,types:e}},createObjectTypeAnnotation:function(e,t,r){return{type:i.ObjectTypeAnnotation,properties:e,indexers:t,callProperties:r}},createObjectTypeIndexer:function(e,t,r,n){return{type:i.ObjectTypeIndexer,id:e,key:t,value:r,"static":n}},createObjectTypeCallProperty:function(e,t){return{type:i.ObjectTypeCallProperty,value:e,"static":t}},createObjectTypeProperty:function(e,t,r,n){return{type:i.ObjectTypeProperty,key:e,value:t,optional:r,"static":n}},createUnionTypeAnnotation:function(e){return{type:i.UnionTypeAnnotation,types:e}},createIntersectionTypeAnnotation:function(e){return{type:i.IntersectionTypeAnnotation,types:e}},createTypeAlias:function(e,t,r){return{type:i.TypeAlias,id:e,typeParameters:t,right:r}},createInterface:function(e,t,r,n){return{type:i.InterfaceDeclaration,id:e,typeParameters:t,body:r,"extends":n}},createInterfaceExtends:function(e,t){return{type:i.InterfaceExtends,id:e,typeParameters:t}},createDeclareFunction:function(e){return{type:i.DeclareFunction,id:e}},createDeclareVariable:function(e){return{type:i.DeclareVariable,id:e}},createDeclareModule:function(e,t){return{type:i.DeclareModule,id:e,body:t}},createXJSAttribute:function(e,t){return{type:i.XJSAttribute,name:e,value:t||null}},createXJSSpreadAttribute:function(e){return{type:i.XJSSpreadAttribute,argument:e}},createXJSIdentifier:function(e){return{type:i.XJSIdentifier,name:e}},createXJSNamespacedName:function(e,t){return{type:i.XJSNamespacedName,namespace:e,name:t}},createXJSMemberExpression:function(e,t){return{type:i.XJSMemberExpression,object:e,property:t}},createXJSElement:function(e,t,r){return{type:i.XJSElement,openingElement:e,closingElement:t,children:r}},createXJSEmptyExpression:function(){return{type:i.XJSEmptyExpression}},createXJSExpressionContainer:function(e){return{type:i.XJSExpressionContainer,expression:e}},createXJSOpeningElement:function(e,t,r){return{type:i.XJSOpeningElement,name:e,selfClosing:r,attributes:t}},createXJSClosingElement:function(e){return{type:i.XJSClosingElement,name:e}},createIfStatement:function(e,t,r){return{type:i.IfStatement,test:e,consequent:t,alternate:r}},createLabeledStatement:function(e,t){return{type:i.LabeledStatement,label:e,body:t}},createLiteral:function(e){var t={type:i.Literal,value:e.value,raw:o.slice(e.range[0],e.range[1])};if(e.regex){t.regex=e.regex}return t},createMemberExpression:function(e,t,r){return{type:i.MemberExpression,computed:e==="[",object:t,property:r}},createNewExpression:function(e,t){return{type:i.NewExpression,callee:e,arguments:t}},createObjectExpression:function(e){return{type:i.ObjectExpression,properties:e}},createPostfixExpression:function(e,t){return{type:i.UpdateExpression,operator:e,argument:t,prefix:false}},createProgram:function(e){return{type:i.Program,body:e}},createProperty:function(e,t,r,n,a,s){return{type:i.Property,key:t,value:r,kind:e,method:n,shorthand:a,computed:s}},createReturnStatement:function(e){return{type:i.ReturnStatement,argument:e}},createSequenceExpression:function(e){return{type:i.SequenceExpression,expressions:e}},createSwitchCase:function(e,t){return{type:i.SwitchCase,test:e,consequent:t}},createSwitchStatement:function(e,t){return{type:i.SwitchStatement,discriminant:e,cases:t}},createThisExpression:function(){return{type:i.ThisExpression}},createThrowStatement:function(e){return{type:i.ThrowStatement,argument:e}},createTryStatement:function(e,t,r,n){return{type:i.TryStatement,block:e,guardedHandlers:t,handlers:r,finalizer:n}},createUnaryExpression:function(e,t){if(e==="++"||e==="--"){return{type:i.UpdateExpression,operator:e,argument:t,prefix:true}}return{type:i.UnaryExpression,operator:e,argument:t,prefix:true}},createVariableDeclaration:function(e,t){return{type:i.VariableDeclaration,declarations:e,kind:t}},createVariableDeclarator:function(e,t){return{type:i.VariableDeclarator,id:e,init:t}},createWhileStatement:function(e,t){return{type:i.WhileStatement,test:e,body:t}},createWithStatement:function(e,t){return{type:i.WithStatement,object:e,body:t}},createTemplateElement:function(e,t){return{type:i.TemplateElement,value:e,tail:t}},createTemplateLiteral:function(e,t){return{type:i.TemplateLiteral,quasis:e,expressions:t}},createSpreadElement:function(e){return{type:i.SpreadElement,argument:e}},createSpreadProperty:function(e){return{type:i.SpreadProperty,argument:e}},createTaggedTemplateExpression:function(e,t){return{type:i.TaggedTemplateExpression,tag:e,quasi:t}},createArrowFunctionExpression:function(t,r,n,a,s,o){var e={type:i.ArrowFunctionExpression,id:null,params:t,defaults:r,body:n,rest:a,generator:false,expression:s};if(o){e.async=true}return e},createMethodDefinition:function(e,t,r,n){return{type:i.MethodDefinition,key:r,value:n,kind:t,"static":e===$.static}},createClassProperty:function(e,t,r,n){return{type:i.ClassProperty,key:e,typeAnnotation:t,computed:r,"static":n}},createClassBody:function(e){return{type:i.ClassBody,body:e}},createClassImplements:function(e,t){return{type:i.ClassImplements,id:e,typeParameters:t}},createClassExpression:function(e,t,r,n,a,s){return{type:i.ClassExpression,id:e,superClass:t,body:r,typeParameters:n,superTypeParameters:a,"implements":s}},createClassDeclaration:function(e,t,r,n,a,s){return{type:i.ClassDeclaration,id:e,superClass:t,body:r,typeParameters:n,superTypeParameters:a,"implements":s}},createModuleSpecifier:function(e){return{type:i.ModuleSpecifier,value:e.value,raw:o.slice(e.range[0],e.range[1])}},createExportSpecifier:function(e,t){return{type:i.ExportSpecifier,id:e,name:t}},createExportBatchSpecifier:function(){return{type:i.ExportBatchSpecifier}},createImportDefaultSpecifier:function(e){return{type:i.ImportDefaultSpecifier,id:e}},createImportNamespaceSpecifier:function(e){return{type:i.ImportNamespaceSpecifier,id:e}},createExportDeclaration:function(e,t,r,n){return{type:i.ExportDeclaration,"default":!!e,declaration:t,specifiers:r,source:n}},createImportSpecifier:function(e,t){return{type:i.ImportSpecifier,id:e,name:t}},createImportDeclaration:function(e,t){return{type:i.ImportDeclaration,specifiers:e,source:t}},createYieldExpression:function(e,t){return{type:i.YieldExpression,argument:e,delegate:t}},createAwaitExpression:function(e){return{type:i.AwaitExpression,argument:e}},createComprehensionExpression:function(e,t,r){return{type:i.ComprehensionExpression,filter:e,blocks:t,body:r}}};function K(){var r,t,n,i;r=e;t=h;n=y;D();i=h!==t;e=r;h=t;y=n;return i}function d(r,a){var t,i=Array.prototype.slice.call(arguments,2),n=a.replace(/%(\d)/g,function(t,e){J(e<i.length,"Message reference must be in range");return i[e]});if(typeof r.lineNumber==="number"){t=new Error("Line "+r.lineNumber+": "+n);t.index=r.range[0];t.lineNumber=r.lineNumber;t.column=r.range[0]-y+1}else{t=new Error("Line "+h+": "+n);t.index=e;t.lineNumber=h;t.column=e-y+1}t.description=n;throw t}function x(){try{d.apply(null,arguments)}catch(e){if(p.errors){p.errors.push(e)}else{throw e}}}function C(e){if(e.type===u.EOF){d(e,s.UnexpectedEOS)}if(e.type===u.NumericLiteral){d(e,s.UnexpectedNumber)}if(e.type===u.StringLiteral||e.type===u.XJSText){d(e,s.UnexpectedString)}if(e.type===u.Identifier){d(e,s.UnexpectedIdentifier)}if(e.type===u.Keyword){if(_n(e.value)){d(e,s.UnexpectedReserved)}else if(g&<(e.value)){x(e,s.StrictReservedWord);return}d(e,s.UnexpectedToken,e.value)}if(e.type===u.Template){d(e,s.UnexpectedTemplate,e.value.raw)}d(e,s.UnexpectedToken,e.value)}function l(t){var e=m();if(e.type!==u.Punctuator||e.value!==t){C(e)}}function E(t,r){var e=m();if(e.type!==(r?u.Identifier:u.Keyword)||e.value!==t){C(e)}}function q(e){return E(e,true)}function n(e){return f.type===u.Punctuator&&f.value===e}function b(e,t){var r=t?u.Identifier:u.Keyword;return f.type===r&&f.value===e}function w(e){return b(e,true)}function tn(){var e;if(f.type!==u.Punctuator){return false}e=f.value;return e==="="||e==="*="||e==="/="||e==="%="||e==="+="||e==="-="||e==="<<="||e===">>="||e===">>>="||e==="&="||e==="^="||e==="|="}function nn(){return a.yieldAllowed&&b("yield",!g)}function it(){var t=f,e=false;if(w("async")){m();e=!K();ft(t)}return e}function sn(){return a.awaitAllowed&&w("await")}function k(){var t,r=e,i=h,a=y,s=f;if(o.charCodeAt(e)===59){m();return}t=h;D();if(h!==t){e=r;h=i;y=a;f=s;return}if(n(";")){m();return}if(f.type!==u.EOF&&!n("}")){C(f)}}function vt(e){return e.type===i.Identifier||e.type===i.MemberExpression}function Ln(e){return vt(e)||e.type===i.ObjectPattern||e.type===i.ArrayPattern}function gt(){var a=[],o=[],h=null,e,p=true,v,y=c();l("[");while(!n("]")){if(f.value==="for"&&f.type===u.Keyword){if(!p){d({},s.ComprehensionError)}b("for");e=Yt({ignoreBody:true});e.of=e.type===i.ForOfStatement;e.type=i.ComprehensionBlock;if(e.left.kind){d({},s.ComprehensionError)}o.push(e)}else if(f.value==="if"&&f.type===u.Keyword){if(!p){d({},s.ComprehensionError)}E("if");l("(");h=S();l(")")}else if(f.value===","&&f.type===u.Punctuator){p=false;m();a.push(null)}else{e=Lt();a.push(e);if(e&&e.type===i.SpreadElement){if(!n("]")){d({},s.ElementAfterSpreadElement)}}else if(!(n("]")||b("for")||b("if"))){l(",");p=false}}}l("]");if(h&&!o.length){d({},s.ComprehensionRequiresBlock)}if(o.length){if(a.length!==1){d({},s.ComprehensionError)}return t(y,r.createComprehensionExpression(h,o,a[0]))}return t(y,r.createArrayExpression(a))}function nt(e){var l,u,f,n,p,o,d=c();l=g;u=a.yieldAllowed;a.yieldAllowed=e.generator;f=a.awaitAllowed;a.awaitAllowed=e.async;n=e.params||[];p=e.defaults||[];o=Kt();if(e.name&&g&&_(n[0].name)){x(e.name,s.StrictParamName)}g=l;a.yieldAllowed=u;a.awaitAllowed=f;return t(d,r.createFunctionExpression(null,n,p,o,e.rest||null,e.generator,o.type!==i.BlockStatement,e.async,e.returnType,e.typeParameters))}function et(t){var r,e,n;r=g;g=true;e=mt();if(e.stricted){x(e.stricted,e.message)}n=nt({params:e.params,defaults:e.defaults,rest:e.rest,generator:t.generator,async:t.async,returnType:e.returnType,typeParameters:t.typeParameters});g=r;return n}function M(){var n=c(),e=m(),i,a;if(e.type===u.StringLiteral||e.type===u.NumericLiteral){if(g&&e.octal){x(e,s.StrictOctalLiteral)}return t(n,r.createLiteral(e))}if(e.type===u.Punctuator&&e.value==="["){n=c();i=A();a=t(n,i);l("]");return a}return t(n,r.createIdentifier(e.value))}function ei(){var i,a,o,h,d,y,e,s=c(),p;i=f;e=i.value==="[";if(i.type===u.Identifier||e||it()){o=M();if(n(":")){m();return t(s,r.createProperty("init",o,A(),false,false,e))}if(n("(")){return t(s,r.createProperty("init",o,et({generator:false,async:false}),true,false,e))}if(i.value==="get"){e=f.value==="[";a=M();l("(");l(")");if(n(":")){p=O()}return t(s,r.createProperty("get",a,nt({generator:false,async:false,returnType:p}),false,false,e))}if(i.value==="set"){e=f.value==="[";a=M();l("(");i=f;d=[rt()];l(")");if(n(":")){p=O()}return t(s,r.createProperty("set",a,nt({params:d,generator:false,async:false,name:i,returnType:p}),false,false,e))}if(i.value==="async"){e=f.value==="[";a=M();return t(s,r.createProperty("init",a,et({generator:false,async:true}),true,false,e))}if(e){C(f)}return t(s,r.createProperty("init",o,o,false,true,false))}if(i.type===u.EOF||i.type===u.Punctuator){if(!n("*")){C(i)}m();e=f.type===u.Punctuator&&f.value==="[";o=M();if(!n("(")){C(m())}return t(s,r.createProperty("init",o,et({generator:true}),true,false,e))}a=M();if(n(":")){m();return t(s,r.createProperty("init",a,A(),false,false,false))}if(n("(")){return t(s,r.createProperty("init",a,et({generator:false}),true,false,false))}C(m())}function ti(){var e=c();l("...");return t(e,r.createSpreadProperty(A()))}function pt(){var p=[],e,f,o,a,u={},d=String,m=c();l("{");while(!n("}")){if(n("...")){e=ti()}else{e=ei();if(e.key.type===i.Identifier){f=e.key.name}else{f=d(e.key.value)}a=e.kind==="init"?G.Data:e.kind==="get"?G.Get:G.Set;o="$"+f;if(Object.prototype.hasOwnProperty.call(u,o)){if(u[o]===G.Data){if(g&&a===G.Data){x({},s.StrictDuplicateProperty)}else if(a!==G.Data){x({},s.AccessorDataProperty)}}else{if(a===G.Data){x({},s.AccessorDataProperty)}else if(u[o]&a){x({},s.AccessorGetSet)}}u[o]|=a}else{u[o]=a}}p.push(e);if(!n("}")){l(",")}}l("}");return t(m,r.createObjectExpression(p))}function Sr(n){var i=c(),e=Ur(n);if(g&&e.octal){d(e,s.StrictOctalLiteral)}return t(i,r.createTemplateElement({raw:e.value.raw,cooked:e.value.cooked},e.tail))}function wt(){var e,n,i,a=c();e=Sr({head:true});n=[e];i=[];while(!e.tail){i.push(S());e=Sr({head:false});n.push(e)}return t(a,r.createTemplateLiteral(n,i))}function Qr(){var e;l("(");++a.parenthesizedCount;e=S();l(")");return e}function Zt(){var e;if(it()){e=j();if(e.type===u.Keyword&&e.value==="function"){return true}}return false}function er(){var e,i,a,o;i=f.type;if(i===u.Identifier){e=c();return t(e,r.createIdentifier(m().value))}if(i===u.StringLiteral||i===u.NumericLiteral){if(g&&f.octal){x(f,s.StrictOctalLiteral)}e=c();return t(e,r.createLiteral(m()))}if(i===u.Keyword){if(b("this")){e=c();m();return t(e,r.createThisExpression())}if(b("function")){return Mt()}if(b("class")){return ar()}if(b("super")){e=c();m();return t(e,r.createIdentifier("super"))}}if(i===u.BooleanLiteral){e=c();a=m();a.value=a.value==="true";return t(e,r.createLiteral(a))}if(i===u.NullLiteral){e=c();a=m();a.value=null;return t(e,r.createLiteral(a))}if(n("[")){return gt()}if(n("{")){return pt()}if(n("(")){return Qr()}if(n("/")||n("/=")){e=c();return t(e,r.createLiteral(N()))}if(i===u.Template){return wt()}if(n("<")){return Ft()}C(m())}function tr(){var r=[],t;l("(");if(!n(")")){while(e<v){t=Lt();r.push(t);if(n(")")){break}else if(t.type===i.SpreadElement){d({},s.ElementAfterSpreadElement)}l(",")}}l(")");return r}function Lt(){if(n("...")){var e=c();m();return t(e,r.createSpreadElement(A()))}return A()}function W(){var n=c(),e=m();if(!Ot(e)){C(e)}return t(n,r.createIdentifier(e.value))}function lr(){l(".");return W()}function hr(){var e;l("[");e=S();l("]");return e}function Bt(){var e,i,a=c();E("new");e=Mn();i=n("(")?tr():[];return t(a,r.createNewExpression(e,i))}function Tt(){var e,a,i=c();e=b("new")?Bt():er();while(n(".")||n("[")||n("(")||f.type===u.Template){if(n("(")){a=tr();e=t(i,r.createCallExpression(e,a))}else if(n("[")){e=t(i,r.createMemberExpression("[",e,hr()))}else if(n(".")){e=t(i,r.createMemberExpression(".",e,lr()))}else{e=t(i,r.createTaggedTemplateExpression(e,wt()))}}return e}function Mn(){var e,i=c();e=b("new")?Bt():er();while(n(".")||n("[")||f.type===u.Template){if(n("[")){e=t(i,r.createMemberExpression("[",e,hr()))}else if(n(".")){e=t(i,r.createMemberExpression(".",e,lr()))}else{e=t(i,r.createTaggedTemplateExpression(e,wt()))}}return e}function Xt(){var o=c(),e=Tt(),a;if(f.type!==u.Punctuator){return e}if((n("++")||n("--"))&&!K()){if(g&&e.type===i.Identifier&&_(e.name)){x({},s.StrictLHSPostfix)}if(!vt(e)){d({},s.InvalidLHSInAssignment)}a=m();e=t(o,r.createPostfixExpression(a.value,e))}return e}function Z(){var a,o,e;if(f.type!==u.Punctuator&&f.type!==u.Keyword){return Xt()}if(n("++")||n("--")){a=c();o=m();e=Z();if(g&&e.type===i.Identifier&&_(e.name)){x({},s.StrictLHSPrefix)}if(!vt(e)){d({},s.InvalidLHSInAssignment)}return t(a,r.createUnaryExpression(o.value,e))}if(n("+")||n("-")||n("~")||n("!")){a=c();o=m();e=Z();return t(a,r.createUnaryExpression(o.value,e))}if(b("delete")||b("void")||b("typeof")){a=c();o=m();e=Z();e=t(a,r.createUnaryExpression(o.value,e));if(g&&e.operator==="delete"&&e.argument.type===i.Identifier){x({},s.StrictDelete)}return e}return Xt()}function Jt(t,r){var e=0;if(t.type!==u.Punctuator&&t.type!==u.Keyword){return 0}switch(t.value){case"||":e=1;break;case"&&":e=2;break;case"|":e=3;break;case"^":e=4;break;case"&":e=5;break;case"==":case"!=":case"===":case"!==":e=6;break;case"<":case">":case"<=":case">=":case"instanceof":e=7;break;case"in":e=r?7:0;break;case"<<":case">>":case">>>":e=8;break;case"+":case"-":e=9;break;case"*":case"/":case"%":e=11;break;default:break}return e}function $n(){var n,s,u,d,e,h,y,p,l,i,o;d=a.allowIn;a.allowIn=true;i=c();p=Z();s=f;u=Jt(s,d);if(u===0){return p}s.prec=u;m();o=[i,c()];h=Z();e=[p,s,h];while((u=Jt(f,d))>0){while(e.length>2&&u<=e[e.length-2].prec){h=e.pop();y=e.pop().value;p=e.pop();n=r.createBinaryExpression(y,p,h);o.pop();i=o.pop();t(i,n);e.push(n);o.push(i)}s=m();s.prec=u;e.push(s);o.push(c());n=Z();e.push(n)}a.allowIn=d;l=e.length-1;n=e[l];o.pop();while(l>1){n=r.createBinaryExpression(e[l-1].value,e[l-2],n);l-=2;i=o.pop();t(i,n)}return n}function Wt(){var e,i,s,o,u=c();e=$n();if(n("?")){m();i=a.allowIn;a.allowIn=true;s=A();a.allowIn=i;l(":");o=A();e=t(u,r.createConditionalExpression(e,s,o))}return e}function z(e){var t,r,n,a;if(e.type===i.ObjectExpression){e.type=i.ObjectPattern;for(t=0,r=e.properties.length;t<r;t+=1){n=e.properties[t];if(n.type===i.SpreadProperty){if(t<r-1){d({},s.PropertyAfterSpreadProperty)}z(n.argument)}else{if(n.kind!=="init"){d({},s.InvalidLHSInAssignment)}z(n.value)}}}else if(e.type===i.ArrayExpression){e.type=i.ArrayPattern;for(t=0,r=e.elements.length;t<r;t+=1){a=e.elements[t];if(a){z(a)}}}else if(e.type===i.Identifier){if(_(e.name)){d({},s.InvalidLHSInAssignment)}}else if(e.type===i.SpreadElement){z(e.argument);if(e.argument.type===i.ObjectPattern){d({},s.ObjectPatternAsSpread)}}else{if(e.type!==i.MemberExpression&&e.type!==i.CallExpression&&e.type!==i.NewExpression){d({},s.InvalidLHSInAssignment)}}}function Y(a,e){var t,r,n,o;if(e.type===i.ObjectExpression){e.type=i.ObjectPattern;for(t=0,r=e.properties.length;t<r;t+=1){n=e.properties[t];if(n.type===i.SpreadProperty){if(t<r-1){d({},s.PropertyAfterSpreadProperty)}Y(a,n.argument)}else{if(n.kind!=="init"){d({},s.InvalidLHSInFormalsList)}Y(a,n.value)}}}else if(e.type===i.ArrayExpression){e.type=i.ArrayPattern;for(t=0,r=e.elements.length;t<r;t+=1){o=e.elements[t];if(o){Y(a,o)}}}else if(e.type===i.Identifier){yt(a,e,e.name)}else{if(e.type!==i.MemberExpression){d({},s.InvalidLHSInFormalsList)}}}function At(f){var n,o,e,a,r,l,t,u;a=[];r=[];l=0;u=null;t={paramSet:{}};for(n=0,o=f.length;n<o;n+=1){e=f[n];if(e.type===i.Identifier){a.push(e);r.push(null);yt(t,e,e.name)}else if(e.type===i.ObjectExpression||e.type===i.ArrayExpression){Y(t,e);a.push(e);r.push(null)}else if(e.type===i.SpreadElement){J(n===o-1,"It is guaranteed that SpreadElement is last element by parseExpression");Y(t,e.argument);u=e.argument}else if(e.type===i.AssignmentExpression){a.push(e.left);r.push(e.right);++l;yt(t,e.left,e.left.name)}else{return null}}if(t.message===s.StrictParamDupe){d(g?t.stricted:t.firstRestricted,t.message)}if(l===0){r=[]}return{params:a,defaults:r,rest:u,stricted:t.stricted,firstRestricted:t.firstRestricted,message:t.message}}function It(e,f){var s,o,u,n;l("=>");s=g;o=a.yieldAllowed;a.yieldAllowed=false;u=a.awaitAllowed;a.awaitAllowed=!!e.async;n=Kt();if(g&&e.firstRestricted){d(e.firstRestricted,e.message)}if(g&&e.stricted){x(e.stricted,e.message)}g=s;a.yieldAllowed=o;a.awaitAllowed=u;return t(f,r.createArrowFunctionExpression(e.params,e.defaults,n,e.rest,n.type!==i.BlockStatement,!!e.async))}function A(){var h,e,l,o,y,v=f,p=false;if(nn()){return on()}if(sn()){return ln()}y=a.parenthesizedCount;h=c();if(Zt()){return Mt()}if(it()){p=true;m()}if(n("(")){l=j();if(l.type===u.Punctuator&&l.value===")"||l.value==="..."){o=mt();if(!n("=>")){C(m())}o.async=p;return It(o,h)}}l=f;if(p&&!n("(")&&l.type!==u.Identifier){p=false;ft(v)}e=Wt();if(n("=>")&&(a.parenthesizedCount===y||a.parenthesizedCount===y+1)){if(e.type===i.Identifier){o=At([e])}else if(e.type===i.SequenceExpression){o=At(e.expressions)}if(o){o.async=p;return It(o,h)}}if(p){p=false;ft(v);e=Wt()}if(tn()){if(g&&e.type===i.Identifier&&_(e.name)){x(l,s.StrictLHSAssignment)}if(n("=")&&(e.type===i.ObjectExpression||e.type===i.ArrayExpression)){z(e)}else if(!vt(e)){d({},s.InvalidLHSInAssignment)}e=t(h,r.createAssignmentExpression(m().value,e,A()))}return e}function S(){var u,o,l,h,f,y,p;p=a.parenthesizedCount;u=c();o=A();l=[o];if(n(",")){while(e<v){if(!n(",")){break}m();o=Lt();l.push(o);if(o.type===i.SpreadElement){y=true;if(!n(")")){d({},s.ElementAfterSpreadElement)}break}}h=t(u,r.createSequenceExpression(l))}if(n("=>")){if(a.parenthesizedCount===p||a.parenthesizedCount===p+1){o=o.type===i.SequenceExpression?o.expressions:l;f=At(o);if(f){return It(f,u)}}C(m())}if(y&&j().value!=="=>"){d({},s.IllegalSpread)}return h||o}function en(){var r=[],t;while(e<v){if(n("}")){break}t=H();if(typeof t==="undefined"){break}r.push(t)}return r}function ht(){var e,n=c();l("{");e=en();l("}");return t(n,r.createBlockStatement(e))}function F(){var i=c(),e=[];l("<");while(!n(">")){e.push(I());if(!n(">")){l(",")}}l(">");return t(i,r.createTypeParameterDeclaration(e))}function st(){var i=c(),s=a.inType,e=[];a.inType=true;l("<");while(!n(">")){e.push(P());if(!n(">")){l(",")}}l(">");a.inType=s;return t(i,r.createTypeParameterInstantiation(e))}function ai(a,s){var e,n,i;l("[");e=M();l(":");n=P();l("]");l(":");i=P();return t(a,r.createObjectTypeIndexer(e,n,i,s))}function ur(o){var e=[],i=null,a,s=null;if(n("<")){s=F()}l("(");while(f.type===u.Identifier){e.push(bt());if(!n(")")){l(",")}}if(n("...")){m();i=bt()}l(")");l(":");a=P();return t(o,r.createFunctionTypeAnnotation(e,a,i,s))}function dn(e,i,a){var s=false,n;n=ur(e);return t(e,r.createObjectTypeProperty(a,n,s,i))}function mn(e,n){var i=c();return t(e,r.createObjectTypeCallProperty(ur(i),n))}function cr(v){var p=[],y=[],e,d=false,o=[],g,a,h,u,i;l("{");while(!n("}")){e=c();if(v&&w("static")){u=m();i=true}if(n("[")){y.push(ai(e,i))}else if(n("(")||n("<")){p.push(mn(e,v))}else{if(i&&n(":")){a=t(e,r.createIdentifier(u));x(u,s.StrictReservedWord)}else{a=M()}if(n("<")||n("(")){o.push(dn(e,i,a))}else{if(n("?")){m();d=true}l(":");h=P();o.push(t(e,r.createObjectTypeProperty(a,h,d,i)))}}if(n(";")){m()}else if(!n("}")){C(f)}}l("}");return r.createObjectTypeAnnotation(o,y,p)}function vn(){var i=c(),s=null,a=null,e,o=c;e=I();while(n(".")){l(".");e=t(i,r.createQualifiedTypeIdentifier(e,I()))}if(n("<")){a=st()}return t(i,r.createGenericTypeAnnotation(e,a))}function En(){var e=c();E("void");return t(e,r.createVoidTypeAnnotation())}function Sn(){var e,n=c();E("typeof");e=Vt();return t(n,r.createTypeofTypeAnnotation(e))}function An(){var a=c(),i=[];l("[");while(e<v&&!n("]")){i.push(P());if(n("]")){break}l(",")}l("]");return t(a,r.createTupleTypeAnnotation(i))}function bt(){var s=c(),e,i=false,a;e=I();if(n("?")){m();i=true}l(":");a=P();return t(s,r.createFunctionTypeParam(e,a,i))}function _t(){var e={params:[],rest:null};while(f.type===u.Identifier){e.params.push(bt());if(!n(")")){l(",")}}if(n("...")){m();e.rest=bt()}return e}function Vt(){var b=null,o=null,p=null,e=c(),h=null,a,v,i,g,y=false;switch(f.type){case u.Identifier:switch(f.value){case"any":m();return t(e,r.createAnyTypeAnnotation());case"bool":case"boolean":m();return t(e,r.createBooleanTypeAnnotation());case"number":m();return t(e,r.createNumberTypeAnnotation());case"string":m();return t(e,r.createStringTypeAnnotation())}return t(e,vn());case u.Punctuator:switch(f.value){case"{":return t(e,cr());case"[":return An();case"<":v=F();l("(");a=_t();o=a.params;h=a.rest;l(")");l("=>");p=P();return t(e,r.createFunctionTypeAnnotation(o,p,h,v));case"(":m();if(!n(")")&&!n("...")){if(f.type===u.Identifier){i=j();y=i.value!=="?"&&i.value!==":"}else{y=true}}if(y){g=P();l(")");if(n("=>")){d({},s.ConfusedAboutFunctionType)}return g}a=_t();o=a.params;h=a.rest;l(")");l("=>");p=P();return t(e,r.createFunctionTypeAnnotation(o,p,h,null))}break;case u.Keyword:switch(f.value){case"void":return t(e,En());case"typeof":return t(e,Sn())}break;case u.StringLiteral:i=m();if(i.octal){d(i,s.StrictOctalLiteral)}return t(e,r.createStringLiteralTypeAnnotation(i))}C(f)}function Nn(){var i=c(),e=Vt();if(n("[")){l("[");l("]");return t(i,r.createArrayTypeAnnotation(e))}return e}function kt(){var e=c();if(n("?")){m();return t(e,r.createNullableTypeAnnotation(kt()))}return Nn()}function qt(){var a=c(),i,e;i=kt();e=[i];while(n("&")){m();e.push(kt())}return e.length===1?i:t(a,r.createIntersectionTypeAnnotation(e))}function zn(){var a=c(),i,e;i=qt();e=[i];while(n("|")){m();e.push(qt())}return e.length===1?i:t(a,r.createUnionTypeAnnotation(e))}function P(){var t=a.inType,e;a.inType=true;e=zn();a.inType=t;return e}function O(){var n=c(),e;l(":");e=P();return t(n,r.createTypeAnnotation(e))}function I(){var n=c(),e=m();if(e.type!==u.Identifier){C(e)}return t(n,r.createIdentifier(e.value))}function rt(a,s){var r=c(),e=I(),i=false;if(s&&n("?")){l("?");i=true}if(a||n(":")){e.typeAnnotation=O();e=t(r,e)}if(i){e.optional=true;e=t(r,e)}return e}function ri(u){var e,f=c(),i=null,o=c();if(n("{")){e=pt();z(e);if(n(":")){e.typeAnnotation=O();t(o,e)}}else if(n("[")){e=gt();z(e);if(n(":")){e.typeAnnotation=O();t(o,e)}}else{e=a.allowKeyword?W():rt();if(g&&_(e.name)){x({},s.StrictVarName)}}if(u==="const"){if(!n("=")){d({},s.NoUnintializedConst)}l("=");i=A()}else if(n("=")){m();i=A()}return t(f,r.createVariableDeclarator(e,i))}function Ct(r){var t=[];do{t.push(ri(r));if(!n(",")){break}m()}while(e<v);return t}function kr(){var e,n=c();E("var");e=Ct();k();return t(n,r.createVariableDeclaration(e,"var"))}function Ir(e){var n,i=c();E(e);n=Ct(e);k();return t(i,r.createVariableDeclaration(n,e))}function ct(){var n=c(),e;if(f.type!==u.StringLiteral){d({},s.InvalidModuleSpecifier)}e=r.createModuleSpecifier(f);m();return t(n,e)}function Ar(){var e=c();l("*");return t(e,r.createExportBatchSpecifier())}function Tr(){var e,n=null,i=c(),a;if(b("default")){m();e=t(i,r.createIdentifier("default"))}else{e=I()}if(w("as")){m();n=W()}return t(i,r.createExportSpecifier(e,n))}function Pr(){var p,y,v,i=null,h,o=null,a=[],e=c();E("export");if(b("default")){m();if(b("function")||b("class")){p=f;m();if(Ot(f)){y=W();ft(p);return t(e,r.createExportDeclaration(true,H(),[y],null))}ft(p);switch(f.value){case"class":return t(e,r.createExportDeclaration(true,ar(),[],null));case"function":return t(e,r.createExportDeclaration(true,Mt(),[],null))}}if(w("from")){d({},s.UnexpectedToken,f.value)}if(n("{")){i=pt()}else if(n("[")){i=gt()}else{i=A()}k();return t(e,r.createExportDeclaration(true,i,[],null))}if(f.type===u.Keyword){switch(f.value){case"let":case"const":case"var":case"class":case"function":return t(e,r.createExportDeclaration(false,H(),a,null))}}if(n("*")){a.push(Ar());if(!w("from")){d({},f.value?s.UnexpectedToken:s.MissingFromClause,f.value)}m();o=ct();k();return t(e,r.createExportDeclaration(false,null,a,o))}l("{");do{h=h||b("default");a.push(Tr())}while(n(",")&&m());l("}");if(w("from")){m();o=ct();k()}else if(h){d({},f.value?s.UnexpectedToken:s.MissingFromClause,f.value)}else{k()}return t(e,r.createExportDeclaration(false,i,a,o))}function Lr(){var e,n=null,i=c();e=W();if(w("as")){m();n=I()}return t(i,r.createImportSpecifier(e,n))}function _r(){var e=[];l("{");do{e.push(Lr())}while(n(",")&&m());l("}");return e}function jr(){var e,n=c();e=W();return t(n,r.createImportDefaultSpecifier(e))}function Mr(){var e,n=c();l("*");if(!w("as")){d({},s.NoAsAfterImportNamespace)}m();e=W();return t(n,r.createImportNamespaceSpecifier(e))}function Or(){var e,i,a=c();E("import");e=[];if(f.type===u.StringLiteral){i=ct();
k();return t(a,r.createImportDeclaration(e,i))}if(!b("default")&&Ot(f)){e.push(jr());if(n(",")){m()}}if(n("*")){e.push(Mr())}else if(n("{")){e=e.concat(_r())}if(!w("from")){d({},f.value?s.UnexpectedToken:s.MissingFromClause,f.value)}m();i=ct();k();return t(a,r.createImportDeclaration(e,i))}function Dr(){var e=c();l(";");return t(e,r.createEmptyStatement())}function Rr(){var e=c(),n=S();k();return t(e,r.createExpressionStatement(n))}function Nr(){var n,i,e,a=c();E("if");l("(");n=S();l(")");i=B();if(b("else")){m();e=B()}else{e=null}return t(a,r.createIfStatement(n,i,e))}function Fr(){var e,i,s,o=c();E("do");s=a.inIteration;a.inIteration=true;e=B();a.inIteration=s;E("while");l("(");i=S();l(")");if(n(";")){m()}return t(o,r.createDoWhileStatement(e,i))}function Br(){var e,n,i,s=c();E("while");l("(");e=S();l(")");i=a.inIteration;a.inIteration=true;n=B();a.inIteration=i;return t(s,r.createWhileStatement(e,n))}function Vr(){var e=c(),n=m(),i=Ct();return t(e,r.createVariableDeclaration(i,n.value))}function Yt(g){var e,h,y,i,o,p,u,x,v=c();e=h=y=null;E("for");if(w("each")){d({},s.EachNotAllowed)}l("(");if(n(";")){m()}else{if(b("var")||b("let")||b("const")){a.allowIn=false;e=Vr();a.allowIn=true;if(e.declarations.length===1){if(b("in")||w("of")){u=f;if(!((u.value==="in"||e.kind!=="var")&&e.declarations[0].init)){m();i=e;o=S();e=null}}}}else{a.allowIn=false;e=S();a.allowIn=true;if(w("of")){u=m();i=e;o=S();e=null}else if(b("in")){if(!Ln(e)){d({},s.InvalidLHSInForIn)}u=m();i=e;o=S();e=null}}if(typeof i==="undefined"){l(";")}}if(typeof i==="undefined"){if(!n(";")){h=S()}l(";");if(!n(")")){y=S()}}l(")");x=a.inIteration;a.inIteration=true;if(!(g!==undefined&&g.ignoreBody)){p=B()}a.inIteration=x;if(typeof i==="undefined"){return t(v,r.createForStatement(e,h,y,p))}if(u.value==="in"){return t(v,r.createForInStatement(i,o,p))}return t(v,r.createForOfStatement(i,o,p))}function qr(){var n=null,l,i=c();E("continue");if(o.charCodeAt(e)===59){m();if(!a.inIteration){d({},s.IllegalContinue)}return t(i,r.createContinueStatement(null))}if(K()){if(!a.inIteration){d({},s.IllegalContinue)}return t(i,r.createContinueStatement(null))}if(f.type===u.Identifier){n=I();l="$"+n.name;if(!Object.prototype.hasOwnProperty.call(a.labelSet,l)){d({},s.UnknownLabel,n.name)}}k();if(n===null&&!a.inIteration){d({},s.IllegalContinue)}return t(i,r.createContinueStatement(n))}function Xr(){var n=null,l,i=c();E("break");if(o.charCodeAt(e)===59){m();if(!(a.inIteration||a.inSwitch)){d({},s.IllegalBreak)}return t(i,r.createBreakStatement(null))}if(K()){if(!(a.inIteration||a.inSwitch)){d({},s.IllegalBreak)}return t(i,r.createBreakStatement(null))}if(f.type===u.Identifier){n=I();l="$"+n.name;if(!Object.prototype.hasOwnProperty.call(a.labelSet,l)){d({},s.UnknownLabel,n.name)}}k();if(n===null&&!(a.inIteration||a.inSwitch)){d({},s.IllegalBreak)}return t(i,r.createBreakStatement(n))}function Gr(){var i=null,l=c();E("return");if(!a.inFunctionBody){x({},s.IllegalReturn)}if(o.charCodeAt(e)===32){if(X(o.charCodeAt(e+1))){i=S();k();return t(l,r.createReturnStatement(i))}}if(K()){return t(l,r.createReturnStatement(null))}if(!n(";")){if(!n("}")&&f.type!==u.EOF){i=S()}}k();return t(l,r.createReturnStatement(i))}function Jr(){var e,n,i=c();if(g){x({},s.StrictModeWith)}E("with");l("(");e=S();l(")");n=B();return t(i,r.createWithStatement(e,n))}function Wr(){var i,s=[],a,o=c();if(b("default")){m();i=null}else{E("case");i=S()}l(":");while(e<v){if(n("}")||b("default")||b("case")){break}a=H();if(typeof a==="undefined"){break}s.push(a)}return t(o,r.createSwitchCase(i,s))}function Hr(){var o,i,u,p,f,h=c();E("switch");l("(");o=S();l(")");l("{");i=[];if(n("}")){m();return t(h,r.createSwitchStatement(o,i))}p=a.inSwitch;a.inSwitch=true;f=false;while(e<v){if(n("}")){break}u=Wr();if(u.test===null){if(f){d({},s.MultipleDefaultsInSwitch)}f=true}i.push(u)}a.inSwitch=p;l("}");return t(h,r.createSwitchStatement(o,i))}function zr(){var e,n=c();E("throw");if(K()){d({},s.NewlineAfterThrow)}e=S();k();return t(n,r.createThrowStatement(e))}function Yr(){var e,a,o=c();E("catch");l("(");if(n(")")){C(f)}e=S();if(g&&e.type===i.Identifier&&_(e.name)){x({},s.StrictCatchVariable)}l(")");a=ht();return t(o,r.createCatchClause(e,a))}function $r(){var i,e=[],n=null,a=c();E("try");i=ht();if(b("catch")){e.push(Yr())}if(b("finally")){m();n=ht()}if(e.length===0&&!n){d({},s.NoCatchOrFinally)}return t(a,r.createTryStatement(i,[],e,n))}function Kr(){var e=c();E("debugger");k();return t(e,r.createDebuggerStatement())}function B(){var l=f.type,p,e,h,o;if(l===u.EOF){C(f)}if(l===u.Punctuator){switch(f.value){case";":return Dr();case"{":return ht();case"(":return Rr();default:break}}if(l===u.Keyword){switch(f.value){case"break":return Xr();case"continue":return qr();case"debugger":return Kr();case"do":return Fr();case"for":return Yt();case"function":return jt();case"class":return hn();case"if":return Nr();case"return":return Gr();case"switch":return Hr();case"throw":return zr();case"try":return $r();case"var":return kr();case"while":return Br();case"with":return Jr();default:break}}if(Zt()){return jt()}p=c();e=S();if(e.type===i.Identifier&&n(":")){m();o="$"+e.name;if(Object.prototype.hasOwnProperty.call(a.labelSet,o)){d({},s.Redeclaration,"Label",e.name)}a.labelSet[o]=true;h=B();delete a.labelSet[o];return t(p,r.createLabeledStatement(e,h))}k();return t(p,r.createExpressionStatement(e))}function Kt(){if(n("{")){return Pt()}return A()}function Pt(){var p,h=[],d,b,m,y,E,S,w,k,I=c();l("{");while(e<v){if(f.type!==u.StringLiteral){break}d=f;p=H();h.push(p);if(p.expression.type!==i.Literal){break}b=o.slice(d.range[0]+1,d.range[1]-1);if(b==="use strict"){g=true;if(m){x(m,s.StrictOctalLiteral)}}else{if(!m&&d.octal){m=d}}}y=a.labelSet;E=a.inIteration;S=a.inSwitch;w=a.inFunctionBody;k=a.parenthesizedCount;a.labelSet={};a.inIteration=false;a.inSwitch=false;a.inFunctionBody=true;a.parenthesizedCount=0;while(e<v){if(n("}")){break}p=H();if(typeof p==="undefined"){break}h.push(p)}l("}");a.labelSet=y;a.inIteration=E;a.inSwitch=S;a.inFunctionBody=w;a.parenthesizedCount=k;return t(I,r.createBlockStatement(h))}function yt(e,t,r){var n="$"+r;if(g){if(_(r)){e.stricted=t;e.message=s.StrictParamName}if(Object.prototype.hasOwnProperty.call(e.paramSet,n)){e.stricted=t;e.message=s.StrictParamDupe}}else if(!e.firstRestricted){if(_(r)){e.firstRestricted=t;e.message=s.StrictParamName}else if(lt(r)){e.firstRestricted=t;e.message=s.StrictReservedWord}else if(Object.prototype.hasOwnProperty.call(e.paramSet,n)){e.firstRestricted=t;e.message=s.StrictParamDupe}}e.paramSet[n]=true}function rn(r){var o,i,a,e,l;i=f;if(i.value==="..."){i=m();a=true}if(n("[")){o=c();e=gt();Y(r,e);if(n(":")){e.typeAnnotation=O();t(o,e)}}else if(n("{")){o=c();if(a){d({},s.ObjectPatternAsRestParameter)}e=pt();Y(r,e);if(n(":")){e.typeAnnotation=O();t(o,e)}}else{e=a?rt(false,false):rt(false,true);yt(r,i,i.value)}if(n("=")){if(a){x(f,s.DefaultRestParameter)}m();l=A();++r.defaultCount}if(a){if(!n(")")){d({},s.ParameterAfterRestParameter)}r.rest=e;return false}r.params.push(e);r.defaults.push(l);return!n(")")}function mt(i){var r,a=c();r={params:[],defaultCount:0,defaults:[],rest:null,firstRestricted:i};l("(");if(!n(")")){r.paramSet={};while(e<v){if(!rn(r)){break}l(",")}}l(")");if(r.defaultCount===0){r.defaults=[]}if(n(":")){r.returnType=O()}return t(a,r)}function jt(){var y,h,i,e,o,l,u,p,v,b,S,k=c(),w;p=false;if(it()){m();p=true}E("function");u=false;if(n("*")){m();u=true}i=f;y=I();if(n("<")){w=F()}if(g){if(_(i.value)){x(i,s.StrictFunctionName)}}else{if(_(i.value)){o=i;l=s.StrictFunctionName}else if(lt(i.value)){o=i;l=s.StrictReservedWord}}e=mt(o);o=e.firstRestricted;if(e.message){l=e.message}v=g;b=a.yieldAllowed;a.yieldAllowed=u;S=a.awaitAllowed;a.awaitAllowed=p;h=Pt();if(g&&o){d(o,l)}if(g&&e.stricted){x(e.stricted,l)}g=v;a.yieldAllowed=b;a.awaitAllowed=S;return t(k,r.createFunctionDeclaration(y,e.params,e.defaults,h,e.rest,u,false,p,e.returnType,w))}function Mt(){var i,h=null,o,l,e,y,u,p,v,b,S,k=c(),w;p=false;if(it()){m();p=true}E("function");u=false;if(n("*")){m();u=true}if(!n("(")){if(!n("<")){i=f;h=I();if(g){if(_(i.value)){x(i,s.StrictFunctionName)}}else{if(_(i.value)){o=i;l=s.StrictFunctionName}else if(lt(i.value)){o=i;l=s.StrictReservedWord}}}if(n("<")){w=F()}}e=mt(o);o=e.firstRestricted;if(e.message){l=e.message}v=g;b=a.yieldAllowed;a.yieldAllowed=u;S=a.awaitAllowed;a.awaitAllowed=p;y=Pt();if(g&&o){d(o,l)}if(g&&e.stricted){x(e.stricted,l)}g=v;a.yieldAllowed=b;a.awaitAllowed=S;return t(k,r.createFunctionExpression(h,e.params,e.defaults,y,e.rest,u,false,p,e.returnType,w))}function on(){var e,i,a=c();E("yield",!g);e=false;if(n("*")){m();e=true}i=A();return t(a,r.createYieldExpression(i,e))}function ln(){var e,n=c();q("await");e=A();return t(n,r.createAwaitExpression(e))}function un(i,e,v,y,g){var p,m,t,a=false,c,h,u,o,b;t=v?$.static:$.prototype;if(y){return r.createMethodDefinition(t,"",e,et({generator:true}))}u=e.type==="Identifier"&&e.name;if(u==="get"&&!n("(")){e=M();if(i[t].hasOwnProperty(e.name)){a=i[t][e.name].get===undefined&&i[t][e.name].data===undefined&&i[t][e.name].set!==undefined;if(!a){d(e,s.IllegalDuplicateClassProperty)}}else{i[t][e.name]={}}i[t][e.name].get=true;l("(");l(")");if(n(":")){o=O()}return r.createMethodDefinition(t,"get",e,nt({generator:false,returnType:o}))}if(u==="set"&&!n("(")){e=M();if(i[t].hasOwnProperty(e.name)){a=i[t][e.name].set===undefined&&i[t][e.name].data===undefined&&i[t][e.name].get!==undefined;if(!a){d(e,s.IllegalDuplicateClassProperty)}}else{i[t][e.name]={}}i[t][e.name].set=true;l("(");p=f;m=[rt()];l(")");if(n(":")){o=O()}return r.createMethodDefinition(t,"set",e,nt({params:m,generator:false,name:p,returnType:o}))}if(n("<")){h=F()}c=u==="async"&&!n("(");if(c){e=M()}if(i[t].hasOwnProperty(e.name)){d(e,s.IllegalDuplicateClassProperty)}else{i[t][e.name]={}}i[t][e.name].data=true;return r.createMethodDefinition(t,"",e,et({generator:false,async:c,typeParameters:h}))}function fn(a,t,n,i){var e;e=O();l(";");return r.createClassProperty(t,e,n,i)}function cn(s){var e,r=false,i,o=c(),a=false;if(n(";")){m();return}if(f.value==="static"){m();a=true}if(n("*")){m();r=true}e=f.value==="[";i=M();if(!r&&f.value===":"){return t(o,fn(s,i,e,a))}return t(o,un(s,i,a,r,e))}function nr(){var i,s=[],a={},o=c();a[$.static]={};a[$.prototype]={};l("{");while(e<v){if(n("}")){break}i=cn(a);if(typeof i!=="undefined"){s.push(i)}}l("}");return t(o,r.createClassBody(s))}function ir(){var a,s=[],o,i;q("implements");while(e<v){o=c();a=I();if(n("<")){i=st()}else{i=null}s.push(t(o,r.createClassImplements(a,i)));if(!n(",")){break}l(",")}return s}function ar(){var e,i,s,o=null,l,f=c(),u;E("class");if(!b("extends")&&!w("implements")&&!n("{")){e=I()}if(n("<")){u=F()}if(b("extends")){E("extends");s=a.yieldAllowed;a.yieldAllowed=false;o=Tt();if(n("<")){l=st()}a.yieldAllowed=s}if(w("implements")){i=ir()}return t(f,r.createClassExpression(e,o,nr(),u,l,i))}function hn(){var e,i,s,o=null,l,f=c(),u;E("class");e=I();if(n("<")){u=F()}if(b("extends")){E("extends");s=a.yieldAllowed;a.yieldAllowed=false;o=Tt();if(n("<")){l=st()}a.yieldAllowed=s}if(w("implements")){i=ir()}return t(f,r.createClassDeclaration(e,o,nr(),u,l,i))}function H(){var e;if(f.type===u.Keyword){switch(f.value){case"const":case"let":return Ir(f.value);case"function":return jt();default:return B()}}if(w("type")&&j().type===u.Identifier){return Gn()}if(w("interface")&&j().type===u.Identifier){return Hn()}if(w("declare")){e=j();if(e.type===u.Keyword){switch(e.value){case"class":return vr();case"function":return gr();case"var":return br()}}else if(e.type===u.Identifier&&e.value==="module"){return Kn()}}if(f.type!==u.EOF){return B()}}function or(){if(f.type===u.Keyword){switch(f.value){case"export":return Pr();case"import":return Or()}}return H()}function gn(){var t,a=[],r,l,n;while(e<v){r=f;if(r.type!==u.StringLiteral){break}t=or();a.push(t);if(t.expression.type!==i.Literal){break}l=o.slice(r.range[0]+1,r.range[1]-1);if(l==="use strict"){g=true;if(n){x(n,s.StrictOctalLiteral)}}else{if(!n&&r.octal){n=r}}}while(e<v){t=or();if(typeof t==="undefined"){break}a.push(t)}return a}function bn(){var e,n=c();g=false;dt();e=gn();return t(n,r.createProgram(e))}function xt(r,n,t,i,s){var e;J(typeof t==="number","Comment must have valid position");if(a.lastCommentStart>=t){return}a.lastCommentStart=t;e={type:r,value:n};if(p.range){e.range=[t,i]}if(p.loc){e.loc=s}p.comments.push(e);if(p.attachComment){p.leadingComments.push(e);p.trailingComments.push(e)}}function xn(){var r,t,n,i,l,a;r="";l=false;a=false;while(e<v){t=o[e];if(a){t=o[e++];if(L(t.charCodeAt(0))){n.end={line:h,column:e-y-1};a=false;xt("Line",r,i,e-1,n);if(t==="\r"&&o[e]==="\n"){++e}++h;y=e;r=""}else if(e>=v){a=false;r+=t;n.end={line:h,column:v-y};xt("Line",r,i,v,n)}else{r+=t}}else if(l){if(L(t.charCodeAt(0))){if(t==="\r"){++e;r+="\r"}if(t!=="\r"||o[e]==="\n"){r+=o[e];++h;++e;y=e;if(e>=v){d({},s.UnexpectedToken,"ILLEGAL")}}}else{t=o[e++];if(e>=v){d({},s.UnexpectedToken,"ILLEGAL")}r+=t;if(t==="*"){t=o[e];if(t==="/"){r=r.substr(0,r.length-1);l=false;++e;n.end={line:h,column:e-y};xt("Block",r,i,e,n);r=""}}}}else if(t==="/"){t=o[e+1];if(t==="/"){n={start:{line:h,column:e-y}};i=e;e+=2;a=true;if(e>=v){n.end={line:h,column:e-y};a=false;xt("Line",r,i,e,n)}}else if(t==="*"){i=e;e+=2;l=true;n={start:{line:h,column:e-y-2}};if(e>=v){d({},s.UnexpectedToken,"ILLEGAL")}}else{break}}else if(sr(t.charCodeAt(0))){++e}else if(L(t.charCodeAt(0))){++e;if(t==="\r"&&o[e]==="\n"){++e}++h;y=e}else{break}}}Rt={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"",zwj:"",lrm:"",rlm:"",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function ot(e){if(e.type===i.XJSIdentifier){return e.name}if(e.type===i.XJSNamespacedName){return e.namespace.name+":"+e.name.name}if(e.type===i.XJSMemberExpression){return ot(e.object)+"."+ot(e.property)}}function wn(e){return e!==92&&X(e)}function kn(e){return e!==92&&(e===45||at(e))}function In(){var t,r,n="";r=e;while(e<v){t=o.charCodeAt(e);if(!kn(t)){break}n+=o[e++]}return{type:u.XJSIdentifier,value:n,lineNumber:h,lineStart:y,range:[r,e]}}function Cn(){var r,t="",i=e,a=0,n;r=o[e];J(r==="&","Entity must start with an ampersand");e++;while(e<v&&a++<10){r=o[e++];if(r===";"){break}t+=r}if(r===";"){if(t[0]==="#"){if(t[1]==="x"){n=+("0"+t.substr(1))}else{n=+t.substr(1).replace(St.LeadingZeros,"")}if(!isNaN(n)){return String.fromCharCode(n)}}else if(Rt[t]){return Rt[t]}}e=i+1;return"&"}function fr(i){var t,r="",n;n=e;while(e<v){t=o[e];if(i.indexOf(t)!==-1){break}if(t==="&"){r+=Cn()}else{e++;if(t==="\r"&&o[e]==="\n"){r+=t;t=o[e];e++}if(L(t.charCodeAt(0))){++h;y=e}r+=t}}return{type:u.XJSText,value:r,lineNumber:h,lineStart:y,range:[n,e]}}function Tn(){var r,t,n;t=o[e];J(t==="'"||t==='"',"String literal must starts with a quote");n=e;++e;r=fr([t]);if(t!==o[e]){d({},s.UnexpectedToken,"ILLEGAL")}++e;r.range=[n,e];return r}function Pn(){var t=o.charCodeAt(e);if(t!==123&&t!==60){return fr(["<","{"])}return U()}function Q(){var e,n=c();if(f.type!==u.XJSIdentifier){C(f)}e=m();return t(n,r.createXJSIdentifier(e.value))}function pr(){var e,n,i=c();e=Q();l(":");n=Q();return t(i,r.createXJSNamespacedName(e,n))}function jn(){var i=c(),e=Q();while(n(".")){m();e=t(i,r.createXJSMemberExpression(e,Q()))}return e}function dr(){if(j().value===":"){return pr()}if(j().value==="."){return jn()}return Q()}function On(){if(j().value===":"){return pr()}return Q()}function Dn(){var e,a;if(n("{")){e=mr();if(e.expression.type===i.XJSEmptyExpression){d(e,"XJS attributes must only be assigned a non-empty "+"expression")}}else if(n("<")){e=Ft()}else if(f.type===u.XJSText){a=c();e=t(a,r.createLiteral(m()))}else{d({},s.InvalidXJSAttributeValue)}return e}function Rn(){var n=Ut();while(o.charAt(e)!=="}"){e++}return t(n,r.createXJSEmptyExpression())}function mr(){var e,i,s,o=c();i=a.inXJSChild;s=a.inXJSTag;a.inXJSChild=false;a.inXJSTag=false;l("{");if(n("}")){e=Rn()}else{e=S()}a.inXJSChild=i;a.inXJSTag=s;l("}");return t(o,r.createXJSExpressionContainer(e))}function Fn(){var e,n,i,s=c();n=a.inXJSChild;i=a.inXJSTag;a.inXJSChild=false;a.inXJSTag=false;l("{");l("...");e=A();a.inXJSChild=n;a.inXJSTag=i;l("}");return t(s,r.createXJSSpreadAttribute(e))}function Bn(){var e,i;if(n("{")){return Fn()}i=c();e=On();if(n("=")){m();return t(i,r.createXJSAttribute(e,Dn()))}return t(i,r.createXJSAttribute(e))}function Vn(){var e,i;if(n("{")){e=mr()}else if(f.type===u.XJSText){i=Ut();e=t(i,r.createLiteral(m()))}else{e=Ft()}return e}function Un(){var e,n,i,s=c();n=a.inXJSChild;i=a.inXJSTag;a.inXJSChild=false;a.inXJSTag=true;l("<");l("/");e=dr();a.inXJSChild=n;a.inXJSTag=i;l(">");return t(s,r.createXJSClosingElement(e))}function qn(){var n,d,i=[],s=false,o,u,p=c();o=a.inXJSChild;u=a.inXJSTag;a.inXJSChild=false;a.inXJSTag=true;l("<");n=dr();while(e<v&&f.value!=="/"&&f.value!==">"){i.push(Bn())}a.inXJSTag=u;if(f.value==="/"){l("/");a.inXJSChild=o;l(">");s=true}else{a.inXJSChild=true;l(">")}return t(p,r.createXJSOpeningElement(n,i,s))}function Ft(){var i,o=null,u=[],l,p,m=c();l=a.inXJSChild;p=a.inXJSTag;i=qn();if(!i.selfClosing){while(e<v){a.inXJSChild=false;if(f.value==="<"&&j().value==="/"){break}a.inXJSChild=true;u.push(Vn())}a.inXJSChild=l;a.inXJSTag=p;o=Un();if(ot(o.name)!==ot(i.name)){d({},s.ExpectedXJSClosingTag,ot(i.name))}}if(!l&&n("<")){d(f,s.AdjacentXJSElements)}return t(m,r.createXJSElement(i,o,u))}function Gn(){var e,s=c(),i=null,a;q("type");e=I();if(n("<")){i=F()}l("=");a=P();k();return t(s,r.createTypeAlias(e,i,a))}function Jn(){var a=c(),e,i=null;e=I();if(n("<")){i=st()}return t(a,r.createInterfaceExtends(e,i))}function yr(f,p){var i,a,s=[],o,u=null;o=I();if(n("<")){u=F()}if(b("extends")){E("extends");while(e<v){s.push(Jn());if(!n(",")){break}l(",")}}a=c();i=t(a,cr(p));return t(f,r.createInterface(o,u,i,s))}function Hn(){var t,r,n=[],i,e=c(),a=null;q("interface");return yr(e,false)}function vr(){var t=c(),e;q("declare");E("class");e=yr(t,true);e.type=i.DeclareClass;return e}function gr(){var e,s,m=c(),o,u,f,i,p=null,d,a;q("declare");E("function");s=c();e=I();a=c();if(n("<")){p=F()}l("(");i=_t();o=i.params;f=i.rest;l(")");l(":");u=P();d=t(a,r.createFunctionTypeAnnotation(o,u,f,p));e.typeAnnotation=t(a,r.createTypeAnnotation(d));t(s,e);k();return t(m,r.createDeclareFunction(e))}function br(){var e,n=c();q("declare");E("var");e=rt();k();return t(n,r.createDeclareVariable(e))}function Kn(){var i=[],o,a,p,h=c(),d;q("declare");q("module");if(f.type===u.StringLiteral){if(g&&f.octal){x(f,s.StrictOctalLiteral)}p=c();a=t(p,r.createLiteral(m()))}else{a=I()}o=c();l("{");while(e<v&&!n("}")){d=j();switch(d.value){case"class":i.push(vr());break;case"function":i.push(gr());break;case"var":i.push(br());break;default:C(f)}}l("}");return t(h,r.createDeclareModule(a,t(o,r.createBlockStatement(i))))}function Qn(){var l,r,t,i,s,n;if(!a.inXJSChild){D()}l=e;r={start:{line:h,column:e-y}};t=p.advance();r.end={line:h,column:e-y};if(t.type!==u.EOF){i=[t.range[0],t.range[1]];s=o.slice(t.range[0],t.range[1]);n={type:T[t.type],value:s,range:i,loc:r};if(t.regex){n.regex={pattern:t.regex.pattern,flags:t.regex.flags}}p.tokens.push(n)}return t}function Zn(){var n,i,r,t;D();n=e;i={start:{line:h,column:e-y}};r=p.scanRegExp();i.end={line:h,column:e-y};if(!p.tokenize){if(p.tokens.length>0){t=p.tokens[p.tokens.length-1];if(t.range[0]===n&&t.type==="Punctuator"){if(t.value==="/"||t.value==="/="){p.tokens.pop()}}}p.tokens.push({type:"RegularExpression",value:r.literal,regex:r.regex,range:[n,e],loc:i})}return r}function Er(){var r,e,t,n=[];for(r=0;r<p.tokens.length;++r){e=p.tokens[r];t={type:e.type,value:e.value};if(e.regex){t.regex={pattern:e.regex.pattern,flags:e.regex.flags}}if(p.range){t.range=e.range}if(p.loc){t.loc=e.loc}n.push(t)}p.tokens=n}function xr(){if(p.comments){p.skipComment=D;D=xn}if(typeof p.tokens!=="undefined"){p.advance=tt;p.scanRegExp=N;tt=Qn;N=Zn}}function $t(){if(typeof p.skipComment==="function"){D=p.skipComment}if(typeof p.scanRegExp==="function"){tt=p.advance;N=p.scanRegExp}}function ni(t,r){var e,n={};for(e in t){if(t.hasOwnProperty(e)){n[e]=t[e]}}for(e in r){if(r.hasOwnProperty(e)){n[e]=r[e]}}return n}function ii(n,t){var l,s,i;l=String;if(typeof n!=="string"&&!(n instanceof String)){n=l(n)}r=Nt;o=n;e=0;h=o.length>0?1:0;y=0;v=o.length;f=null;a={allowKeyword:true,allowIn:true,labelSet:{},inFunctionBody:false,inIteration:false,inSwitch:false,lastCommentStart:-1};p={};t=t||{};t.tokens=true;p.tokens=[];p.tokenize=true;p.openParenToken=-1;p.openCurlyToken=-1;p.range=typeof t.range==="boolean"&&t.range;p.loc=typeof t.loc==="boolean"&&t.loc;if(typeof t.comment==="boolean"&&t.comment){p.comments=[]}if(typeof t.tolerant==="boolean"&&t.tolerant){p.errors=[]}if(v>0){if(typeof o[0]==="undefined"){if(n instanceof String){o=n.valueOf()}}}xr();try{dt();if(f.type===u.EOF){return p.tokens}s=m();while(f.type!==u.EOF){try{s=m()}catch(c){s=f;if(p.errors){p.errors.push(c);break}else{throw c}}}Er();i=p.tokens;if(typeof p.comments!=="undefined"){i.comments=p.comments}if(typeof p.errors!=="undefined"){i.errors=p.errors}}catch(d){throw d}finally{$t();p={}}return i}function Cr(n,t){var i,s;s=String;if(typeof n!=="string"&&!(n instanceof String)){n=s(n)}r=Nt;o=n;e=0;h=o.length>0?1:0;y=0;v=o.length;f=null;a={allowKeyword:false,allowIn:true,labelSet:{},parenthesizedCount:0,inFunctionBody:false,inIteration:false,inSwitch:false,inXJSChild:false,inXJSTag:false,inType:false,lastCommentStart:-1,yieldAllowed:false,awaitAllowed:false};p={};if(typeof t!=="undefined"){p.range=typeof t.range==="boolean"&&t.range;p.loc=typeof t.loc==="boolean"&&t.loc;p.attachComment=typeof t.attachComment==="boolean"&&t.attachComment;if(p.loc&&t.source!==null&&t.source!==undefined){r=ni(r,{postProcess:function(e){e.loc.source=s(t.source);return e}})}if(typeof t.tokens==="boolean"&&t.tokens){p.tokens=[]}if(typeof t.comment==="boolean"&&t.comment){p.comments=[]}if(typeof t.tolerant==="boolean"&&t.tolerant){p.errors=[]}if(p.attachComment){p.range=true;p.comments=[];p.bottomRightStack=[];p.trailingComments=[];p.leadingComments=[]}}if(v>0){if(typeof o[0]==="undefined"){if(n instanceof String){o=n.valueOf()}}}xr();try{i=bn();if(typeof p.comments!=="undefined"){i.comments=p.comments}if(typeof p.tokens!=="undefined"){Er();i.tokens=p.tokens}if(typeof p.errors!=="undefined"){i.errors=p.errors}}catch(l){throw l}finally{$t();p={}}return i}Et.version="8001.1001.0-dev-harmony-fb";Et.tokenize=ii;Et.parse=Cr;Et.Syntax=function(){var e,t={};if(typeof Object.create==="function"){t=Object.create(null)}for(e in i){if(i.hasOwnProperty(e)){t[e]=i[e]}}if(typeof Object.freeze==="function"){Object.freeze(t)}return t}()})},{}],148:[function(o,b,v){var i=o("assert");var s=o("recast").types;var E=s.builtInTypes.array;var e=s.builders;var t=s.namedTypes;var a=o("./leap");var u=o("./meta");var c=o("./util");var d=c.runtimeProperty("keys");var l=Object.prototype.hasOwnProperty;function f(e){i.ok(this instanceof f);t.Identifier.assert(e);Object.defineProperties(this,{contextId:{value:e},listing:{value:[]},marked:{value:[true]},finalLoc:{value:r()},tryEntries:{value:[]}});Object.defineProperties(this,{leapManager:{value:new a.LeapManager(this)}})}var n=f.prototype;v.Emitter=f;function r(){return e.literal(-1)}n.mark=function(e){t.Literal.assert(e);var r=this.listing.length;if(e.value===-1){e.value=r}else{i.strictEqual(e.value,r)}this.marked[r]=true;return e};n.emit=function(r){if(t.Expression.check(r))r=e.expressionStatement(r);t.Statement.assert(r);this.listing.push(r)};n.emitAssign=function(e,t){this.emit(this.assign(e,t));return e};n.assign=function(t,r){return e.expressionStatement(e.assignmentExpression("=",t,r))};n.contextProperty=function(t,r){return e.memberExpression(this.contextId,r?e.literal(t):e.identifier(t),!!r)};var m={prev:true,next:true,sent:true,rval:true};n.isVolatileContextProperty=function(e){if(t.MemberExpression.check(e)){if(e.computed){return true}if(t.Identifier.check(e.object)&&t.Identifier.check(e.property)&&e.object.name===this.contextId.name&&l.call(m,e.property.name)){return true}}return false};n.stop=function(e){if(e){this.setReturnValue(e)}this.jump(this.finalLoc)};n.setReturnValue=function(e){t.Expression.assert(e.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(e))};n.clearPendingException=function(r,n){t.Literal.assert(r);var i=e.callExpression(this.contextProperty("catch",true),[r]);if(n){this.emitAssign(n,i)}else{this.emit(i)}};n.jump=function(t){this.emitAssign(this.contextProperty("next"),t);this.emit(e.breakStatement())};n.jumpIf=function(r,n){t.Expression.assert(r);t.Literal.assert(n);this.emit(e.ifStatement(r,e.blockStatement([this.assign(this.contextProperty("next"),n),e.breakStatement()])))};n.jumpIfNot=function(r,i){t.Expression.assert(r);t.Literal.assert(i);var n;if(t.UnaryExpression.check(r)&&r.operator==="!"){n=r.argument}else{n=e.unaryExpression("!",r)}this.emit(e.ifStatement(n,e.blockStatement([this.assign(this.contextProperty("next"),i),e.breakStatement()])))};var h=0;n.makeTempVar=function(){return this.contextProperty("t"+h++)};n.getContextFunction=function(t){return e.functionExpression(t||null,[this.contextId],e.blockStatement([this.getDispatchLoop()]),false,false)};n.getDispatchLoop=function(){var n=this;var t=[];var i;var r=false;n.listing.forEach(function(a,s){if(n.marked.hasOwnProperty(s)){t.push(e.switchCase(e.literal(s),i=[]));r=false}if(!r){i.push(a);if(y(a))r=true}});this.finalLoc.value=this.listing.length;t.push(e.switchCase(this.finalLoc,[]),e.switchCase(e.literal("end"),[e.returnStatement(e.callExpression(this.contextProperty("stop"),[]))]));return e.whileStatement(e.literal(1),e.switchStatement(e.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),t))};function y(e){return t.BreakStatement.check(e)||t.ContinueStatement.check(e)||t.ReturnStatement.check(e)||t.ThrowStatement.check(e)}n.getTryEntryList=function(){if(this.tryEntries.length===0){return null}var t=0;return e.arrayExpression(this.tryEntries.map(function(r){var n=r.firstLoc.value;i.ok(n>=t,"try entries out of order");t=n;var a=r.catchEntry;var s=r.finallyEntry;var o=[r.firstLoc,a?a.firstLoc:null];if(s){o[2]=s.firstLoc}return e.arrayExpression(o)}))};n.explode=function(r,a){i.ok(r instanceof s.NodePath);var e=r.value;var n=this;t.Node.assert(e);if(t.Statement.check(e))return n.explodeStatement(r);if(t.Expression.check(e))return n.explodeExpression(r,a);if(t.Declaration.check(e))throw p(e);switch(e.type){case"Program":return r.get("body").map(n.explodeStatement,n);case"VariableDeclarator":throw p(e);case"Property":case"SwitchCase":case"CatchClause":throw new Error(e.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+JSON.stringify(e.type))}};function p(e){return new Error("all declarations should have been transformed into "+"assignments before the Exploder began its work: "+JSON.stringify(e))}n.explodeStatement=function(o,p){i.ok(o instanceof s.NodePath);var l=o.value;var n=this;t.Statement.assert(l);if(p){t.Identifier.assert(p)}else{p=null}if(t.BlockStatement.check(l)){return o.get("body").each(n.explodeStatement,n)}if(!u.containsLeap(l)){n.emit(l);return}switch(l.type){case"ExpressionStatement":n.explodeExpression(o.get("expression"),true);break;case"LabeledStatement":var f=r();n.leapManager.withEntry(new a.LabeledEntry(f,l.label),function(){n.explodeStatement(o.get("body"),l.label)});n.mark(f);break;case"WhileStatement":var S=r();var f=r();n.mark(S);n.jumpIfNot(n.explodeExpression(o.get("test")),f);n.leapManager.withEntry(new a.LoopEntry(f,S,p),function(){n.explodeStatement(o.get("body"))});n.jump(S);n.mark(f);break;case"DoWhileStatement":var P=r();var T=r();var f=r();n.mark(P);n.leapManager.withEntry(new a.LoopEntry(f,T,p),function(){n.explode(o.get("body"))});n.mark(T);n.jumpIf(n.explodeExpression(o.get("test")),P);n.mark(f);break;case"ForStatement":var v=r();var j=r();var f=r();if(l.init){n.explode(o.get("init"),true)}n.mark(v);if(l.test){n.jumpIfNot(n.explodeExpression(o.get("test")),f)}else{}n.leapManager.withEntry(new a.LoopEntry(f,j,p),function(){n.explodeStatement(o.get("body"))});n.mark(j);if(l.update){n.explode(o.get("update"),true)}n.jump(v);n.mark(f);break;case"ForInStatement":t.Identifier.assert(l.left);var v=r();var f=r();var M=n.makeTempVar();n.emitAssign(M,e.callExpression(d,[n.explodeExpression(o.get("right"))]));n.mark(v);var A=n.makeTempVar();n.jumpIf(e.memberExpression(e.assignmentExpression("=",A,e.callExpression(M,[])),e.identifier("done"),false),f);n.emitAssign(l.left,e.memberExpression(A,e.identifier("value"),false));n.leapManager.withEntry(new a.LoopEntry(f,v,p),function(){n.explodeStatement(o.get("body"))});n.jump(v);n.mark(f);break;case"BreakStatement":n.emitAbruptCompletion({type:"break",target:n.leapManager.getBreakLoc(l.label)});break;case"ContinueStatement":n.emitAbruptCompletion({type:"continue",target:n.leapManager.getContinueLoc(l.label)});break;case"SwitchStatement":var O=n.emitAssign(n.makeTempVar(),n.explodeExpression(o.get("discriminant")));var f=r();var g=r();var w=g;var k=[];var L=l.cases||[];for(var y=L.length-1;y>=0;--y){var I=L[y];t.SwitchCase.assert(I);if(I.test){w=e.conditionalExpression(e.binaryExpression("===",O,I.test),k[y]=r(),w)}else{k[y]=g}}n.jump(n.explodeExpression(new s.NodePath(w,o,"discriminant")));n.leapManager.withEntry(new a.SwitchEntry(f),function(){o.get("cases").each(function(e){var r=e.value;var t=e.name;n.mark(k[t]);e.get("consequent").each(n.explodeStatement,n)})});n.mark(f);if(g.value===-1){n.mark(g);i.strictEqual(f.value,g.value)}break;case"IfStatement":var C=l.alternate&&r();var f=r();n.jumpIfNot(n.explodeExpression(o.get("test")),C||f);n.explodeStatement(o.get("consequent"));if(C){n.jump(f);n.mark(C);n.explodeStatement(o.get("alternate"))}n.mark(f);
break;case"ReturnStatement":n.emitAbruptCompletion({type:"return",value:n.explodeExpression(o.get("argument"))});break;case"WithStatement":throw new Error(node.type+" not supported in generator functions.");case"TryStatement":var f=r();var h=l.handler;if(!h&&l.handlers){h=l.handlers[0]||null}var E=h&&r();var _=E&&new a.CatchEntry(E,h.param);var m=l.finalizer&&r();var x=m&&new a.FinallyEntry(m);var b=new a.TryEntry(n.getUnmarkedCurrentLoc(),_,x);n.tryEntries.push(b);n.updateContextPrevLoc(b.firstLoc);n.leapManager.withEntry(b,function(){n.explodeStatement(o.get("block"));if(E){if(m){n.jump(m)}else{n.jump(f)}n.updateContextPrevLoc(n.mark(E));var l=o.get("handler","body");var u=n.makeTempVar();n.clearPendingException(b.firstLoc,u);var r=l.scope;var a=h.param.name;t.CatchClause.assert(r.node);i.strictEqual(r.lookup(a),r);s.visit(l,{visitIdentifier:function(e){if(c.isReference(e,a)&&e.scope.lookup(a)===r){return u}this.traverse(e)},visitFunction:function(e){if(e.scope.declares(a)){return false}this.traverse(e)}});n.leapManager.withEntry(_,function(){n.explodeStatement(l)})}if(m){n.updateContextPrevLoc(n.mark(m));n.leapManager.withEntry(x,function(){n.explodeStatement(o.get("finalizer"))});n.emit(e.callExpression(n.contextProperty("finish"),[x.firstLoc]))}});n.mark(f);break;case"ThrowStatement":n.emit(e.throwStatement(n.explodeExpression(o.get("argument"))));break;default:throw new Error("unknown Statement of type "+JSON.stringify(l.type))}};n.emitAbruptCompletion=function(r){if(!g(r)){i.ok(false,"invalid completion record: "+JSON.stringify(r))}i.notStrictEqual(r.type,"normal","normal completions are not abrupt");var n=[e.literal(r.type)];if(r.type==="break"||r.type==="continue"){t.Literal.assert(r.target);n[1]=r.target}else if(r.type==="return"||r.type==="throw"){if(r.value){t.Expression.assert(r.value);n[1]=r.value}}this.emit(e.returnStatement(e.callExpression(this.contextProperty("abrupt"),n)))};function g(e){var r=e.type;if(r==="normal"){return!l.call(e,"target")}if(r==="break"||r==="continue"){return!l.call(e,"value")&&t.Literal.check(e.target)}if(r==="return"||r==="throw"){return l.call(e,"value")&&!l.call(e,"target")}return false}n.getUnmarkedCurrentLoc=function(){return e.literal(this.listing.length)};n.updateContextPrevLoc=function(e){if(e){t.Literal.assert(e);if(e.value===-1){e.value=this.listing.length}else{i.strictEqual(e.value,this.listing.length)}}else{e=this.getUnmarkedCurrentLoc()}this.emitAssign(this.contextProperty("prev"),e)};n.explodeExpression=function(a,d){i.ok(a instanceof s.NodePath);var o=a.value;if(o){t.Expression.assert(o)}else{return o}var n=this;var l;function c(e){t.Expression.assert(e);if(d){n.emit(e)}else{return e}}if(!u.containsLeap(o)){return c(o)}var E=u.containsLeap.onlyChildren(o);function f(t,a,r){i.ok(a instanceof s.NodePath);i.ok(!r||!t,"Ignoring the result of a child expression but forcing it to "+"be assigned to a temporary variable?");var e=n.explodeExpression(a,r);if(r){}else if(t||E&&(n.isVolatileContextProperty(e)||u.hasSideEffects(e))){e=n.emitAssign(t||n.makeTempVar(),e)}return e}switch(o.type){case"MemberExpression":return c(e.memberExpression(n.explodeExpression(a.get("object")),o.computed?f(null,a.get("property")):o.property,o.computed));case"CallExpression":var g=a.get("callee");var m=n.explodeExpression(g);if(!t.MemberExpression.check(g.node)&&t.MemberExpression.check(m)){m=e.sequenceExpression([e.literal(0),m])}return c(e.callExpression(m,a.get("arguments").map(function(e){return f(null,e)})));case"NewExpression":return c(e.newExpression(f(null,a.get("callee")),a.get("arguments").map(function(e){return f(null,e)})));case"ObjectExpression":return c(e.objectExpression(a.get("properties").map(function(t){return e.property(t.value.kind,t.value.key,f(null,t.get("value")))})));case"ArrayExpression":return c(e.arrayExpression(a.get("elements").map(function(e){return f(null,e)})));case"SequenceExpression":var b=o.expressions.length-1;a.get("expressions").each(function(e){if(e.name===b){l=n.explodeExpression(e,d)}else{n.explodeExpression(e,true)}});return l;case"LogicalExpression":var p=r();if(!d){l=n.makeTempVar()}var y=f(l,a.get("left"));if(o.operator==="&&"){n.jumpIfNot(y,p)}else{i.strictEqual(o.operator,"||");n.jumpIf(y,p)}f(l,a.get("right"),d);n.mark(p);return l;case"ConditionalExpression":var v=r();var p=r();var x=n.explodeExpression(a.get("test"));n.jumpIfNot(x,v);if(!d){l=n.makeTempVar()}f(l,a.get("consequent"),d);n.jump(p);n.mark(v);f(l,a.get("alternate"),d);n.mark(p);return l;case"UnaryExpression":return c(e.unaryExpression(o.operator,n.explodeExpression(a.get("argument")),!!o.prefix));case"BinaryExpression":return c(e.binaryExpression(o.operator,f(null,a.get("left")),f(null,a.get("right"))));case"AssignmentExpression":return c(e.assignmentExpression(o.operator,n.explodeExpression(a.get("left")),n.explodeExpression(a.get("right"))));case"UpdateExpression":return c(e.updateExpression(o.operator,n.explodeExpression(a.get("argument")),o.prefix));case"YieldExpression":var p=r();var h=o.argument&&n.explodeExpression(a.get("argument"));if(h&&o.delegate){var l=n.makeTempVar();n.emit(e.returnStatement(e.callExpression(n.contextProperty("delegateYield"),[h,e.literal(l.property.name),p])));n.mark(p);return l}n.emitAssign(n.contextProperty("next"),p);n.emit(e.returnStatement(h||null));n.mark(p);return n.contextProperty("sent");default:throw new Error("unknown Expression of type "+JSON.stringify(o.type))}}},{"./leap":150,"./meta":151,"./util":152,assert:103,recast:146}],149:[function(n,o,i){var a=n("assert");var r=n("recast").types;var t=r.namedTypes;var e=r.builders;var s=Object.prototype.hasOwnProperty;i.hoist=function(n){a.ok(n instanceof r.NodePath);t.Function.assert(n.value);var i={};function o(n,a){t.VariableDeclaration.assert(n);var r=[];n.declarations.forEach(function(t){i[t.id.name]=t.id;if(t.init){r.push(e.assignmentExpression("=",t.id,t.init))}else if(a){r.push(t.id)}});if(r.length===0)return null;if(r.length===1)return r[0];return e.sequenceExpression(r)}r.visit(n.get("body"),{visitVariableDeclaration:function(t){var r=o(t.value,false);if(r===null){t.replace()}else{return e.expressionStatement(r)}return false},visitForStatement:function(e){var r=e.value.init;if(t.VariableDeclaration.check(r)){e.get("init").replace(o(r,false))}this.traverse(e)},visitForInStatement:function(e){var r=e.value.left;if(t.VariableDeclaration.check(r)){e.get("left").replace(o(r,true))}this.traverse(e)},visitFunctionDeclaration:function(n){var r=n.value;i[r.id.name]=r.id;var s=n.parent.node;var a=e.expressionStatement(e.assignmentExpression("=",r.id,e.functionExpression(r.id,r.params,r.body,r.generator,r.expression)));if(t.BlockStatement.check(n.parent.node)){n.parent.get("body").unshift(a);n.replace()}else{n.replace(a)}return false},visitFunctionExpression:function(e){return false}});var u={};n.get("params").each(function(r){var e=r.value;if(t.Identifier.check(e)){u[e.name]=e}else{}});var l=[];Object.keys(i).forEach(function(t){if(!s.call(u,t)){l.push(e.variableDeclarator(i[t],null))}});if(l.length===0){return null}return e.variableDeclaration("var",l)}},{assert:103,recast:146}],150:[function(a,y,r){var n=a("assert");var p=a("recast").types;var t=p.namedTypes;var g=p.builders;var i=a("util").inherits;var v=Object.prototype.hasOwnProperty;function e(){n.ok(this instanceof e)}function u(r){e.call(this);t.Literal.assert(r);this.returnLoc=r}i(u,e);r.FunctionEntry=u;function h(n,i,r){e.call(this);t.Literal.assert(n);t.Literal.assert(i);if(r){t.Identifier.assert(r)}else{r=null}this.breakLoc=n;this.continueLoc=i;this.label=r}i(h,e);r.LoopEntry=h;function m(r){e.call(this);t.Literal.assert(r);this.breakLoc=r}i(m,e);r.SwitchEntry=m;function d(a,r,i){e.call(this);t.Literal.assert(a);if(r){n.ok(r instanceof f)}else{r=null}if(i){n.ok(i instanceof c)}else{i=null}n.ok(r||i);this.firstLoc=a;this.catchEntry=r;this.finallyEntry=i}i(d,e);r.TryEntry=d;function f(r,n){e.call(this);t.Literal.assert(r);t.Identifier.assert(n);this.firstLoc=r;this.paramId=n}i(f,e);r.CatchEntry=f;function c(r){e.call(this);t.Literal.assert(r);this.firstLoc=r}i(c,e);r.FinallyEntry=c;function l(r,n){e.call(this);t.Literal.assert(r);t.Identifier.assert(n);this.breakLoc=r;this.label=n}i(l,e);r.LabeledEntry=l;function o(e){n.ok(this instanceof o);var t=a("./emit").Emitter;n.ok(e instanceof t);this.emitter=e;this.entryStack=[new u(e.finalLoc)]}var s=o.prototype;r.LeapManager=o;s.withEntry=function(t,r){n.ok(t instanceof e);this.entryStack.push(t);try{r.call(this.emitter)}finally{var i=this.entryStack.pop();n.strictEqual(i,t)}};s._findLeapLocation=function(i,n){for(var t=this.entryStack.length-1;t>=0;--t){var e=this.entryStack[t];var r=e[i];if(r){if(n){if(e.label&&e.label.name===n.name){return r}}else if(e instanceof l){}else{return r}}}return null};s.getBreakLoc=function(e){return this._findLeapLocation("breakLoc",e)};s.getContinueLoc=function(e){return this._findLeapLocation("continueLoc",e)}},{"./emit":148,assert:103,recast:146,util:127}],151:[function(n,d,l){var c=n("assert");var u=n("private").makeAccessor();var i=n("recast").types;var f=i.builtInTypes.array;var r=i.namedTypes;var t=Object.prototype.hasOwnProperty;function s(e,s){function a(t){r.Node.assert(t);var e=false;function a(t){if(e){}else if(f.check(t)){t.some(a)}else if(r.Node.check(t)){c.strictEqual(e,false);e=n(t)}return e}i.eachField(t,function(t,e){a(e)});return e}function n(n){r.Node.assert(n);var i=u(n);if(t.call(i,e))return i[e];if(t.call(p,n.type))return i[e]=false;if(t.call(s,n.type))return i[e]=true;return i[e]=a(n)}n.onlyChildren=a;return n}var p={FunctionExpression:true};var o={CallExpression:true,ForInStatement:true,UnaryExpression:true,BinaryExpression:true,AssignmentExpression:true,UpdateExpression:true,NewExpression:true};var e={YieldExpression:true,BreakStatement:true,ContinueStatement:true,ReturnStatement:true,ThrowStatement:true};for(var a in e){if(t.call(e,a)){o[a]=e[a]}}l.hasSideEffects=s("hasSideEffects",o);l.containsLeap=s("containsLeap",e)},{assert:103,"private":136,recast:146}],152:[function(r,s,e){var o=r("assert");var n=r("recast").types;var a=n.namedTypes;var t=n.builders;var i=Object.prototype.hasOwnProperty;e.defaults=function(r){var a=arguments.length;var e;for(var n=1;n<a;++n){if(e=arguments[n]){for(var t in e){if(i.call(e,t)&&!i.call(r,t)){r[t]=e[t]}}}}return r};e.runtimeProperty=function(e){return t.memberExpression(t.identifier("regeneratorRuntime"),t.identifier(e),false)};e.isReference=function(e,n){var r=e.value;if(!a.Identifier.check(r)){return false}if(n&&r.name!==n){return false}var t=e.parent.value;switch(t.type){case"VariableDeclarator":return e.name==="init";case"MemberExpression":return e.name==="object"||t.computed&&e.name==="property";case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":if(e.name==="id"){return false}if(t.params===e.parentPath&&t.params[e.name]===r){return false}return true;case"ClassDeclaration":case"ClassExpression":return e.name!=="id";case"CatchClause":return e.name!=="param";case"Property":case"MethodDefinition":return e.name!=="key";case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"LabeledStatement":return false;default:return true}}},{assert:103,recast:146}],153:[function(n,E,m){var y=n("assert");var l=n("fs");var i=n("recast");var r=i.types;var t=r.namedTypes;var e=r.builders;var w=r.builtInTypes.array;var S=r.builtInTypes.object;var x=r.NodePath;var b=n("./hoist").hoist;var d=n("./emit").Emitter;var a=n("./util").runtimeProperty;var h=a("wrap");var o=a("mark");var v=a("values");var g=a("async");m.transform=function k(e,r){r=r||{};e=i.visit(e,s);if(r.includeRuntime===true||r.includeRuntime==="if used"&&s.wasChangeReported()){p(t.File.check(e)?e.program:e)}r.madeChanges=s.wasChangeReported();return e};function p(e){t.Program.assert(e);var r=n("..").runtime.path;var s=l.readFileSync(r,"utf8");var o=i.parse(s,{sourceFileName:r}).program.body;var a=e.body;a.unshift.apply(a,o)}var s=r.PathVisitor.fromMethodsObject({visitFunction:function(n){this.traverse(n);var r=n.value;if(!r.generator&&!r.async){return}this.reportChanged();r.generator=false;if(r.expression){r.expression=false;r.body=e.blockStatement([e.returnStatement(r.body)])}if(r.async){c.visit(n.get("body"))}var T=r.id||(r.id=n.scope.parent.declareTemporary("callee$"));var C=e.identifier(r.id.name+"$");var I=n.scope.declareTemporary("context$");var x=n.scope.declareTemporary("args$");var w=u(n,x);var a=b(n);if(w){a=a||e.variableDeclaration("var",[]);a.declarations.push(e.variableDeclarator(x,e.identifier("arguments")))}var y=new d(I);y.explode(n.get("body"));var l=[];if(a&&a.declarations.length>0){l.push(a)}var v=[y.getContextFunction(C),r.async?e.literal(null):T,e.thisExpression()];var E=y.getTryEntryList();if(E){v.push(E)}var k=e.callExpression(r.async?g:h,v);l.push(e.returnStatement(k));r.body=e.blockStatement(l);if(r.async){r.async=false;return}if(t.FunctionDeclaration.check(r)){var i=n.parent;while(i&&!(t.BlockStatement.check(i.value)||t.Program.check(i.value))){i=i.parent}if(!i){return}n.replace();r.type="FunctionExpression";var s=e.variableDeclaration("var",[e.variableDeclarator(r.id,e.callExpression(o,[r]))]);if(r.comments){s.comments=r.comments;r.comments=null}var m=i.get("body");var A=m.value.length;for(var p=0;p<A;++p){var S=m.get(p);if(!f(S)){S.insertBefore(s);return}}m.push(s)}else{t.FunctionExpression.assert(r);return e.callExpression(o,[r])}},visitForOfStatement:function(i){this.traverse(i);var r=i.value;var o=i.scope.declareTemporary("t$");var l=e.variableDeclarator(o,e.callExpression(v,[r.right]));var s=i.scope.declareTemporary("t$");var u=e.variableDeclarator(s,null);var n=r.left;var a;if(t.VariableDeclaration.check(n)){a=n.declarations[0].id;n.declarations.push(l,u)}else{a=n;n=e.variableDeclaration("var",[l,u])}t.Identifier.assert(a);var f=e.expressionStatement(e.assignmentExpression("=",a,e.memberExpression(s,e.identifier("value"),false)));if(t.BlockStatement.check(r.body)){r.body.body.unshift(f)}else{r.body=e.blockStatement([f,r.body])}return e.forStatement(n,e.unaryExpression("!",e.memberExpression(e.assignmentExpression("=",s,e.callExpression(e.memberExpression(o,e.identifier("next"),false),[])),e.identifier("done"),false)),null,r.body)}});function f(a){var e=a.value;t.Statement.assert(e);if(t.ExpressionStatement.check(e)&&t.Literal.check(e.expression)&&e.expression.value==="use strict"){return true}if(t.VariableDeclaration.check(e)){for(var n=0;n<e.declarations.length;++n){var i=e.declarations[n];if(t.CallExpression.check(i.init)&&r.astNodesAreEquivalent(i.init.callee,o)){return true}}}return false}function u(e,s){y.ok(e instanceof r.NodePath);var o=e.value;var n=false;var a=false;i.visit(e,{visitFunction:function(e){if(e.value===o){a=!e.scope.lookup("arguments");this.traverse(e)}else{return false}},visitIdentifier:function(e){if(e.value.name==="arguments"){var r=t.MemberExpression.check(e.parent.node)&&e.name==="property"&&!e.parent.node.computed;if(!r){e.replace(s);n=true;return false}}this.traverse(e)}});return n&&a}var c=r.PathVisitor.fromMethodsObject({visitFunction:function(e){return false},visitAwaitExpression:function(t){return e.yieldExpression(t.value.argument,false)}})},{"..":154,"./emit":148,"./hoist":149,"./util":152,assert:103,fs:102,recast:146}],154:[function(e,t,r){(function(m){var c=e("assert");var y=e("path");var v=e("fs");var d=e("through");var s=e("./lib/visit").transform;var h=e("./lib/util");var r=e("recast");var o=r.types;var E=/\bfunction\s*\*|\basync\b/;var p=/\b(let|const)\s+/;function n(i,t){var e=[];return d(r,n);function r(t){e.push(t)}function n(){this.queue(l(e.join(""),t).code);this.queue(null)}}t.exports=n;function i(){e("./runtime")}n.runtime=i;i.path=y.join(m,"runtime.js");function l(t,e){e=u(e);if(!E.test(t)){return{code:(e.includeRuntime===true?v.readFileSync(i.path,"utf-8")+"\n":"")+t}}var n=f(e);var p=r.parse(t,n);var l=new o.NodePath(p);var c=l.get("program");if(g(t,e)){a(c.node)}s(c,e);return r.print(l,n)}function u(t){t=h.defaults(t||{},{includeRuntime:false,supportBlockBinding:true});if(!t.esprima){t.esprima=e("esprima-fb")}c.ok(/harmony/.test(t.esprima.version),"Bad esprima version: "+t.esprima.version);return t}function f(t){var r={range:true};function e(e){if(e in t){r[e]=t[e]}}e("esprima");e("sourceFileName");e("sourceMapName");e("inputSourceMap");e("sourceRoot");return r}function g(t,r){var e=!!r.supportBlockBinding;if(e){if(!p.test(t)){e=false}}return e}function b(n,i){var e=f(u(i));var t=r.parse(n,e);a(t.program);return r.print(t,e).code}function a(t){o.namedTypes.Program.assert(t);var r=e("defs")(t,{ast:true,disallowUnknownReferences:false,disallowDuplicated:false,disallowVars:false,loopClosures:"iife"});if(r.errors){throw new Error(r.errors.join("\n"))}return t}n.varify=b;n.compile=l;n.transform=s}).call(this,"/node_modules/regenerator")},{"./lib/util":152,"./lib/visit":153,"./runtime":171,assert:103,defs:155,"esprima-fb":169,fs:102,path:111,recast:146,through:170}],155:[function(r,b,N){"use strict";var i=r("assert");var n=r("simple-is");var c=r("simple-fmt");var O=r("stringmap");var S=r("stringset");var w=r("alter");var a=r("ast-traverse");var C=r("breakable");var o=r("./scope");var t=r("./error");var e=t.getline;var s=r("./options");var I=r("./stats");var u=r("./jshint_globals/vars.js");function f(e){return n.someof(e,["const","let"])}function g(e){return n.someof(e,["var","const","let"])}function D(e){return e.type==="BlockStatement"&&n.noneof(e.$parent.type,["FunctionDeclaration","FunctionExpression"])}function E(e){return e.type==="ForStatement"&&e.init&&e.init.type==="VariableDeclaration"&&f(e.init.kind)}function x(e){return v(e)&&e.left.type==="VariableDeclaration"&&f(e.left.kind)}function v(e){return n.someof(e.type,["ForInStatement","ForOfStatement"])}function l(e){return n.someof(e.type,["FunctionDeclaration","FunctionExpression"])}function m(e){return n.someof(e.type,["ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement"])}function p(t){var e=t.$parent;return t.$refToScope||t.type==="Identifier"&&!(e.type==="VariableDeclarator"&&e.id===t)&&!(e.type==="MemberExpression"&&e.computed===false&&e.property===t)&&!(e.type==="Property"&&e.key===t)&&!(e.type==="LabeledStatement"&&e.label===t)&&!(e.type==="CatchClause"&&e.param===t)&&!(l(e)&&e.id===t)&&!(l(e)&&n.someof(t,e.params))&&true}function y(e){return p(e)&&(e.$parent.type==="AssignmentExpression"&&e.$parent.left===e||e.$parent.type==="UpdateExpression"&&e.$parent.argument===e)}function A(r,a){i(!r.$scope);r.$parent=a;r.$scope=r.$parent?r.$parent.$scope:null;if(r.type==="Program"){r.$scope=new o({kind:"hoist",node:r,parent:null})}else if(l(r)){r.$scope=new o({kind:"hoist",node:r,parent:r.$parent.$scope});if(r.id){i(r.id.type==="Identifier");if(r.type==="FunctionDeclaration"){r.$parent.$scope.add(r.id.name,"fun",r.id,null)}else if(r.type==="FunctionExpression"){r.$scope.add(r.id.name,"fun",r.id,null)}else{i(false)}}r.params.forEach(function(e){r.$scope.add(e.name,"param",e,null)})}else if(r.type==="VariableDeclaration"){i(g(r.kind));r.declarations.forEach(function(n){i(n.type==="VariableDeclarator");var a=n.id.name;if(s.disallowVars&&r.kind==="var"){t(e(n),"var {0} is not allowed (use let or const)",a)}r.$scope.add(a,r.kind,n.id,n.range[1])})}else if(E(r)||x(r)){r.$scope=new o({kind:"block",node:r,parent:r.$parent.$scope})}else if(D(r)){r.$scope=new o({kind:"block",node:r,parent:r.$parent.$scope})}else if(r.type==="CatchClause"){var n=r.param;r.$scope=new o({kind:"catch-block",node:r,parent:r.$parent.$scope});r.$scope.add(n.name,"caught",n,null);r.$scope.closestHoistScope().markPropagates(n.name)}}function T(n,i,a){function r(r){for(var t in r){var n=r[t];var i=n?"var":"const";if(e.hasOwn(t)){e.remove(t)}e.add(t,i,{loc:{start:{line:-1}}},-1)}}var e=new o({kind:"hoist",node:{},parent:null});var s={undefined:false,Infinity:false,console:false};r(s);r(u.reservedVars);r(u.ecmaIdentifiers);if(i){i.forEach(function(e){if(!u[e]){t(-1,'environment "{0}" not found',e)}else{r(u[e])}})}if(a){r(a)}n.parent=e;e.children.push(n);return e}function P(l,u,r){var o=n.own(r,"analyze")?r.analyze:true;function f(r){if(!p(r)){return}u.add(r.name);var a=r.$scope.lookup(r.name);if(o&&!a&&s.disallowUnknownReferences){t(e(r),"reference to unknown global variable {0}",r.name)}if(o&&a&&n.someof(a.getKind(r.name),["const","let"])){var l=a.getFromPos(r.name);var f=r.range[0];i(n.finitenumber(l));i(n.finitenumber(f));if(f<l){if(!r.$scope.hasFunctionScopeBetween(a)){t(e(r),"{0} is referenced before its declaration",r.name)}}}r.$refToScope=a}a(l,{pre:f})}function L(r,s,n,t){function o(e){i(n.has(e));for(var t=0;;t++){var r=e+"$"+String(t);if(!n.has(r)){return r}}}function l(r){if(r.type==="VariableDeclaration"&&f(r.kind)){var a=r.$scope.closestHoistScope();var l=r.$scope;t.push({start:r.range[0],end:r.range[0]+r.kind.length,str:"var"});r.declarations.forEach(function(u){i(u.type==="VariableDeclarator");var f=u.id.name;s.declarator(r.kind);var p=l!==a&&(a.hasOwn(f)||a.doesPropagate(f));var c=p?o(f):f;l.remove(f);a.add(c,"var",u.id,u.range[1]);l.moves=l.moves||O();l.moves.set(f,{name:c,scope:a});n.add(c);if(c!==f){s.rename(f,c,e(u));u.id.originalName=f;u.id.name=c;t.push({start:u.id.range[0],end:u.id.range[1],str:c})}});r.kind="var"}}function u(e){if(!e.$refToScope){return}var r=e.$refToScope.moves&&e.$refToScope.moves.get(e.name);if(!r){return}e.$refToScope=r.scope;if(e.name!==r.name){e.originalName=e.name;e.name=r.name;if(e.alterop){var n=null;for(var a=0;a<t.length;a++){var s=t[a];if(s.node===e){n=s;break}}i(n);n.str=r.name}else{t.push({start:e.range[0],end:e.range[1],str:r.name})}}}a(r,{pre:l});a(r,{pre:u});r.$scope.traverse({pre:function(e){delete e.moves}})}function _(r){a(r,{pre:o});function n(n,r){return C(function(i){a(n,{pre:function(n){if(l(n)){return false}var s=true;var a="loop-variable {0} is captured by a loop-closure that can't be transformed due to use of {1} at line {2}";if(n.type==="BreakStatement"){t(e(r),a,r.name,"break",e(n))}else if(n.type==="ContinueStatement"){t(e(r),a,r.name,"continue",e(n))}else if(n.type==="ReturnStatement"){t(e(r),a,r.name,"return",e(n))}else if(n.type==="YieldExpression"){t(e(r),a,r.name,"yield",e(n))}else if(n.type==="Identifier"&&n.name==="arguments"){t(e(r),a,r.name,"arguments",e(n))}else if(n.type==="VariableDeclaration"&&n.kind==="var"){t(e(r),a,r.name,"var",e(n))}else{s=false}if(s){i(true)}}});return false})}function o(r){var a=null;if(p(r)&&r.$refToScope&&f(r.$refToScope.getKind(r.name))){for(var o=r.$refToScope.node;;){if(l(o)){return}else if(m(o)){a=o;break}o=o.$parent;if(!o){return}}i(m(a));var c=r.$refToScope;var h=s.loopClosures==="iife";for(var u=r.$scope;u;u=u.parent){if(u===c){return}else if(l(u.node)){if(!h){var y='loop-variable {0} is captured by a loop-closure. Tried "loopClosures": "iife" in defs-config.json?';return t(e(r),y,r.name)}if(a.type==="ForStatement"&&c.node===a){var d=c.getNode(r.name);return t(e(d),"Not yet specced ES6 feature. {0} is declared in for-loop header and then captured in loop closure",d.name)}if(n(a.body,r)){return}a.$iify=true}}}}}function j(t,r,n){function e(e,i,t){var n={start:e,end:e,str:i};if(t){n.node=t}r.push(n)}a(t,{pre:function(t){if(!t.$iify){return}var s=t.body.type==="BlockStatement";var d=s?t.body.range[0]+1:t.body.range[0];var i=s?t.body.range[1]-1:t.body.range[1];var r=v(t)&&t.left.declarations[0].id.name;var o=c("(function({0}){",r?r:"");var l=c("}).call(this{0});",r?", "+r:"");var g=n.parse(o+l);var a=g.body[0];var p=a.expression.callee.object.body;if(s){var f=t.body;var m=f.body;f.body=[a];p.body=m}else{var h=t.body;t.body=a;p.body[0]=h}e(d,o);if(r){e(i,"}).call(this, ");var y=a.expression.arguments;var u=y[1];u.alterop=true;e(i,r,u);e(i,");")}else{e(i,l)}}})}function M(r){a(r,{pre:function(r){if(y(r)){var n=r.$scope.lookup(r.name);if(n&&n.getKind(r.name)==="const"){t(e(r),"can't assign to const variable {0}",r.name)}}}})}function R(e){a(e,{pre:function(e){if(y(e)){var t=e.$scope.lookup(e.name);if(t){t.markWrite(e.name)}}}});e.$scope.detectUnmodifiedLets()}function h(e,r){a(e,{pre:A});var n=T(e.$scope,s.environments,s.globals);var t=S();n.traverse({pre:function(e){t.addMany(e.decls.keys())}});P(e,t,r);return t}function d(e){a(e,{pre:function(e){for(var t in e){if(t[0]==="$"){delete e[t]}}}})}function k(r,f){for(var p in f){s[p]=f[p]}var l;if(n.object(r)){if(!s.ast){return{errors:["Can't produce string output when input is an AST. "+"Did you forget to set options.ast = true?"]}}l=r}else if(n.string(r)){try{l=s.parse(r,{loc:true,range:true})}catch(a){return{errors:[c("line {0} column {1}: Error during input file parsing\n{2}\n{3}",a.lineNumber,a.column,r.split("\n")[a.lineNumber-1],c.repeat(" ",a.column-1)+"^")]}}}else{return{errors:["Input was neither an AST object nor a string."]}}var e=l;t.reset();var m=h(e,{});_(e);M(e);var o=[];j(e,o,s);if(t.errors.length>=1){return{errors:t.errors}}if(o.length>0){d(e);m=h(e,{analyze:false})}i(t.errors.length===0);var u=new I;L(e,u,m,o);if(s.ast){d(e);return{stats:u,ast:e}}else{var y=w(r,o);return{stats:u,src:y}}}b.exports=k},{"./error":156,"./jshint_globals/vars.js":157,"./options":158,"./scope":159,"./stats":160,alter:161,assert:103,"ast-traverse":163,breakable:164,"simple-fmt":165,"simple-is":166,stringmap:167,stringset:168}],156:[function(r,n,a){"use strict";var t=r("simple-fmt");var i=r("assert");function e(r,a){i(arguments.length>=2);var n=arguments.length===2?String(a):t.apply(t,Array.prototype.slice.call(arguments,1));e.errors.push(r===-1?n:t("line {0}: {1}",r,n))}e.reset=function(){e.errors=[]};e.getline=function(e){if(e&&e.loc&&e.loc.start){return e.loc.start.line}return-1};e.reset();n.exports=e},{assert:103,"simple-fmt":165}],157:[function(t,r,e){"use strict";e.reservedVars={arguments:false,NaN:false};e.ecmaIdentifiers={Array:false,Boolean:false,Date:false,decodeURI:false,decodeURIComponent:false,encodeURI:false,encodeURIComponent:false,Error:false,eval:false,EvalError:false,Function:false,hasOwnProperty:false,isFinite:false,isNaN:false,JSON:false,Math:false,Map:false,Number:false,Object:false,parseInt:false,parseFloat:false,RangeError:false,ReferenceError:false,RegExp:false,Set:false,String:false,SyntaxError:false,TypeError:false,URIError:false,WeakMap:false};e.browser={ArrayBuffer:false,ArrayBufferView:false,Audio:false,Blob:false,addEventListener:false,applicationCache:false,atob:false,blur:false,btoa:false,clearInterval:false,clearTimeout:false,close:false,closed:false,DataView:false,DOMParser:false,defaultStatus:false,document:false,Element:false,event:false,FileReader:false,Float32Array:false,Float64Array:false,FormData:false,focus:false,frames:false,getComputedStyle:false,HTMLElement:false,HTMLAnchorElement:false,HTMLBaseElement:false,HTMLBlockquoteElement:false,HTMLBodyElement:false,HTMLBRElement:false,HTMLButtonElement:false,HTMLCanvasElement:false,HTMLDirectoryElement:false,HTMLDivElement:false,HTMLDListElement:false,HTMLFieldSetElement:false,HTMLFontElement:false,HTMLFormElement:false,HTMLFrameElement:false,HTMLFrameSetElement:false,HTMLHeadElement:false,HTMLHeadingElement:false,HTMLHRElement:false,HTMLHtmlElement:false,HTMLIFrameElement:false,HTMLImageElement:false,HTMLInputElement:false,HTMLIsIndexElement:false,HTMLLabelElement:false,HTMLLayerElement:false,HTMLLegendElement:false,HTMLLIElement:false,HTMLLinkElement:false,HTMLMapElement:false,HTMLMenuElement:false,HTMLMetaElement:false,HTMLModElement:false,HTMLObjectElement:false,HTMLOListElement:false,HTMLOptGroupElement:false,HTMLOptionElement:false,HTMLParagraphElement:false,HTMLParamElement:false,HTMLPreElement:false,HTMLQuoteElement:false,HTMLScriptElement:false,HTMLSelectElement:false,HTMLStyleElement:false,HTMLTableCaptionElement:false,HTMLTableCellElement:false,HTMLTableColElement:false,HTMLTableElement:false,HTMLTableRowElement:false,HTMLTableSectionElement:false,HTMLTextAreaElement:false,HTMLTitleElement:false,HTMLUListElement:false,HTMLVideoElement:false,history:false,Int16Array:false,Int32Array:false,Int8Array:false,Image:false,length:false,localStorage:false,location:false,MessageChannel:false,MessageEvent:false,MessagePort:false,moveBy:false,moveTo:false,MutationObserver:false,name:false,Node:false,NodeFilter:false,navigator:false,onbeforeunload:true,onblur:true,onerror:true,onfocus:true,onload:true,onresize:true,onunload:true,open:false,openDatabase:false,opener:false,Option:false,parent:false,print:false,removeEventListener:false,resizeBy:false,resizeTo:false,screen:false,scroll:false,scrollBy:false,scrollTo:false,sessionStorage:false,setInterval:false,setTimeout:false,SharedWorker:false,status:false,top:false,Uint16Array:false,Uint32Array:false,Uint8Array:false,Uint8ClampedArray:false,WebSocket:false,window:false,Worker:false,XMLHttpRequest:false,XMLSerializer:false,XPathEvaluator:false,XPathException:false,XPathExpression:false,XPathNamespace:false,XPathNSResolver:false,XPathResult:false};e.devel={alert:false,confirm:false,console:false,Debug:false,opera:false,prompt:false};e.worker={importScripts:true,postMessage:true,self:true};e.nonstandard={escape:false,unescape:false};e.couch={require:false,respond:false,getRow:false,emit:false,send:false,start:false,sum:false,log:false,exports:false,module:false,provides:false};e.node={__filename:false,__dirname:false,Buffer:false,DataView:false,console:false,exports:true,GLOBAL:false,global:false,module:false,process:false,require:false,setTimeout:false,clearTimeout:false,setInterval:false,clearInterval:false};e.phantom={phantom:true,require:true,WebPage:true};e.rhino={defineClass:false,deserialize:false,gc:false,help:false,importPackage:false,java:false,load:false,loadClass:false,print:false,quit:false,readFile:false,readUrl:false,runCommand:false,seal:false,serialize:false,spawn:false,sync:false,toint32:false,version:false};e.wsh={ActiveXObject:true,Enumerator:true,GetObject:true,ScriptEngine:true,ScriptEngineBuildVersion:true,ScriptEngineMajorVersion:true,ScriptEngineMinorVersion:true,VBArray:true,WSH:true,WScript:true,XDomainRequest:true};e.dojo={dojo:false,dijit:false,dojox:false,define:false,require:false};e.jquery={$:false,jQuery:false};e.mootools={$:false,$$:false,Asset:false,Browser:false,Chain:false,Class:false,Color:false,Cookie:false,Core:false,Document:false,DomReady:false,DOMEvent:false,DOMReady:false,Drag:false,Element:false,Elements:false,Event:false,Events:false,Fx:false,Group:false,Hash:false,HtmlTable:false,Iframe:false,IframeShim:false,InputValidator:false,instanceOf:false,Keyboard:false,Locale:false,Mask:false,MooTools:false,Native:false,Options:false,OverText:false,Request:false,Scroller:false,Slick:false,Slider:false,Sortables:false,Spinner:false,Swiff:false,Tips:false,Type:false,typeOf:false,URI:false,Window:false};e.prototypejs={$:false,$$:false,$A:false,$F:false,$H:false,$R:false,$break:false,$continue:false,$w:false,Abstract:false,Ajax:false,Class:false,Enumerable:false,Element:false,Event:false,Field:false,Form:false,Hash:false,Insertion:false,ObjectRange:false,PeriodicalExecuter:false,Position:false,Prototype:false,Selector:false,Template:false,Toggle:false,Try:false,Autocompleter:false,Builder:false,Control:false,Draggable:false,Draggables:false,Droppables:false,Effect:false,Sortable:false,SortableObserver:false,Sound:false,Scriptaculous:false};e.yui={YUI:false,Y:false,YUI_config:false}},{}],158:[function(e,t,r){t.exports={disallowVars:false,disallowDuplicated:true,disallowUnknownReferences:true,parse:e("esprima-fb").parse}},{"esprima-fb":169}],159:[function(n,u,c){"use strict";var r=n("assert");var l=n("stringmap");var o=n("stringset");var t=n("simple-is");var a=n("simple-fmt");var i=n("./error");var s=i.getline;var f=n("./options");function e(e){r(t.someof(e.kind,["hoist","block","catch-block"]));r(t.object(e.node));r(e.parent===null||t.object(e.parent));this.kind=e.kind;this.node=e.node;this.parent=e.parent;this.children=[];this.decls=l();this.written=o();this.propagates=this.kind==="hoist"?o():null;if(this.parent){this.parent.children.push(this)
}}e.prototype.print=function(e){e=e||0;var t=this;var r=this.decls.keys().map(function(e){return a("{0} [{1}]",e,t.decls.get(e).kind)}).join(", ");var n=this.propagates?this.propagates.items().join(", "):"";console.log(a("{0}{1}: {2}. propagates: {3}",a.repeat(" ",e),this.node.type,r,n));this.children.forEach(function(t){t.print(e+2)})};e.prototype.add=function(n,a,o,u){r(t.someof(a,["fun","param","var","caught","const","let"]));function l(e){return t.someof(e,["const","let"])}var e=this;if(t.someof(a,["fun","param","var"])){while(e.kind!=="hoist"){if(e.decls.has(n)&&l(e.decls.get(n).kind)){return i(s(o),"{0} is already declared",n)}e=e.parent}}if(e.decls.has(n)&&(f.disallowDuplicated||l(e.decls.get(n).kind)||l(a))){return i(s(o),"{0} is already declared",n)}var c={kind:a,node:o};if(u){r(t.someof(a,["var","const","let"]));c.from=u}e.decls.set(n,c)};e.prototype.getKind=function(e){r(t.string(e));var n=this.decls.get(e);return n?n.kind:null};e.prototype.getNode=function(e){r(t.string(e));var n=this.decls.get(e);return n?n.node:null};e.prototype.getFromPos=function(e){r(t.string(e));var n=this.decls.get(e);return n?n.from:null};e.prototype.hasOwn=function(e){return this.decls.has(e)};e.prototype.remove=function(e){return this.decls.remove(e)};e.prototype.doesPropagate=function(e){return this.propagates.has(e)};e.prototype.markPropagates=function(e){this.propagates.add(e)};e.prototype.closestHoistScope=function(){var e=this;while(e.kind!=="hoist"){e=e.parent}return e};e.prototype.hasFunctionScopeBetween=function(r){function n(e){return t.someof(e.type,["FunctionDeclaration","FunctionExpression"])}for(var e=this;e;e=e.parent){if(e===r){return false}if(n(e.node)){return true}}throw new Error("wasn't inner scope of outer")};e.prototype.lookup=function(t){for(var e=this;e;e=e.parent){if(e.decls.has(t)){return e}else if(e.kind==="hoist"){e.propagates.add(t)}}return null};e.prototype.markWrite=function(e){r(t.string(e));this.written.add(e)};e.prototype.detectUnmodifiedLets=function(){var t=this;function e(r){if(r!==t){r.decls.keys().forEach(function(e){if(r.getKind(e)==="let"&&!r.written.has(e)){return i(s(r.getNode(e)),"{0} is declared as let but never modified so could be const",e)}})}r.children.forEach(function(t){e(t)})}e(this)};e.prototype.traverse=function(e){e=e||{};var t=e.pre;var r=e.post;function n(e){if(t){t(e)}e.children.forEach(function(e){n(e)});if(r){r(e)}}n(this)};u.exports=e},{"./error":156,"./options":158,assert:103,"simple-fmt":165,"simple-is":166,stringmap:167,stringset:168}],160:[function(t,n,s){var r=t("simple-fmt");var i=t("simple-is");var a=t("assert");function e(){this.lets=0;this.consts=0;this.renames=[]}e.prototype.declarator=function(e){a(i.someof(e,["const","let"]));if(e==="const"){this.consts++}else{this.lets++}};e.prototype.rename=function(e,t,r){this.renames.push({oldName:e,newName:t,line:r})};e.prototype.toString=function(){var t=this.renames.map(function(e){return e}).sort(function(e,t){return e.line-t.line});var n=t.map(function(e){return r("\nline {0}: {1} => {2}",e.line,e.oldName,e.newName)}).join("");var e=this.consts+this.lets;var i=e===0?"can't calculate const coverage (0 consts, 0 lets)":r("{0}% const coverage ({1} consts, {2} lets)",Math.floor(100*this.consts/e),this.consts,this.lets);return i+n+"\n"};n.exports=e},{assert:103,"simple-fmt":165,"simple-is":166}],161:[function(r,t,a){var e=r("assert");var n=r("stable");function i(i,o){"use strict";var u=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};e(typeof i==="string");e(u(o));var l=n(o,function(e,t){return e.start-t.start});var a=[];var r=0;for(var s=0;s<l.length;s++){var t=l[s];e(r<=t.start);e(t.start<=t.end);a.push(i.slice(r,t.start));a.push(t.str);r=t.end}if(r<i.length){a.push(i.slice(r))}return a.join("")}if(typeof t!=="undefined"&&typeof t.exports!=="undefined"){t.exports=i}},{assert:103,stable:162}],162:[function(t,e,r){(function(){var t=function(e,t){return r(e.slice(),t)};t.inplace=function(e,i){var t=r(e,i);if(t!==e){n(t,null,e.length,e)}return e};function r(e,t){if(typeof t!=="function"){t=function(e,t){return String(e).localeCompare(t)}}var r=e.length;if(r<=1){return e}var i=new Array(r);for(var a=1;a<r;a*=2){n(e,t,a,i);var s=e;e=i;i=s}return e}var n=function(e,f,u,l){var i=e.length;var o=0;var c=u*2;var a,t,s;var r,n;for(a=0;a<i;a+=c){t=a+u;s=t+u;if(t>i)t=i;if(s>i)s=i;r=a;n=t;while(true){if(r<t&&n<s){if(f(e[r],e[n])<=0){l[o++]=e[r++]}else{l[o++]=e[n++]}}else if(r<t){l[o++]=e[r++]}else if(n<s){l[o++]=e[n++]}else{break}}}};if(typeof e!=="undefined"){e.exports=t}else{window.stable=t}})()},{}],163:[function(r,e,n){function t(a,e){"use strict";e=e||{};var r=e.pre;var n=e.post;var i=e.skipProperty;function t(e,l,a,u){if(!e||typeof e.type!=="string"){return}var f=undefined;if(r){f=r(e,l,a,u)}if(f!==false){for(var a in e){if(i?i(a,e):a[0]==="$"){continue}var s=e[a];if(Array.isArray(s)){for(var o=0;o<s.length;o++){t(s[o],e,a,o)}}else{t(s,e,a)}}}if(n){n(e,l,a,u)}}t(a,null)}if(typeof e!=="undefined"&&typeof e.exports!=="undefined"){e.exports=t}},{}],164:[function(r,e,n){var t=function(){"use strict";function e(e,t){this.val=e;this.brk=t}function t(){return function t(r){throw new e(r,t)}}function r(i){var n=t();try{return i(n)}catch(r){if(r instanceof e&&r.brk===n){return r.val}throw r}}return r}();if(typeof e!=="undefined"&&typeof e.exports!=="undefined"){e.exports=t}},{}],165:[function(r,e,n){var t=function(){"use strict";function e(t,r){var e=Array.prototype.slice.call(arguments,1);return t.replace(/\{(\d+)\}/g,function(r,t){return t in e?e[t]:r})}function t(t,e){return t.replace(/\{([_$a-zA-Z0-9][_$a-zA-Z0-9]*)\}/g,function(r,t){return t in e?e[t]:r})}function r(e,t){return new Array(t+1).join(e)}e.fmt=e;e.obj=t;e.repeat=r;return e}();if(typeof e!=="undefined"&&typeof e.exports!=="undefined"){e.exports=t}},{}],166:[function(r,e,n){var t=function(){"use strict";var e=Object.prototype.hasOwnProperty;var t=Object.prototype.toString;var r=void 0;return{nan:function(e){return e!==e},"boolean":function(e){return typeof e==="boolean"},number:function(e){return typeof e==="number"},string:function(e){return typeof e==="string"},fn:function(e){return typeof e==="function"},object:function(e){return e!==null&&typeof e==="object"},primitive:function(e){var t=typeof e;return e===null||e===r||t==="boolean"||t==="number"||t==="string"},array:Array.isArray||function(e){return t.call(e)==="[object Array]"},finitenumber:function(e){return typeof e==="number"&&isFinite(e)},someof:function(e,t){return t.indexOf(e)>=0},noneof:function(e,t){return t.indexOf(e)===-1},own:function(t,r){return e.call(t,r)}}}();if(typeof e!=="undefined"&&typeof e.exports!=="undefined"){e.exports=t}},{}],167:[function(r,e,n){var t=function(){"use strict";var t=Object.prototype.hasOwnProperty;var r=function(){function n(e){for(var r in e){if(t.call(e,r)){return true}}return false}function i(e){return t.call(e,"__count__")||t.call(e,"__parent__")}var e=false;if(typeof Object.create==="function"){if(!n(Object.create(null))){e=true}}if(e===false){if(n({})){throw new Error("StringMap environment error 0, please file a bug at https://github.com/olov/stringmap/issues")}}var r=e?Object.create(null):{};var a=false;if(i(r)){r.__proto__=null;if(n(r)||i(r)){throw new Error("StringMap environment error 1, please file a bug at https://github.com/olov/stringmap/issues")}a=true}return function(){var t=e?Object.create(null):{};if(a){t.__proto__=null}return t}}();function e(t){if(!(this instanceof e)){return new e(t)}this.obj=r();this.hasProto=false;this.proto=undefined;if(t){this.setMany(t)}}e.prototype.has=function(e){if(typeof e!=="string"){throw new Error("StringMap expected string key")}return e==="__proto__"?this.hasProto:t.call(this.obj,e)};e.prototype.get=function(e){if(typeof e!=="string"){throw new Error("StringMap expected string key")}return e==="__proto__"?this.proto:t.call(this.obj,e)?this.obj[e]:undefined};e.prototype.set=function(e,t){if(typeof e!=="string"){throw new Error("StringMap expected string key")}if(e==="__proto__"){this.hasProto=true;this.proto=t}else{this.obj[e]=t}};e.prototype.remove=function(e){if(typeof e!=="string"){throw new Error("StringMap expected string key")}var t=this.has(e);if(e==="__proto__"){this.hasProto=false;this.proto=undefined}else{delete this.obj[e]}return t};e.prototype["delete"]=e.prototype.remove;e.prototype.isEmpty=function(){for(var e in this.obj){if(t.call(this.obj,e)){return false}}return!this.hasProto};e.prototype.size=function(){var e=0;for(var r in this.obj){if(t.call(this.obj,r)){++e}}return this.hasProto?e+1:e};e.prototype.keys=function(){var e=[];for(var r in this.obj){if(t.call(this.obj,r)){e.push(r)}}if(this.hasProto){e.push("__proto__")}return e};e.prototype.values=function(){var e=[];for(var r in this.obj){if(t.call(this.obj,r)){e.push(this.obj[r])}}if(this.hasProto){e.push(this.proto)}return e};e.prototype.items=function(){var e=[];for(var r in this.obj){if(t.call(this.obj,r)){e.push([r,this.obj[r]])}}if(this.hasProto){e.push(["__proto__",this.proto])}return e};e.prototype.setMany=function(e){if(e===null||typeof e!=="object"&&typeof e!=="function"){throw new Error("StringMap expected Object")}for(var r in e){if(t.call(e,r)){this.set(r,e[r])}}return this};e.prototype.merge=function(t){var r=t.keys();for(var e=0;e<r.length;e++){var n=r[e];this.set(n,t.get(n))}return this};e.prototype.map=function(n){var e=this.keys();for(var t=0;t<e.length;t++){var r=e[t];e[t]=n(this.get(r),r)}return e};e.prototype.forEach=function(n){var t=this.keys();for(var e=0;e<t.length;e++){var r=t[e];n(this.get(r),r)}};e.prototype.clone=function(){var t=e();return t.merge(this)};e.prototype.toString=function(){var e=this;return"{"+this.keys().map(function(t){return JSON.stringify(t)+":"+JSON.stringify(e.get(t))}).join(",")+"}"};return e}();if(typeof e!=="undefined"&&typeof e.exports!=="undefined"){e.exports=t}},{}],168:[function(r,e,n){var t=function(){"use strict";var t=Object.prototype.hasOwnProperty;var r=function(){function n(e){for(var r in e){if(t.call(e,r)){return true}}return false}function i(e){return t.call(e,"__count__")||t.call(e,"__parent__")}var e=false;if(typeof Object.create==="function"){if(!n(Object.create(null))){e=true}}if(e===false){if(n({})){throw new Error("StringSet environment error 0, please file a bug at https://github.com/olov/stringset/issues")}}var r=e?Object.create(null):{};var a=false;if(i(r)){r.__proto__=null;if(n(r)||i(r)){throw new Error("StringSet environment error 1, please file a bug at https://github.com/olov/stringset/issues")}a=true}return function(){var t=e?Object.create(null):{};if(a){t.__proto__=null}return t}}();function e(t){if(!(this instanceof e)){return new e(t)}this.obj=r();this.hasProto=false;if(t){this.addMany(t)}}e.prototype.has=function(e){if(typeof e!=="string"){throw new Error("StringSet expected string item")}return e==="__proto__"?this.hasProto:t.call(this.obj,e)};e.prototype.add=function(e){if(typeof e!=="string"){throw new Error("StringSet expected string item")}if(e==="__proto__"){this.hasProto=true}else{this.obj[e]=true}};e.prototype.remove=function(e){if(typeof e!=="string"){throw new Error("StringSet expected string item")}var t=this.has(e);if(e==="__proto__"){this.hasProto=false}else{delete this.obj[e]}return t};e.prototype["delete"]=e.prototype.remove;e.prototype.isEmpty=function(){for(var e in this.obj){if(t.call(this.obj,e)){return false}}return!this.hasProto};e.prototype.size=function(){var e=0;for(var r in this.obj){if(t.call(this.obj,r)){++e}}return this.hasProto?e+1:e};e.prototype.items=function(){var e=[];for(var r in this.obj){if(t.call(this.obj,r)){e.push(r)}}if(this.hasProto){e.push("__proto__")}return e};e.prototype.addMany=function(e){if(!Array.isArray(e)){throw new Error("StringSet expected array")}for(var t=0;t<e.length;t++){this.add(e[t])}return this};e.prototype.merge=function(e){this.addMany(e.items());return this};e.prototype.clone=function(){var t=e();return t.merge(this)};e.prototype.toString=function(){return"{"+this.items().map(JSON.stringify).join(",")+"}"};return e}();if(typeof e!=="undefined"&&typeof e.exports!=="undefined"){e.exports=t}},{}],169:[function(e,t,r){t.exports=e(147)},{"/Users/sebastian/Projects/6to5/6to5/node_modules/recast/node_modules/esprima-fb/esprima.js":147}],170:[function(e,t,r){(function(i){var a=e("stream");r=t.exports=n;n.through=n;function n(r,n,o){r=r||function(e){this.queue(e)};n=n||function(){this.queue(null)};var s=false,l=false,t=[],u=false;var e=new a;e.readable=e.writable=true;e.paused=false;e.autoDestroy=!(o&&o.autoDestroy===false);e.write=function(t){r.call(this,t);return!e.paused};function f(){while(t.length&&!e.paused){var r=t.shift();if(null===r)return e.emit("end");else e.emit("data",r)}}e.queue=e.push=function(r){if(u)return e;if(r==null)u=true;t.push(r);f();return e};e.on("end",function(){e.readable=false;if(!e.writable&&e.autoDestroy)i.nextTick(function(){e.destroy()})});function c(){e.writable=false;n.call(e);if(!e.readable&&e.autoDestroy)e.destroy()}e.end=function(t){if(s)return;s=true;if(arguments.length)e.write(t);c();return e};e.destroy=function(){if(l)return;l=true;s=true;t.length=0;e.writable=e.readable=false;e.emit("close");return e};e.pause=function(){if(e.paused)return;e.paused=true;return e};e.resume=function(){if(e.paused){e.paused=false;e.emit("resume")}f();if(!e.paused)e.emit("drain");return e};return e}}).call(this,e("_process"))},{_process:112,stream:124}],171:[function(t,r,e){!function(){var n=Object.prototype.hasOwnProperty;var r;var d=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";if(typeof regeneratorRuntime==="object"){return}var t=regeneratorRuntime=typeof e==="undefined"?{}:e;function v(e,t,r,n){return new p(e,t,r||null,n||[])}t.wrap=v;var u="suspendedStart";var f="suspendedYield";var m="executing";var l="completed";var i={};function s(){}function a(){}var o=a.prototype=p.prototype;s.prototype=o.constructor=a;a.constructor=s;s.displayName="GeneratorFunction";t.isGeneratorFunction=function(t){var e=typeof t==="function"&&t.constructor;return e?e===s||(e.displayName||e.name)==="GeneratorFunction":false};t.mark=function(e){e.__proto__=a;e.prototype=Object.create(o);return e};t.async=function(e,t,r,n){return new Promise(function(o,l){var i=v(e,t,r,n);var a=s.bind(i.next);var u=s.bind(i["throw"]);function s(r){try{var e=this(r);var t=e.value}catch(n){return l(n)}if(e.done){o(t)}else{Promise.resolve(t).then(a,u)}}a()})};function p(o,s,p,d){var n=s?Object.create(s.prototype):this;var e=new c(d);var t=u;function a(a,n){if(t===m){throw new Error("Generator is already running")}if(t===l){return g()}while(true){var s=e.delegate;if(s){try{var c=s.iterator[a](n);a="next";n=r}catch(y){e.delegate=null;a="throw";n=y;continue}if(c.done){e[s.resultName]=c.value;e.next=s.nextLoc}else{t=f;return c}e.delegate=null}if(a==="next"){if(t===u&&typeof n!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(n)+" to newborn generator")}if(t===f){e.sent=n}else{delete e.sent}}else if(a==="throw"){if(t===u){t=l;throw n}if(e.dispatchException(n)){a="next";n=r}}else if(a==="return"){e.abrupt("return",n)}t=m;try{var d=o.call(p,e);t=e.done?l:f;var c={value:d,done:e.done};if(d===i){if(e.delegate&&a==="next"){n=r}}else{return c}}catch(h){t=l;if(a==="next"){e.dispatchException(h)}else{n=h}}}}n.next=a.bind(n,"next");n["throw"]=a.bind(n,"throw");n["return"]=a.bind(n,"return");return n}o[d]=function(){return this};o.toString=function(){return"[object Generator]"};function b(e){var t={tryLoc:e[0]};if(1 in e){t.catchLoc=e[1]}if(2 in e){t.finallyLoc=e[2]}this.tryEntries.push(t)}function y(t,r){var e=t.completion||{};e.type=r===0?"normal":"return";delete e.arg;t.completion=e}function c(e){this.tryEntries=[{tryLoc:"root"}];e.forEach(b,this);this.reset()}t.keys=function(t){var e=[];for(var r in t){e.push(r)}e.reverse();return function n(){while(e.length){var r=e.pop();if(r in t){n.value=r;n.done=false;return n}}n.done=true;return n}};function h(e){if(e){var a=e[d];if(a){return a.call(e)}if(typeof e.next==="function"){return e}if(!isNaN(e.length)){var i=-1;function t(){while(++i<e.length){if(n.call(e,i)){t.value=e[i];t.done=false;return t}}t.value=r;t.done=true;return t}return t.next=t}}return{next:g}}t.values=h;function g(){return{value:r,done:true}}c.prototype={constructor:c,reset:function(){this.prev=0;this.next=0;this.sent=r;this.done=false;this.delegate=null;this.tryEntries.forEach(y);for(var e=0,t;n.call(this,t="t"+e)||e<20;++e){this[t]=null}},stop:function(){this.done=true;var t=this.tryEntries[0];var e=t.completion;if(e.type==="throw"){throw e.arg}return this.rval},dispatchException:function(i){if(this.done){throw i}var l=this;function t(e,t){a.type="throw";a.arg=i;l.next=e;return!!t}for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];var a=e.completion;if(e.tryLoc==="root"){return t("end")}if(e.tryLoc<=this.prev){var s=n.call(e,"catchLoc");var o=n.call(e,"finallyLoc");if(s&&o){if(this.prev<e.catchLoc){return t(e.catchLoc,true)}else if(this.prev<e.finallyLoc){return t(e.finallyLoc)}}else if(s){if(this.prev<e.catchLoc){return t(e.catchLoc,true)}}else if(o){if(this.prev<e.finallyLoc){return t(e.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(r){for(var t=this.tryEntries.length-1;t>=0;--t){var e=this.tryEntries[t];if(e.tryLoc<=this.prev&&n.call(e,"finallyLoc")&&(e.finallyLoc===r||this.prev<e.finallyLoc)){return e}}},abrupt:function(r,n){var e=this._findFinallyEntry();var t=e?e.completion:{};t.type=r;t.arg=n;if(e){this.next=e.finallyLoc}else{this.complete(t)}return i},complete:function(e){if(e.type==="throw"){throw e.arg}if(e.type==="break"||e.type==="continue"){this.next=e.arg}else if(e.type==="return"){this.rval=e.arg;this.next="end"}return i},finish:function(e){var t=this._findFinallyEntry(e);return this.complete(t.completion)},"catch":function(n){for(var e=this.tryEntries.length-1;e>=0;--e){var t=this.tryEntries[e];if(t.tryLoc===n){var r=t.completion;if(r.type==="throw"){var i=r.arg;y(t,e)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){this.delegate={iterator:h(e),resultName:t,nextLoc:r};return i}}}()},{}],172:[function(r,n,t){var e=r("regenerate");t.REGULAR={d:e().addRange(48,57),D:e().addRange(0,47).addRange(58,65535),s:e(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:e().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,65535),w:e(95).addRange(48,57).addRange(65,90).addRange(97,122),W:e(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,65535)};t.UNICODE={d:e().addRange(48,57),D:e().addRange(0,47).addRange(58,1114111),s:e(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:e().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:e(95).addRange(48,57).addRange(65,90).addRange(97,122),W:e(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)};t.UNICODE_IGNORE_CASE={d:e().addRange(48,57),D:e().addRange(0,47).addRange(58,1114111),s:e(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:e().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:e(95,383,8490).addRange(48,57).addRange(65,90).addRange(97,122),W:e(75,83,96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)}},{regenerate:174}],173:[function(t,e,r){e.exports={75:8490,83:383,107:8490,115:383,181:924,197:8491,383:83,452:453,453:452,455:456,456:455,458:459,459:458,497:498,498:497,837:8126,914:976,917:1013,920:1012,921:8126,922:1008,924:181,928:982,929:1009,931:962,934:981,937:8486,962:931,976:914,977:1012,981:934,982:928,1008:922,1009:929,1012:[920,977],1013:917,7776:7835,7835:7776,8126:[837,921],8486:937,8490:75,8491:197,66560:66600,66561:66601,66562:66602,66563:66603,66564:66604,66565:66605,66566:66606,66567:66607,66568:66608,66569:66609,66570:66610,66571:66611,66572:66612,66573:66613,66574:66614,66575:66615,66576:66616,66577:66617,66578:66618,66579:66619,66580:66620,66581:66621,66582:66622,66583:66623,66584:66624,66585:66625,66586:66626,66587:66627,66588:66628,66589:66629,66590:66630,66591:66631,66592:66632,66593:66633,66594:66634,66595:66635,66596:66636,66597:66637,66598:66638,66599:66639,66600:66560,66601:66561,66602:66562,66603:66563,66604:66564,66605:66565,66606:66566,66607:66567,66608:66568,66609:66569,66610:66570,66611:66571,66612:66572,66613:66573,66614:66574,66615:66575,66616:66576,66617:66577,66618:66578,66619:66579,66620:66580,66621:66581,66622:66582,66623:66583,66624:66584,66625:66585,66626:66586,66627:66587,66628:66588,66629:66589,66630:66590,66631:66591,66632:66592,66633:66593,66634:66594,66635:66595,66636:66596,66637:66597,66638:66598,66639:66599,71840:71872,71841:71873,71842:71874,71843:71875,71844:71876,71845:71877,71846:71878,71847:71879,71848:71880,71849:71881,71850:71882,71851:71883,71852:71884,71853:71885,71854:71886,71855:71887,71856:71888,71857:71889,71858:71890,71859:71891,71860:71892,71861:71893,71862:71894,71863:71895,71864:71896,71865:71897,71866:71898,71867:71899,71868:71900,71869:71901,71870:71902,71871:71903,71872:71840,71873:71841,71874:71842,71875:71843,71876:71844,71877:71845,71878:71846,71879:71847,71880:71848,71881:71849,71882:71850,71883:71851,71884:71852,71885:71853,71886:71854,71887:71855,71888:71856,71889:71857,71890:71858,71891:71859,71892:71860,71893:71861,71894:71862,71895:71863,71896:71864,71897:71865,71898:71866,71899:71867,71900:71868,71901:71869,71902:71870,71903:71871}},{}],174:[function(n,t,r){(function(n){(function(k){var y=typeof r=="object"&&r;var I=typeof t=="object"&&t&&t.exports==y&&t;var c=typeof n=="object"&&n;if(c.global===c||c.window===c){k=c}var p={rangeOrder:"A range’s `stop` value must be greater than or equal "+"to the `start` value.",codePointRange:"Invalid code point value. Code points range from "+"U+000000 to U+10FFFF."};var i=55296;var a=56319;var u=56320;var b=57343;var X=/\\x00([^0123456789]|$)/g;var T={};var U=T.hasOwnProperty;var B=function(r,t){var e;for(e in t){if(U.call(t,e)){r[e]=t[e]}}return r};var v=function(t,r){var e=-1;var n=t.length;while(++e<n){r(t[e],e)}};var O=T.toString;var _=function(e){return O.call(e)=="[object Array]"};var l=function(e){return typeof e=="number"||O.call(e)=="[object Number]"};var q="0000";var N=function(r,t){var e=String(r);return e.length<t?(q+e).slice(-t):e};var w=function(e){return Number(e).toString(16).toUpperCase()};var S=[].slice;var $=function(a){var i=-1;var s=a.length;var o=s-1;var t=[];var n=true;var e;var r=0;while(++i<s){e=a[i];if(n){t.push(e);r=e;n=false}else{if(e==r+1){if(i!=o){r=e;continue}else{n=true;t.push(e+1)}}else{t.push(r+1,e);r=e}}}if(!n){t.push(e+1)}return t};var C=function(e,t){var r=0;var n;var i;var a=e.length;while(r<a){n=e[r];i=e[r+1];if(t>=n&&t<i){if(t==n){if(i==n+1){e.splice(r,2);return e}else{e[r]=t+1;return e}}else if(t==i-1){e[r+1]=t;return e}else{e.splice(r,2,n,t,t+1,i);return e}}r+=2}return e};var A=function(e,n,r){if(r<n){throw Error(p.rangeOrder)}var t=0;var i;var a;while(t<e.length){i=e[t];a=e[t+1]-1;if(i>r){return e}if(n<=i&&r>=a){e.splice(t,2);continue}if(n>=i&&r<a){if(n==i){e[t]=r+1;e[t+1]=a+1;return e}e.splice(t,2,i,n,r+1,a+1);return e}if(n>=i&&n<=a){e[t+1]=n}else if(r>=i&&r<=a){e[t]=r+1;return e}t+=2}return e};var d=function(e,t){var r=0;var n;var i;var a=null;var s=e.length;if(t<0||t>1114111){throw RangeError(p.codePointRange)}while(r<s){n=e[r];i=e[r+1];if(t>=n&&t<i){return e}if(t==n-1){e[r]=t;return e}if(n>t){e.splice(a!=null?a+2:0,0,t,t+1);return e}if(t==i){if(t+1==e[r+2]){e.splice(r,4,n,e[r+3]);return e}e[r+1]=t+1;return e}a=r;r+=2}e.push(t,t+1);return e};var P=function(a,n){var t=0;var r;var i;var e=a.slice();var s=n.length;while(t<s){r=n[t];i=n[t+1]-1;if(r==i){e=d(e,r)}else{e=m(e,r,i)}t+=2}return e};var V=function(a,n){var t=0;var r;var i;var e=a.slice();var s=n.length;while(t<s){r=n[t];i=n[t+1]-1;if(r==i){e=C(e,r)}else{e=A(e,r,i)}t+=2}return e};var m=function(e,t,r){if(r<t){throw Error(p.rangeOrder)}if(t<0||t>1114111||r<0||r>1114111){throw RangeError(p.codePointRange)}var n=0;var i;var a;var s=false;var o=e.length;while(n<o){i=e[n];a=e[n+1];if(s){if(i==r+1){e.splice(n-1,2);return e}if(i>r){return e}if(i>=t&&i<=r){if(a>t&&a-1<=r){e.splice(n,2);n-=2}else{e.splice(n-1,2);n-=2}}}else if(i==r+1){e[n]=t;return e}else if(i>r){e.splice(n,0,t,r+1);return e}else if(t>=i&&t<a&&r+1<=a){return e}else if(t>=i&&t<a||a==t){e[n+1]=r+1;s=true}else if(t<=i&&r+1>=a){e[n]=t;e[n+1]=r+1;s=true}n+=2}if(!s){e.push(t,r+1)}return e};var j=function(t,r){var e=0;var n;var i;var a=t.length;while(e<a){n=t[e];i=t[e+1];if(r>=n&&r<i){return true}e+=2}return false};var J=function(i,r){var e=0;var a=r.length;var t;var n=[];while(e<a){t=r[e];if(j(i,t)){n.push(t)}++e}return $(n)};var g=function(e){return!e.length};var x=function(e){return e.length==2&&e[0]+1==e[1]};var R=function(r){var e=0;var t;var n;var i=[];var a=r.length;while(e<a){t=r[e];n=r[e+1];while(t<n){i.push(t);++t}e+=2}return i};var K=Math.floor;var D=function(e){return parseInt(K((e-65536)/1024)+i,10)};var M=function(e){return parseInt((e-65536)%1024+u,10)};var L=String.fromCharCode;var f=function(e){var t;if(e==9){t="\\t"}else if(e==10){t="\\n"}else if(e==12){t="\\f"}else if(e==13){t="\\r"}else if(e==92){t="\\\\"}else if(e==36||e>=40&&e<=43||e==45||e==46||e==63||e>=91&&e<=94||e>=123&&e<=125){t="\\"+L(e)}else if(e>=32&&e<=126){t=L(e)}else if(e<=255){t="\\x"+N(w(e),2)}else{t="\\u"+N(w(e),4)}return t};var o=function(t){var n=t.length;var e=t.charCodeAt(0);var r;if(e>=i&&e<=a&&n>1){r=t.charCodeAt(1);return(e-i)*1024+r-u+65536}return e};var h=function(t){var n="";var i=0;var e;var r;var a=t.length;if(x(t)){return f(t[0])}while(i<a){e=t[i];r=t[i+1]-1;if(e==r){n+=f(e)}else if(e+1==r){n+=f(e)+f(r)}else{n+=f(e)+"-"+f(r)}i+=2}return"["+n+"]"};var G=function(o){var n=[];var r=[];var l=[];var s=0;var e;var t;var u=o.length;while(s<u){e=o[s];t=o[s+1]-1;if(e<=65535&&t<=65535){if(e>=i&&e<=a){if(t<=a){n.push(e,t+1)}else{n.push(e,a+1);r.push(a+1,t+1)}}else if(t>=i&&t<=a){r.push(e,i);n.push(i,t+1)}else if(e<i&&t>a){r.push(e,i,a+1,t+1);n.push(i,a+1)}else{r.push(e,t+1)}}else if(e<=65535&&t>65535){if(e>=i&&e<=a){n.push(e,a+1);r.push(a+1,65535+1)}else if(e<i){r.push(e,i,a+1,65535+1);n.push(i,a+1)}else{r.push(e,65535+1)}l.push(65535+1,t+1)}else{l.push(e,t+1)}s+=2}return{loneHighSurrogates:n,bmp:r,astral:l}};var F=function(s){var u=[];var r=[];var f=false;var t;var e;var a;var l;var o;var i;var n=-1;var c=s.length;while(++n<c){t=s[n];e=s[n+1];if(!e){u.push(t);continue}a=t[0];l=t[1];o=e[0];i=e[1];r=l;while(o&&a[0]==o[0]&&a[1]==o[1]){if(x(i)){r=d(r,i[0])}else{r=m(r,i[0],i[1]-1)}++n;t=s[n];a=t[0];l=t[1];e=s[n+1];o=e&&e[0];i=e&&e[1];f=true}u.push([a,f?r:l]);f=false}return W(u)};var W=function(e){if(e.length==1){return e}var i=-1;var t=-1;while(++i<e.length){var r=e[i];var a=r[1];var f=a[0];var l=a[1];t=i;while(++t<e.length){var n=e[t];var s=n[1];var u=s[0];var o=s[1];if(f==u&&l==o){if(x(n[0])){r[0]=d(r[0],n[0][0])}else{r[0]=m(r[0],n[0][0],n[0][1]-1)}e.splice(t,1);--t}}}return e};var H=function(i){if(!i.length){return[]}var o=0;var f;var l;var e;var a;var d=0;var p=0;var v=[];var t;var n;var r=[];var m=i.length;var y=[];while(o<m){f=i[o];l=i[o+1]-1;e=D(f);a=M(f);t=D(l);n=M(l);var h=a==u;var c=n==b;var s=false;if(e==t||h&&c){r.push([[e,t+1],[a,n+1]]);s=true}else{r.push([[e,e+1],[a,b+1]])}if(!s&&e+1<t){if(c){r.push([[e+1,t+1],[u,n+1]]);s=true}else{r.push([[e+1,t],[u,b+1]])}}if(!s){r.push([[t,t+1],[u,n+1]])}d=e;p=t;o+=2}return F(r)};var z=function(t){var e=[];v(t,function(t){var r=t[0];var n=t[1];e.push(h(r)+h(n))});return e.join("|")};var Y=function(o){var e=[];var t=G(o);var n=t.loneHighSurrogates;var r=t.bmp;var l=t.astral;var i=!g(t.astral);var a=!g(n);var s=H(l);if(!i&&a){r=P(r,n)}if(!g(r)){e.push(h(r))}if(s.length){e.push(z(s))}if(i&&a){e.push(h(n))}return e.join("|")};var s=function(e){if(arguments.length>1){e=S.call(arguments)}if(this instanceof s){this.data=[];return e?this.add(e):this}return(new s).add(e)};s.version="1.0.1";var E=s.prototype;B(E,{add:function(e){var t=this;if(e==null){return t}if(e instanceof s){t.data=P(t.data,e.data);return t}if(arguments.length>1){e=S.call(arguments)}if(_(e)){v(e,function(e){t.add(e)});return t}t.data=d(t.data,l(e)?e:o(e));return t},remove:function(e){var t=this;if(e==null){return t}if(e instanceof s){t.data=V(t.data,e.data);return t}if(arguments.length>1){e=S.call(arguments)}if(_(e)){v(e,function(e){t.remove(e)});return t}t.data=C(t.data,l(e)?e:o(e));return t},addRange:function(e,t){var r=this;r.data=m(r.data,l(e)?e:o(e),l(t)?t:o(t));return r},removeRange:function(e,t){var r=this;var n=l(e)?e:o(e);var i=l(t)?t:o(t);r.data=A(r.data,n,i);return r},intersection:function(e){var t=this;var r=e instanceof s?R(e.data):e;t.data=J(t.data,r);return t},contains:function(e){return j(this.data,l(e)?e:o(e))},clone:function(){var e=new s;e.data=this.data.slice(0);return e},toString:function(){var e=Y(this.data);return e.replace(X,"\\0$1")},toRegExp:function(e){return RegExp(this.toString(),e||"")},valueOf:function(){return R(this.data)}});E.toArray=E.valueOf;if(typeof e=="function"&&typeof e.amd=="object"&&e.amd){e(function(){return s})}else if(y&&!y.nodeType){if(I){I.exports=s}else{y.regenerate=s}}else{k.regenerate=s}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],175:[function(n,t,r){(function(n){(function(){"use strict";var o={"function":true,object:true};var f=o[typeof window]&&window||this;var T=f;var l=o[typeof r]&&r;var d=o[typeof t]&&t&&!t.nodeType&&t;var s=l&&d&&typeof n=="object"&&n;if(s&&(s.global===s||s.window===s||s.self===s)){f=s}var x=String.fromCharCode;var m=Math.floor;function u(){var o=16384;var t=[];var i;var a;var r=-1;var n=arguments.length;if(!n){return""}var s="";while(++r<n){var e=Number(arguments[r]);if(!isFinite(e)||e<0||e>1114111||m(e)!=e){throw RangeError("Invalid code point: "+e)}if(e<=65535){t.push(e)}else{e-=65536;i=(e>>10)+55296;a=e%1024+56320;t.push(i,a)}if(r+1==n||t.length>o){s+=x.apply(null,t);t.length=0}}return s}function a(t,e){if(e.indexOf("|")==-1){if(t==e){return}throw Error("Invalid node type: "+t)}e=a.hasOwnProperty(e)?a[e]:a[e]=RegExp("^(?:"+e+")$");if(e.test(t)){return}throw Error("Invalid node type: "+t)}function i(t){var e=t.type;if(i.hasOwnProperty(e)&&typeof i[e]=="function"){return i[e](t)}throw Error("Invalid node type: "+e)}function h(t){a(t.type,"alternative");var e=t.body,r=e?e.length:0;if(r==1){return p(e[0])}else{var n=-1,i="";while(++n<r){i+=p(e[n])}return i}}function A(e){a(e.type,"anchor");switch(e.kind){case"start":return"^";case"end":return"$";case"boundary":return"\\b";case"not-boundary":return"\\B";default:throw Error("Invalid assertion")}}function v(e){a(e.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value");return i(e)}function g(t){a(t.type,"characterClass");var r=t.body,i=r?r.length:0;var n=-1,e="[";if(t.negative){e+="^"}while(++n<i){e+=c(r[n])}e+="]";return e}function b(e){a(e.type,"characterClassEscape");return"\\"+e.value}function E(e){a(e.type,"characterClassRange");var t=e.min,r=e.max;if(t.type=="characterClassRange"||r.type=="characterClassRange"){throw Error("Invalid character class range")}return c(t)+"-"+c(r)}function c(e){a(e.type,"anchor|characterClassEscape|characterClassRange|dot|value");return i(e)}function S(s){a(s.type,"disjunction");var e=s.body,t=e?e.length:0;if(t==0){throw Error("No body")
}else if(t==1){return i(e[0])}else{var r=-1,n="";while(++r<t){if(r!=0){n+="|"}n+=i(e[r])}return n}}function w(e){a(e.type,"dot");return"."}function k(t){a(t.type,"group");var e="(";switch(t.behavior){case"normal":break;case"ignore":e+="?:";break;case"lookahead":e+="?=";break;case"negativeLookahead":e+="?!";break;default:throw Error("Invalid behaviour: "+t.behaviour)}var r=t.body,n=r?r.length:0;if(n==1){e+=i(r[0])}else{var s=-1;while(++s<n){e+=i(r[s])}}e+=")";return e}function I(r){a(r.type,"quantifier");var e="",t=r.min,n=r.max;switch(n){case undefined:case null:switch(t){case 0:e="*";break;case 1:e="+";break;default:e="{"+t+",}";break}break;default:if(t==n){e="{"+t+"}"}else if(t==0&&n==1){e="?"}else{e="{"+t+","+n+"}"}break}if(!r.greedy){e+="?"}return v(r.body[0])+e}function C(e){a(e.type,"reference");return"\\"+e.matchIndex}function p(e){a(e.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value");return i(e)}function y(t){a(t.type,"value");var r=t.kind,e=t.codePoint;switch(r){case"controlLetter":return"\\c"+u(e+64);case"hexadecimalEscape":return"\\x"+("00"+e.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+u(e);case"null":return"\\"+e;case"octal":return"\\"+e.toString(8);case"singleEscape":switch(e){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 11:return"\\v";case 12:return"\\f";case 13:return"\\r";default:throw Error("Invalid codepoint: "+e)}case"symbol":return u(e);case"unicodeEscape":return"\\u"+("0000"+e.toString(16).toUpperCase()).slice(-4);case"unicodeCodePointEscape":return"\\u{"+e.toString(16).toUpperCase()+"}";default:throw Error("Unsupported node kind: "+r)}}i.alternative=h;i.anchor=A;i.characterClass=g;i.characterClassEscape=b;i.characterClassRange=E;i.disjunction=S;i.dot=w;i.group=k;i.quantifier=I;i.reference=C;i.value=y;if(typeof e=="function"&&typeof e.amd=="object"&&e.amd){e(function(){return{generate:i}})}else if(l&&d){l.generate=i}else{f.regjsgen={generate:i}}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],176:[function(t,e,r){(function(){function r(n,_){var m=(_||"").indexOf("u")!==-1;var e=0;var y=0;function i(e){e.raw=n.substring(e.range[0],e.range[1]);return e}function k(e,t){e.range[0]=t;return i(e)}function l(t,r){return i({type:"anchor",kind:t,range:[e-r,e]})}function p(e,t,r,n){return i({type:"value",kind:e,codePoint:t,range:[r,n]})}function a(r,n,i,t){t=t||0;return p(r,n,e-(i.length+t),e)}function u(i){var n=i[0];var t=n.charCodeAt(0);if(m){var r;if(n.length===1&&t>=55296&&t<=56319){r=L().charCodeAt(0);if(r>=56320&&r<=57343){e++;return p("symbol",(t-55296)*1024+r-56320+65536,e-2,e)}}}return p("symbol",t,e-1,e)}function z(e,t,r){return i({type:"disjunction",body:e,range:[t,r]})}function J(){return i({type:"dot",range:[e-1,e]})}function G(t){return i({type:"characterClassEscape",value:t,range:[e-2,e]})}function F(t){return i({type:"reference",matchIndex:parseInt(t,10),range:[e-1-t.length,e]})}function N(e,t,r,n){return i({type:"group",behavior:e,body:t,range:[r,n]})}function o(n,a,r,t){if(t==null){r=e-1;t=e}return i({type:"quantifier",min:n,max:a,greedy:true,body:null,range:[r,t]})}function R(e,t,r){return i({type:"alternative",body:e,range:[t,r]})}function g(e,t,r,n){return i({type:"characterClass",body:e,negative:t,range:[r,n]})}function b(e,t,r,n){if(e.codePoint>t.codePoint){throw SyntaxError("invalid range in character class")}return i({type:"characterClassRange",min:e,max:t,range:[r,n]})}function E(e){if(e.type==="alternative"){return e.body}else{return[e]}}function $(e){return e.type==="empty"}function c(t){t=t||1;var r=n.substring(e,e+t);e+=t||1;return r}function f(e){if(!t(e)){throw SyntaxError("character: "+e)}}function t(t){if(n.indexOf(t,e)===e){return c(t.length)}}function L(){return n[e]}function s(t){return n.indexOf(t,e)===e}function A(t){return n[e+1]===t}function r(r){var i=n.substring(e);var t=i.match(r);if(t){t.range=[];t.range[0]=e;c(t[0].length);t.range[1]=e}return t}function P(){var r=[],n=e;r.push(I());while(t("|")){r.push(I())}if(r.length===1){return r[0]}return z(r,n,e)}function I(){var t=[],n=e;var r;while(r=V()){t.push(r)}if(t.length===1){return t[0]}return R(t,n,e)}function V(){if(e>=n.length||s("|")||s(")")){return null}var i=M();if(i){return i}var t=D();if(!t){throw SyntaxError("Expected atom")}var r=O()||false;if(r){r.body=E(t);k(r,t.range[0]);return r}return t}function x(i,a,s,o){var r=null,l=e;if(t(i)){r=a}else if(t(s)){r=o}else{return false}var n=P();if(!n){throw SyntaxError("Expected disjunction")}f(")");var u=N(r,E(n),l,e);if(r=="normal"){y++}return u}function M(){var r,n=e;if(t("^")){return l("start",1)}else if(t("$")){return l("end",1)}else if(t("\\b")){return l("boundary",2)}else if(t("\\B")){return l("not-boundary",2)}else{return x("(?=","lookahead","(?!","negativeLookahead")}}function O(){var e;var n;var i,a;if(t("*")){n=o(0)}else if(t("+")){n=o(1)}else if(t("?")){n=o(0,1)}else if(e=r(/^\{([0-9]+)\}/)){i=parseInt(e[1],10);n=o(i,i,e.range[0],e.range[1])}else if(e=r(/^\{([0-9]+),\}/)){i=parseInt(e[1],10);n=o(i,undefined,e.range[0],e.range[1])}else if(e=r(/^\{([0-9]+),([0-9]+)\}/)){i=parseInt(e[1],10);a=parseInt(e[2],10);if(i>a){throw SyntaxError("numbers out of order in {} quantifier")}n=o(i,a,e.range[0],e.range[1])}if(n){if(t("?")){n.greedy=false;n.range[1]+=1}}return n}function D(){var e;if(e=r(/^[^^$\\.*+?(){[|]/)){return u(e)}else if(t(".")){return J()}else if(t("\\")){e=C();if(!e){throw SyntaxError("atomEscape")}return e}else if(e=X()){return e}else{return x("(?:","ignore","(","normal")}}function v(t){if(m){var r,n;if(t.kind=="unicodeEscape"&&(r=t.codePoint)>=55296&&r<=56319&&s("\\")&&A("u")){var o=e;e++;var a=T();if(a.kind=="unicodeEscape"&&(n=a.codePoint)>=56320&&n<=57343){t.range[1]=a.range[1];t.codePoint=(r-55296)*1024+n-56320+65536;t.type="value";t.kind="unicodeCodePointEscape";i(t)}else{e=o}}}return t}function T(){return C(true)}function C(r){var e;e=B();if(e){return e}if(r){if(t("b")){return a("singleEscape",8,"\\b")}else if(t("B")){throw SyntaxError("\\B not possible inside of CharacterClass")}}e=Y();return e}function B(){var e,t;if(e=r(/^(?!0)\d+/)){t=e[0];var n=parseInt(e[0],10);if(n<=y){return F(e[0])}else{c(-e[0].length);if(e=r(/^[0-7]{1,3}/)){return a("octal",parseInt(e[0],8),e[0],1)}else{e=u(r(/^[89]/));return k(e,e.range[0]-1)}}}else if(e=r(/^[0-7]{1,3}/)){t=e[0];if(/^0{1,3}$/.test(t)){return a("null",0,"0",t.length+1)}else{return a("octal",parseInt(t,8),t,1)}}else if(e=r(/^[dDsSwW]/)){return G(e[0])}return false}function Y(){var e;if(e=r(/^[fnrtv]/)){var t=0;switch(e[0]){case"t":t=9;break;case"n":t=10;break;case"v":t=11;break;case"f":t=12;break;case"r":t=13;break}return a("singleEscape",t,"\\"+e[0])}else if(e=r(/^c([a-zA-Z])/)){return a("controlLetter",e[1].charCodeAt(0)%32,e[1],2)}else if(e=r(/^x([0-9a-fA-F]{2})/)){return a("hexadecimalEscape",parseInt(e[1],16),e[1],2)}else if(e=r(/^u([0-9a-fA-F]{4})/)){return v(a("unicodeEscape",parseInt(e[1],16),e[1],2))}else if(m&&(e=r(/^u\{([0-9a-fA-F]{1,})\}/))){return a("unicodeCodePointEscape",parseInt(e[1],16),e[1],4)}else{return q()}}function U(e){var t=new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԯԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠ-ࢲࣤ-ॣ०-९ॱ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಁ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲഁ-ഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧ᪰-᪽ᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶ᳸᳹ᴀ-᷵᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚝꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꧠ-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︭︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]");return e===36||e===95||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===92||e>=128&&t.test(String.fromCharCode(e))}function q(){var r="";var n="";var i;var e;if(!U(L())){e=c();return a("identifier",e.charCodeAt(0),e,1)}if(t(r)){return a("identifier",8204,r)}else if(t(n)){return a("identifier",8205,n)}return null}function X(){var n,i=e;if(n=r(/^\[\^/)){n=d();f("]");return g(n,true,i,e)}else if(t("[")){n=d();f("]");return g(n,false,i,e)}return null}function d(){var e;if(s("]")){return[]}else{e=W();if(!e){throw SyntaxError("nonEmptyClassRanges")}return e}}function w(r){var n,i,t;if(s("-")&&!A("]")){f("-");t=h();if(!t){throw SyntaxError("classAtom")}i=e;var a=d();if(!a){throw SyntaxError("classRanges")}n=r.range[0];if(a.type==="empty"){return[b(r,t,n,i)]}return[b(r,t,n,i)].concat(a)}t=H();if(!t){throw SyntaxError("nonEmptyClassRangesNoDash")}return[r].concat(t)}function W(){var e=h();if(!e){throw SyntaxError("classAtom")}if(s("]")){return[e]}return w(e)}function H(){var e=h();if(!e){throw SyntaxError("classAtom")}if(s("]")){return e}return w(e)}function h(){if(t("-")){return u("-")}else{return j()}}function j(){var e;if(e=r(/^[^\\\]-]/)){return u(e[0])}else if(t("\\")){e=T();if(!e){throw SyntaxError("classEscape")}return v(e)}}n=String(n);if(n===""){n="(?:)"}var S=P();if(S.range[1]!==n.length){throw SyntaxError("Could not parse entire input - got stuck: "+n)}return S}var t={parse:r};if(typeof e!=="undefined"&&e.exports){e.exports=t}else{window.regjsparser=t}})()},{}],177:[function(t,h,w){var x=t("regjsgen").generate;var o=t("regjsparser").parse;var n=t("regenerate");var f=t("./data/iu-mappings.json");var a=t("./data/character-class-escape-sets.js");function l(t){if(e){if(r){return a.UNICODE_IGNORE_CASE[t]}return a.UNICODE[t]}return a.REGULAR[t]}var E={};var g=E.hasOwnProperty;function v(e,t){return g.call(e,t)}var m=n().addRange(0,1114111);var d=n().addRange(0,65535);var p=m.clone().remove(10,13,8232,8233);var y=p.clone().intersection(d);n.prototype.iuAddRange=function(e,n){var t=this;do{var r=s(e);if(r){t.add(r)}}while(++e<=n);return t};function c(r,e){for(var t in e){r[t]=e[t]}}function i(r,t){var e=o(t,"");switch(e.type){case"characterClass":case"group":case"value":break;default:e=b(e,t)}c(r,e)}function b(e,t){return{type:"group",behavior:"ignore",body:[e],raw:"(?:"+t+")"}}function s(e){return v(f,e)?f[e]:false}var r=false;var e=false;function S(a){var t=n();var o=a.body.forEach(function(n){switch(n.type){case"value":t.add(n.codePoint);if(r&&e){var i=s(n.codePoint);if(i){t.add(i)}}break;case"characterClassRange":var a=n.min.codePoint;var o=n.max.codePoint;t.addRange(a,o);if(r&&e){t.iuAddRange(a,o)}break;case"characterClassEscape":t.add(l(n.value));break;default:throw Error("Unknown term type: "+n.type)}});if(a.negative){t=(e?m:d).clone().remove(t)}i(a,t.toString());return a}function u(t){switch(t.type){case"dot":i(t,(e?p:y).toString());break;case"characterClass":t=S(t);break;case"characterClassEscape":i(t,l(t.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":t.body=t.body.map(u);break;case"value":var a=t.codePoint;var o=n(a);if(r&&e){var f=s(a);if(f){o.add(f)}}i(t,o.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+t.type)}return t}h.exports=function(i,t){var n=o(i,t);r=t?t.indexOf("i")>-1:false;e=t?t.indexOf("u")>-1:false;c(n,u(n));return x(n)}},{"./data/character-class-escape-sets.js":172,"./data/iu-mappings.json":173,regenerate:174,regjsgen:175,regjsparser:176}],178:[function(e,r,t){t.SourceMapGenerator=e("./source-map/source-map-generator").SourceMapGenerator;t.SourceMapConsumer=e("./source-map/source-map-consumer").SourceMapConsumer;t.SourceNode=e("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":183,"./source-map/source-map-generator":184,"./source-map/source-node":185}],179:[function(e,r,n){if(typeof t!=="function"){var t=e("amdefine")(r,e)}t(function(r,n,i){var t=r("./util");function e(){this._array=[];this._set={}}e.fromArray=function a(r,i){var n=new e;for(var t=0,a=r.length;t<a;t++){n.add(r[t],i)}return n};e.prototype.add=function s(e,n){var r=this.has(e);var i=this._array.length;if(!r||n){this._array.push(e)}if(!r){this._set[t.toSetString(e)]=i}};e.prototype.has=function o(e){return Object.prototype.hasOwnProperty.call(this._set,t.toSetString(e))};e.prototype.indexOf=function l(e){if(this.has(e)){return this._set[t.toSetString(e)]}throw new Error('"'+e+'" is not in the set.')};e.prototype.at=function u(e){if(e>=0&&e<this._array.length){return this._array[e]}throw new Error("No element indexed by "+e)};e.prototype.toArray=function f(){return this._array.slice()};n.ArraySet=e})},{"./util":186,amdefine:187}],180:[function(e,r,n){if(typeof t!=="function"){var t=e("amdefine")(r,e)}t(function(s,t,u){var r=s("./base64");var e=5;var n=1<<e;var i=n-1;var a=n;function o(e){return e<0?(-e<<1)+1:(e<<1)+0}function l(e){var r=(e&1)===1;var t=e>>1;return r?-t:t}t.encode=function f(l){var s="";var n;var t=o(l);do{n=t&i;t>>>=e;if(t>0){n|=a}s+=r.encode(n)}while(t>0);return s};t.decode=function c(n,u){var s=0;var p=n.length;var o=0;var f=0;var c,t;do{if(s>=p){throw new Error("Expected more digits in base 64 VLQ value.")}t=r.decode(n.charAt(s++));c=!!(t&a);t&=i;o=o+(t<<f);f+=e}while(c);u.value=l(o);u.rest=n.slice(s)}})},{"./base64":181,amdefine:187}],181:[function(e,r,n){if(typeof t!=="function"){var t=e("amdefine")(r,e)}t(function(n,r,i){var e={};var t={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(r,n){e[r]=n;t[n]=r});r.encode=function a(e){if(e in t){return t[e]}throw new TypeError("Must be between 0 and 63: "+e)};r.decode=function s(t){if(t in e){return e[t]}throw new TypeError("Not a valid base 64 digit: "+t)}})},{amdefine:187}],182:[function(e,r,n){if(typeof t!=="function"){var t=e("amdefine")(r,e)}t(function(r,t,n){function e(r,i,a,n,s){var t=Math.floor((i-r)/2)+r;var o=s(a,n[t],true);if(o===0){return n[t]}else if(o>0){if(i-t>1){return e(t,i,a,n,s)}return n[t]}else{if(t-r>1){return e(r,t,a,n,s)}return r<0?null:n[r]}}t.search=function i(r,t,n){return t.length>0?e(-1,t.length,r,t,n):null}})},{amdefine:187}],183:[function(e,r,n){if(typeof t!=="function"){var t=e("amdefine")(r,e)}t(function(n,a,o){var e=n("./util");var s=n("./binary-search");var i=n("./array-set").ArraySet;var r=n("./base64-vlq");function t(r){var t=r;if(typeof r==="string"){t=JSON.parse(r.replace(/^\)\]\}'/,""))}var n=e.getArg(t,"version");var a=e.getArg(t,"sources");var s=e.getArg(t,"names",[]);var o=e.getArg(t,"sourceRoot",null);var l=e.getArg(t,"sourcesContent",null);var u=e.getArg(t,"mappings");var f=e.getArg(t,"file",null);if(n!=this._version){throw new Error("Unsupported version: "+n)}this._names=i.fromArray(s,true);this._sources=i.fromArray(a,true);this.sourceRoot=o;this.sourcesContent=l;this._mappings=u;this.file=f}t.fromSourceMap=function l(n){var r=Object.create(t.prototype);r._names=i.fromArray(n._names.toArray(),true);r._sources=i.fromArray(n._sources.toArray(),true);r.sourceRoot=n._sourceRoot;r.sourcesContent=n._generateSourcesContent(r._sources.toArray(),r.sourceRoot);r.file=n._file;r.__generatedMappings=n._mappings.slice().sort(e.compareByGeneratedPositions);r.__originalMappings=n._mappings.slice().sort(e.compareByOriginalPositions);return r};t.prototype._version=3;Object.defineProperty(t.prototype,"sources",{get:function(){return this._sources.toArray().map(function(t){return this.sourceRoot!=null?e.join(this.sourceRoot,t):t},this)}});t.prototype.__generatedMappings=null;Object.defineProperty(t.prototype,"_generatedMappings",{get:function(){if(!this.__generatedMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__generatedMappings}});t.prototype.__originalMappings=null;Object.defineProperty(t.prototype,"_originalMappings",{get:function(){if(!this.__originalMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__originalMappings}});t.prototype._nextCharIsMappingSeparator=function u(t){var e=t.charAt(0);return e===";"||e===","};t.prototype._parseMappings=function f(c,p){var l=1;var a=0;var o=0;var s=0;var u=0;var f=0;var t=c;var n={};var i;while(t.length>0){if(t.charAt(0)===";"){l++;t=t.slice(1);a=0}else if(t.charAt(0)===","){t=t.slice(1)}else{i={};i.generatedLine=l;r.decode(t,n);i.generatedColumn=a+n.value;a=i.generatedColumn;t=n.rest;if(t.length>0&&!this._nextCharIsMappingSeparator(t)){r.decode(t,n);i.source=this._sources.at(u+n.value);u+=n.value;t=n.rest;if(t.length===0||this._nextCharIsMappingSeparator(t)){throw new Error("Found a source, but no line and column")}r.decode(t,n);i.originalLine=o+n.value;o=i.originalLine;i.originalLine+=1;t=n.rest;if(t.length===0||this._nextCharIsMappingSeparator(t)){throw new Error("Found a source and line, but no column")}r.decode(t,n);i.originalColumn=s+n.value;s=i.originalColumn;t=n.rest;if(t.length>0&&!this._nextCharIsMappingSeparator(t)){r.decode(t,n);i.name=this._names.at(f+n.value);f+=n.value;t=n.rest}}this.__generatedMappings.push(i);if(typeof i.originalLine==="number"){this.__originalMappings.push(i)}}}this.__generatedMappings.sort(e.compareByGeneratedPositions);this.__originalMappings.sort(e.compareByOriginalPositions)};t.prototype._findMapping=function c(e,n,t,r,i){if(e[t]<=0){throw new TypeError("Line must be greater than or equal to 1, got "+e[t])}if(e[r]<0){throw new TypeError("Column must be greater than or equal to 0, got "+e[r])}return s.search(e,n,i)};t.prototype.originalPositionFor=function p(n){var i={generatedLine:e.getArg(n,"line"),generatedColumn:e.getArg(n,"column")};var t=this._findMapping(i,this._generatedMappings,"generatedLine","generatedColumn",e.compareByGeneratedPositions);if(t&&t.generatedLine===i.generatedLine){var r=e.getArg(t,"source",null);if(r!=null&&this.sourceRoot!=null){r=e.join(this.sourceRoot,r)}return{source:r,line:e.getArg(t,"originalLine",null),column:e.getArg(t,"originalColumn",null),name:e.getArg(t,"name",null)}}return{source:null,line:null,column:null,name:null}};t.prototype.sourceContentFor=function d(t){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){t=e.relative(this.sourceRoot,t)}if(this._sources.has(t)){return this.sourcesContent[this._sources.indexOf(t)]}var r;if(this.sourceRoot!=null&&(r=e.urlParse(this.sourceRoot))){var n=t.replace(/^file:\/\//,"");if(r.scheme=="file"&&this._sources.has(n)){return this.sourcesContent[this._sources.indexOf(n)]}if((!r.path||r.path=="/")&&this._sources.has("/"+t)){return this.sourcesContent[this._sources.indexOf("/"+t)]}}throw new Error('"'+t+'" is not in the SourceMap.')};t.prototype.generatedPositionFor=function m(t){var r={source:e.getArg(t,"source"),originalLine:e.getArg(t,"line"),originalColumn:e.getArg(t,"column")};if(this.sourceRoot!=null){r.source=e.relative(this.sourceRoot,r.source)}var n=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",e.compareByOriginalPositions);if(n){return{line:e.getArg(n,"generatedLine",null),column:e.getArg(n,"generatedColumn",null)}}return{line:null,column:null}};t.GENERATED_ORDER=1;t.ORIGINAL_ORDER=2;t.prototype.eachMapping=function h(i,a,s){var o=a||null;var l=s||t.GENERATED_ORDER;var r;switch(l){case t.GENERATED_ORDER:r=this._generatedMappings;break;case t.ORIGINAL_ORDER:r=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var n=this.sourceRoot;r.map(function(t){var r=t.source;if(r!=null&&n!=null){r=e.join(n,r)}return{source:r,generatedLine:t.generatedLine,generatedColumn:t.generatedColumn,originalLine:t.originalLine,originalColumn:t.originalColumn,name:t.name}}).forEach(i,o)};a.SourceMapConsumer=t})},{"./array-set":179,"./base64-vlq":180,"./binary-search":182,"./util":186,amdefine:187}],184:[function(e,r,n){if(typeof t!=="function"){var t=e("amdefine")(r,e)}t(function(i,a,s){var r=i("./base64-vlq");var e=i("./util");var n=i("./array-set").ArraySet;function t(t){if(!t){t={}}this._file=e.getArg(t,"file",null);this._sourceRoot=e.getArg(t,"sourceRoot",null);this._sources=new n;this._names=new n;this._mappings=[];this._sourcesContents=null}t.prototype._version=3;t.fromSourceMap=function o(r){var n=r.sourceRoot;var i=new t({file:r.file,sourceRoot:n});r.eachMapping(function(t){var r={generated:{line:t.generatedLine,column:t.generatedColumn}};if(t.source!=null){r.source=t.source;if(n!=null){r.source=e.relative(n,r.source)}r.original={line:t.originalLine,column:t.originalColumn};if(t.name!=null){r.name=t.name}}i.addMapping(r)});r.sources.forEach(function(e){var t=r.sourceContentFor(e);if(t!=null){i.setSourceContent(e,t)}});return i};t.prototype.addMapping=function l(i){var a=e.getArg(i,"generated");var t=e.getArg(i,"original",null);var r=e.getArg(i,"source",null);var n=e.getArg(i,"name",null);this._validateMapping(a,t,r,n);if(r!=null&&!this._sources.has(r)){this._sources.add(r)}if(n!=null&&!this._names.has(n)){this._names.add(n)}this._mappings.push({generatedLine:a.line,generatedColumn:a.column,originalLine:t!=null&&t.line,originalColumn:t!=null&&t.column,source:r,name:n})};t.prototype.setSourceContent=function u(n,r){var t=n;if(this._sourceRoot!=null){t=e.relative(this._sourceRoot,t)}if(r!=null){if(!this._sourcesContents){this._sourcesContents={}}this._sourcesContents[e.toSetString(t)]=r}else if(this._sourcesContents){delete this._sourcesContents[e.toSetString(t)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};t.prototype.applySourceMap=function f(r,l,i){var a=l;if(l==null){if(r.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}a=r.file}var t=this._sourceRoot;if(t!=null){a=e.relative(t,a)}var s=new n;var o=new n;this._mappings.forEach(function(n){if(n.source===a&&n.originalLine!=null){var l=r.originalPositionFor({line:n.originalLine,column:n.originalColumn});if(l.source!=null){n.source=l.source;if(i!=null){n.source=e.join(i,n.source)}if(t!=null){n.source=e.relative(t,n.source)}n.originalLine=l.line;n.originalColumn=l.column;if(l.name!=null){n.name=l.name}}}var u=n.source;if(u!=null&&!s.has(u)){s.add(u)}var f=n.name;if(f!=null&&!o.has(f)){o.add(f)}},this);this._sources=s;this._names=o;r.sources.forEach(function(n){var a=r.sourceContentFor(n);if(a!=null){if(i!=null){n=e.join(i,n)}if(t!=null){n=e.relative(t,n)}this.setSourceContent(n,a)}},this)};t.prototype._validateMapping=function c(e,t,r,n){if(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!t&&!r&&!n){return}else if(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&r){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:t,name:n}))}};t.prototype._serializeMappings=function p(){var s=0;var a=1;var l=0;var u=0;var o=0;var f=0;var n="";var t;this._mappings.sort(e.compareByGeneratedPositions);for(var i=0,c=this._mappings.length;i<c;i++){t=this._mappings[i];if(t.generatedLine!==a){s=0;while(t.generatedLine!==a){n+=";";a++}}else{if(i>0){if(!e.compareByGeneratedPositions(t,this._mappings[i-1])){continue}n+=","}}n+=r.encode(t.generatedColumn-s);s=t.generatedColumn;if(t.source!=null){n+=r.encode(this._sources.indexOf(t.source)-f);f=this._sources.indexOf(t.source);n+=r.encode(t.originalLine-1-u);u=t.originalLine-1;n+=r.encode(t.originalColumn-l);l=t.originalColumn;if(t.name!=null){n+=r.encode(this._names.indexOf(t.name)-o);o=this._names.indexOf(t.name)}}}return n};t.prototype._generateSourcesContent=function d(r,t){return r.map(function(r){if(!this._sourcesContents){return null}if(t!=null){r=e.relative(t,r)}var n=e.toSetString(r);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null},this)};t.prototype.toJSON=function m(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){e.file=this._file}if(this._sourceRoot!=null){e.sourceRoot=this._sourceRoot}if(this._sourcesContents){e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)}return e};t.prototype.toString=function h(){return JSON.stringify(this)};a.SourceMapGenerator=t})},{"./array-set":179,"./base64-vlq":180,"./util":186,amdefine:187}],185:[function(e,r,n){if(typeof t!=="function"){var t=e("amdefine")(r,e)}t(function(r,i,o){var a=r("./source-map-generator").SourceMapGenerator;var t=r("./util");var n=/(\r?\n)/;var s=/\r\n|[\s\S]/g;function e(e,t,r,n,i){this.children=[];this.sourceContents={};this.line=e==null?null:e;this.column=t==null?null:t;this.source=r==null?null:r;this.name=i==null?null:i;if(n!=null)this.add(n)}e.fromStringWithSourceMap=function l(p,f,o){var i=new e;var r=p.split(n);var u=function(){var e=r.shift();var t=r.shift()||"";return e+t};var l=1,s=0;var a=null;f.eachMapping(function(e){if(a!==null){if(l<e.generatedLine){var n="";c(a,u());l++;s=0}else{var t=r[0];var n=t.substr(0,e.generatedColumn-s);r[0]=t.substr(e.generatedColumn-s);s=e.generatedColumn;c(a,n);a=e;return}}while(l<e.generatedLine){i.add(u());l++}if(s<e.generatedColumn){var t=r[0];i.add(t.substr(0,e.generatedColumn));r[0]=t.substr(e.generatedColumn);s=e.generatedColumn}a=e},this);if(r.length>0){if(a){c(a,u())}i.add(r.join(""))}f.sources.forEach(function(e){var r=f.sourceContentFor(e);if(r!=null){if(o!=null){e=t.join(o,e)}i.setSourceContent(e,r)}});return i;function c(r,n){if(r===null||r.source===undefined){i.add(n)}else{var a=o?t.join(o,r.source):r.source;i.add(new e(r.originalLine,r.originalColumn,a,n,r.name))}}};e.prototype.add=function u(t){if(Array.isArray(t)){t.forEach(function(e){this.add(e)},this)}else if(t instanceof e||typeof t==="string"){if(t){this.children.push(t)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+t)}return this};e.prototype.prepend=function f(t){if(Array.isArray(t)){for(var r=t.length-1;r>=0;r--){this.prepend(t[r])}}else if(t instanceof e||typeof t==="string"){this.children.unshift(t)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+t)}return this};e.prototype.walk=function c(n){var t;for(var r=0,i=this.children.length;r<i;r++){t=this.children[r];if(t instanceof e){t.walk(n)}else{if(t!==""){n(t,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};e.prototype.join=function p(n){var e;var t;var r=this.children.length;if(r>0){e=[];for(t=0;t<r-1;t++){e.push(this.children[t]);e.push(n)}e.push(this.children[t]);this.children=e}return this};e.prototype.replaceRight=function d(r,n){var t=this.children[this.children.length-1];if(t instanceof e){t.replaceRight(r,n)}else if(typeof t==="string"){this.children[this.children.length-1]=t.replace(r,n)}else{this.children.push("".replace(r,n))}return this};e.prototype.setSourceContent=function m(e,r){this.sourceContents[t.toSetString(e)]=r};e.prototype.walkSourceContents=function h(i){for(var r=0,a=this.children.length;r<a;r++){if(this.children[r]instanceof e){this.children[r].walkSourceContents(i)}}var n=Object.keys(this.sourceContents);for(var r=0,a=n.length;r<a;r++){i(t.fromSetString(n[r]),this.sourceContents[n[r]])}};e.prototype.toString=function y(){var e="";this.walk(function(t){e+=t});return e};e.prototype.toStringWithSourceMap=function v(f){var e={code:"",line:1,column:0};var t=new a(f);var r=false;var i=null;var o=null;var l=null;var u=null;this.walk(function(f,a){e.code+=f;if(a.source!==null&&a.line!==null&&a.column!==null){if(i!==a.source||o!==a.line||l!==a.column||u!==a.name){t.addMapping({source:a.source,original:{line:a.line,column:a.column},generated:{line:e.line,column:e.column},name:a.name})}i=a.source;o=a.line;l=a.column;u=a.name;r=true}else if(r){t.addMapping({generated:{line:e.line,column:e.column}});i=null;r=false}f.match(s).forEach(function(s,o,l){if(n.test(s)){e.line++;e.column=0;if(o+1===l.length){i=null;r=false}else if(r){t.addMapping({source:a.source,original:{line:a.line,column:a.column},generated:{line:e.line,column:e.column},name:a.name})}}else{e.column+=s.length}})});this.walkSourceContents(function(e,r){t.setSourceContent(e,r)});return{code:e.code,map:t}};i.SourceNode=e})},{"./source-map-generator":184,"./util":186,amdefine:187}],186:[function(e,r,n){if(typeof t!=="function"){var t=e("amdefine")(r,e)}t(function(h,e,m){function l(t,e,r){if(e in t){return t[e]}else if(arguments.length===3){return r}else{throw new Error('"'+e+'" is a required argument.')}}e.getArg=l;var d=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;var a=/^data:.+\,.+$/;function t(t){var e=t.match(d);if(!e){return null}return{scheme:e[1],auth:e[2],host:e[3],port:e[4],path:e[5]}}e.urlParse=t;function r(e){var t="";if(e.scheme){t+=e.scheme+":"}t+="//";if(e.auth){t+=e.auth+"@"}if(e.host){t+=e.host}if(e.port){t+=":"+e.port}if(e.path){t+=e.path}return t}e.urlGenerate=r;function i(l){var e=l;var n=t(l);if(n){if(!n.path){return l}e=n.path}var u=e.charAt(0)==="/";var i=e.split(/\/+/);for(var o,s=0,a=i.length-1;a>=0;a--){o=i[a];if(o==="."){i.splice(a,1)}else if(o===".."){s++}else if(s>0){if(o===""){i.splice(a+1,s);s=0}else{i.splice(a,2);s--}}}e=i.join("/");if(e===""){e=u?"/":"."}if(n){n.path=e;return r(n)}return e}e.normalize=i;function u(s,n){if(s===""){s="."}if(n===""){n="."}var o=t(n);var e=t(s);if(e){s=e.path||"/"}if(o&&!o.scheme){if(e){o.scheme=e.scheme}return r(o)}if(o||n.match(a)){return n}if(e&&!e.host&&!e.path){e.host=n;return r(e)}var l=n.charAt(0)==="/"?n:i(s.replace(/\/+$/,"")+"/"+n);if(e){e.path=l;return r(e)}return l}e.join=u;function f(e,r){if(e===""){e="."}e=e.replace(/\/$/,"");var n=t(e);if(r.charAt(0)=="/"&&n&&n.path=="/"){return r.slice(1)}return r.indexOf(e+"/")===0?r.substr(e.length+1):r}e.relative=f;function c(e){return"$"+e}e.toSetString=c;function p(e){return e.substr(1)}e.fromSetString=p;function n(r,n){var e=r||"";var t=n||"";return(e>t)-(e<t)}function o(t,r,i){var e;e=n(t.source,r.source);if(e){return e}e=t.originalLine-r.originalLine;if(e){return e}e=t.originalColumn-r.originalColumn;if(e||i){return e}e=n(t.name,r.name);if(e){return e}e=t.generatedLine-r.generatedLine;if(e){return e}return t.generatedColumn-r.generatedColumn}e.compareByOriginalPositions=o;function s(t,r,i){var e;e=t.generatedLine-r.generatedLine;if(e){return e}e=t.generatedColumn-r.generatedColumn;if(e||i){return e}e=n(t.source,r.source);if(e){return e}e=t.originalLine-r.originalLine;if(e){return e}e=t.originalColumn-r.originalColumn;if(e){return e}return n(t.name,r.name)}e.compareByGeneratedPositions=s})},{amdefine:187}],187:[function(e,t,r){(function(r,n){"use strict";function i(i,l){"use strict";var a={},t={},p=false,d=e("path"),s,u;function m(t){var e,r;for(e=0;t[e];e+=1){r=t[e];if(r==="."){t.splice(e,1);e-=1}else if(r===".."){if(e===1&&(t[2]===".."||t[0]==="..")){break}else if(e>0){t.splice(e-1,2);e-=2}}}}function o(t,r){var e;if(t&&t.charAt(0)==="."){if(r){e=r.split("/");e=e.slice(0,e.length-1);e=e.concat(t.split("/"));m(e);t=e.join("/")}}return t}function h(e){return function(t){return o(t,e)}}function y(r){function e(e){t[r]=e}e.fromText=function(e,t){throw new Error("amdefine does not implement load.fromText")};return e}s=function(t,n,e,i){function a(a,s){if(typeof a==="string"){return u(t,n,e,a,i)}else{a=a.map(function(r){return u(t,n,e,r,i)});r.nextTick(function(){s.apply(null,a)})}}a.toUrl=function(t){if(t.indexOf(".")===0){return o(t,d.dirname(e.filename))}else{return t}};return a};l=l||function v(){return i.require.apply(i,arguments)};function f(r,o,f){var c,a,e,u;if(r){a=t[r]={};e={id:r,uri:n,exports:a};c=s(l,a,e,r)}else{if(p){throw new Error("amdefine with no module ID cannot be called more than once per file.")
}p=true;a=i.exports;e=i;c=s(l,a,e,i.id)}if(o){o=o.map(function(e){return c(e)})}if(typeof f==="function"){u=f.apply(e.exports,o)}else{u=f}if(u!==undefined){e.exports=u;if(r){t[r]=e.exports}}}u=function(n,i,l,e,r){var p=e.indexOf("!"),m=e,d,c;if(p===-1){e=o(e,r);if(e==="require"){return s(n,i,l,r)}else if(e==="exports"){return i}else if(e==="module"){return l}else if(t.hasOwnProperty(e)){return t[e]}else if(a[e]){f.apply(null,a[e]);return t[e]}else{if(n){return n(m)}else{throw new Error("No module with ID: "+e)}}}else{d=e.substring(0,p);e=e.substring(p+1,e.length);c=u(n,i,l,d,r);if(c.normalize){e=c.normalize(e,h(r))}else{e=o(e,r)}if(t[e]){return t[e]}else{c.load(e,s(n,i,l,r),y(e),{});return t[e]}}};function c(t,e,r){if(Array.isArray(t)){r=e;e=t;t=undefined}else if(typeof t!=="string"){r=t;t=e=undefined}if(e&&!Array.isArray(e)){r=e;e=undefined}if(!e){e=["require","exports","module"]}if(t){a[t]=[t,e,r]}else{f(t,e,r)}}c.require=function(e){if(t[e]){return t[e]}if(a[e]){f.apply(null,a[e]);return t[e]}};c.amd={};return c}t.exports=i}).call(this,e("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:112,path:111}],188:[function(t,e,r){e.exports={name:"6to5",description:"Turn ES6 code into readable vanilla ES5 with source maps",version:"2.12.6",author:"Sebastian McKenzie <[email protected]>",homepage:"https://6to5.org/",repository:"6to5/6to5",preferGlobal:true,main:"lib/6to5/index.js",bin:{"6to5":"./bin/6to5/index.js","6to5-node":"./bin/6to5-node","6to5-runtime":"./bin/6to5-runtime"},browser:{"./lib/6to5/index.js":"./lib/6to5/browser.js","./lib/6to5/register.js":"./lib/6to5/register-browser.js"},keywords:["harmony","classes","modules","let","const","var","es6","transpile","transpiler","6to5"],scripts:{bench:"make bench",test:"make test"},dependencies:{"acorn-6to5":"0.11.1-16","ast-types":"~0.6.1",chokidar:"0.11.1",commander:"2.5.0","core-js":"0.4.4",estraverse:"1.8.0",esutils:"1.1.6",esvalid:"1.1.0","fs-readdir-recursive":"0.1.0",jshint:"2.5.10",lodash:"2.4.1","output-file-sync":"^1.1.0","private":"0.1.6",regenerator:"0.8.3",regexpu:"0.3.0",roadrunner:"1.0.4","source-map":"0.1.40","source-map-support":"0.2.8"},devDependencies:{browserify:"6.3.2",chai:"1.9.2",istanbul:"0.3.2","jshint-stylish":"1.0.0",matcha:"0.6.0",mocha:"1.21.4",rimraf:"2.2.8","uglify-js":"2.4.15"},optionalDependencies:{kexec:"0.2.0"}}},{}],189:[function(t,e,r){e.exports={"abstract-expression-call":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceGet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-delete":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceDelete"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-get":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceGet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-set":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceSet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"},{type:"Identifier",name:"VALUE"}]}}]},"apply-constructor":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"Constructor"},{type:"Identifier",name:"args"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"instance"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"create"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"prototype"},computed:false}]}}],kind:"var"},{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"result"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"Identifier",name:"instance"},{type:"Identifier",name:"args"}]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"Identifier",name:"result"},operator:"!=",right:{type:"Literal",value:null}},operator:"&&",right:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"result"}},operator:"==",right:{type:"Literal",value:"object"}},operator:"||",right:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"result"}},operator:"==",right:{type:"Literal",value:"function"}}}},consequent:{type:"Identifier",name:"result"},alternate:{type:"Identifier",name:"instance"}}}]},expression:false}}]},"array-comprehension-container":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"KEY"},init:{type:"ArrayExpression",elements:[]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false},arguments:[]}}]},"array-comprehension-for-each":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"forEach"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[]},expression:false}]}}]},"array-from":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"from"},computed:false},arguments:[{type:"Identifier",name:"VALUE"}]}}]},"array-push":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"KEY"},property:{type:"Identifier",name:"push"},computed:false},arguments:[{type:"Identifier",name:"STATEMENT"}]}}]},"async-to-generator":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"fn"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"gen"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"fn"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"ThisExpression"},{type:"Identifier",name:"arguments"}]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"NewExpression",callee:{type:"Identifier",name:"Promise"},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"resolve"},{type:"Identifier",name:"reject"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"FunctionDeclaration",id:{type:"Identifier",name:"step"},params:[{type:"Identifier",name:"getNext"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"next"},init:null}],kind:"var"},{type:"TryStatement",block:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"next"},right:{type:"CallExpression",callee:{type:"Identifier",name:"getNext"},arguments:[]}}}]},handler:{type:"CatchClause",param:{type:"Identifier",name:"e"},guard:null,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"reject"},arguments:[{type:"Identifier",name:"e"}]}},{type:"ReturnStatement",argument:null}]}},guardedHandlers:[],finalizer:null},{type:"IfStatement",test:{type:"MemberExpression",object:{type:"Identifier",name:"next"},property:{type:"Identifier",name:"done"},computed:false},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"resolve"},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"next"},property:{type:"Identifier",name:"value"},computed:false}]}},{type:"ReturnStatement",argument:null}]},alternate:null},{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Promise"},property:{type:"Identifier",name:"resolve"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"next"},property:{type:"Identifier",name:"value"},computed:false}]},property:{type:"Identifier",name:"then"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"v"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"step"},arguments:[{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"gen"},property:{type:"Identifier",name:"next"},computed:false},arguments:[{type:"Identifier",name:"v"}]}}]},expression:false}]}}]},expression:false},{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"e"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"step"},arguments:[{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"gen"},property:{type:"Literal",value:"throw"},computed:true},arguments:[{type:"Identifier",name:"e"}]}}]},expression:false}]}}]},expression:false}]}}]},expression:false},{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"step"},arguments:[{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"gen"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}}]},expression:false}]}}]},expression:false}]}}]},expression:false}}]},expression:false}}]},bind:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Function"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"bind"},computed:false}}]},call:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"CONTEXT"}]}}]},"class-super-constructor-call-loose":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"Identifier",name:"SUPER_NAME"},operator:"!=",right:{type:"Literal",value:null}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"SUPER_NAME"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"ThisExpression"},{type:"Identifier",name:"arguments"}]}}]},alternate:null}]},"class-super-constructor-call":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"getPrototypeOf"},computed:false},arguments:[{type:"Identifier",name:"CLASS_NAME"}]},operator:"!==",right:{type:"Literal",value:null}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"getPrototypeOf"},computed:false},arguments:[{type:"Identifier",name:"CLASS_NAME"}]},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"ThisExpression"},{type:"Identifier",name:"arguments"}]}}]},alternate:null}]},"common-export-default-assign":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"module"},property:{type:"Identifier",name:"exports"},computed:false},right:{type:"CallExpression",callee:{type:"Identifier",name:"EXTENDS_HELPER"},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Literal",value:"default"},computed:true},{type:"Identifier",name:"exports"}]}}}]},"corejs-iterator":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"CORE_ID"},property:{type:"Identifier",name:"$for"},computed:false},property:{type:"Identifier",name:"getIterator"},computed:false},arguments:[{type:"Identifier",name:"VALUE"}]}}]},"default-parameter":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"ConditionalExpression",test:{type:"BinaryExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"ARGUMENTS"},property:{type:"Identifier",name:"ARGUMENT_KEY"},computed:true},operator:"===",right:{type:"Identifier",name:"undefined"}},consequent:{type:"Identifier",name:"DEFAULT_VALUE"},alternate:{type:"MemberExpression",object:{type:"Identifier",name:"ARGUMENTS"},property:{type:"Identifier",name:"ARGUMENT_KEY"},computed:true}}}],kind:"var"}]},defaults:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"defaults"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"key"},init:null}],kind:"var"},right:{type:"Identifier",name:"defaults"},body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"key"},computed:true},operator:"===",right:{type:"Identifier",name:"undefined"}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"key"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"defaults"},property:{type:"Identifier",name:"key"},computed:true}}}]},alternate:null}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"obj"}}]},expression:false}}]},"define-property":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"key"},{type:"Identifier",name:"value"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperty"},computed:false},arguments:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"key"},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"value"},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"enumerable"},value:{type:"Literal",value:true},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"configurable"},value:{type:"Literal",value:true},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"writable"},value:{type:"Literal",value:true},kind:"init"}]}]}}]},expression:false}}]},"exports-assign":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"KEY"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-default-module-override":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"exports"},right:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"module"},property:{type:"Identifier",name:"exports"},computed:false},right:{type:"Identifier",name:"VALUE"}}}}]},"exports-default-module":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"module"},property:{type:"Identifier",name:"exports"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"extends":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"target"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:{type:"Literal",value:1}}],kind:"var"},test:{type:"BinaryExpression",left:{type:"Identifier",name:"i"},operator:"<",right:{type:"MemberExpression",object:{type:"Identifier",name:"arguments"},property:{type:"Identifier",name:"length"},computed:false}},update:{type:"UpdateExpression",operator:"++",prefix:false,argument:{type:"Identifier",name:"i"}},body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"source"},init:{type:"MemberExpression",object:{type:"Identifier",name:"arguments"},property:{type:"Identifier",name:"i"},computed:true}}],kind:"var"},{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"key"},init:null}],kind:"var"},right:{type:"Identifier",name:"source"},body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"target"},property:{type:"Identifier",name:"key"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"source"},property:{type:"Identifier",name:"key"},computed:true}}}]}}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"target"}}]},expression:false}}]},"for-of-loose":{type:"Program",body:[{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"LOOP_OBJECT"},init:{type:"Identifier",name:"OBJECT"}},{type:"VariableDeclarator",id:{type:"Identifier",name:"IS_ARRAY"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"isArray"},computed:false},arguments:[{type:"Identifier",name:"LOOP_OBJECT"}]}},{type:"VariableDeclarator",id:{type:"Identifier",name:"INDEX"},init:{type:"Literal",value:0}},{type:"VariableDeclarator",id:{type:"Identifier",name:"LOOP_OBJECT"},init:{type:"ConditionalExpression",test:{type:"Identifier",name:"IS_ARRAY"},consequent:{type:"Identifier",name:"LOOP_OBJECT"},alternate:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"LOOP_OBJECT"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"iterator"},computed:false},computed:true},arguments:[]}}}],kind:"var"},test:null,update:null,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"Identifier",name:"IS_ARRAY"},consequent:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"Identifier",name:"INDEX"},operator:">=",right:{type:"MemberExpression",object:{type:"Identifier",name:"LOOP_OBJECT"},property:{type:"Identifier",name:"length"},computed:false}},consequent:{type:"BreakStatement",label:null},alternate:null},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"ID"},right:{type:"MemberExpression",object:{type:"Identifier",name:"LOOP_OBJECT"},property:{type:"UpdateExpression",operator:"++",prefix:false,argument:{type:"Identifier",name:"INDEX"}},computed:true}}}]},alternate:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"INDEX"},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"LOOP_OBJECT"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}}},{type:"IfStatement",test:{type:"MemberExpression",object:{type:"Identifier",name:"INDEX"},property:{type:"Identifier",name:"done"},computed:false},consequent:{type:"BreakStatement",label:null},alternate:null},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"ID"},right:{type:"MemberExpression",object:{type:"Identifier",name:"INDEX"},property:{type:"Identifier",name:"value"},computed:false}}}]}}]}}]},"for-of":{type:"Program",body:[{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"ITERATOR_KEY"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"iterator"},computed:false},computed:true},arguments:[]}},{type:"VariableDeclarator",id:{type:"Identifier",name:"STEP_KEY"},init:null}],kind:"var"},test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"MemberExpression",object:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"STEP_KEY"},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ITERATOR_KEY"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}},property:{type:"Identifier",name:"done"},computed:false}},update:null,body:{type:"BlockStatement",body:[]}}]},get:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:{type:"Identifier",name:"get"},params:[{type:"Identifier",name:"object"},{type:"Identifier",name:"property"},{type:"Identifier",name:"receiver"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"desc"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"getOwnPropertyDescriptor"},computed:false},arguments:[{type:"Identifier",name:"object"},{type:"Identifier",name:"property"}]}}],kind:"var"},{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"Identifier",name:"desc"},operator:"===",right:{type:"Identifier",name:"undefined"}},consequent:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"parent"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"getPrototypeOf"},computed:false},arguments:[{type:"Identifier",name:"object"}]}}],kind:"var"},{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"Identifier",name:"parent"},operator:"===",right:{type:"Literal",value:null}},consequent:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"undefined"}}]},alternate:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"Identifier",name:"get"},arguments:[{type:"Identifier",name:"parent"},{type:"Identifier",name:"property"},{type:"Identifier",name:"receiver"}]}}]}}]},alternate:{type:"IfStatement",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"Literal",value:"value"},operator:"in",right:{type:"Identifier",name:"desc"}},operator:"&&",right:{type:"MemberExpression",object:{type:"Identifier",name:"desc"},property:{type:"Identifier",name:"writable"},computed:false}},consequent:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"MemberExpression",object:{type:"Identifier",name:"desc"},property:{type:"Identifier",name:"value"},computed:false}}]},alternate:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"getter"},init:{type:"MemberExpression",object:{type:"Identifier",name:"desc"},property:{type:"Identifier",name:"get"},computed:false}}],kind:"var"},{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"Identifier",name:"getter"},operator:"===",right:{type:"Identifier",name:"undefined"}},consequent:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"undefined"}}]},alternate:null},{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"getter"},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"receiver"}]}}]}}}]},expression:false}}]},"has-own":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"hasOwnProperty"},computed:false}}]},inherits:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"subClass"},{type:"Identifier",name:"superClass"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"superClass"}},operator:"!==",right:{type:"Literal",value:"function"}},operator:"&&",right:{type:"BinaryExpression",left:{type:"Identifier",name:"superClass"},operator:"!==",right:{type:"Literal",value:null}}},consequent:{type:"BlockStatement",body:[{type:"ThrowStatement",argument:{type:"NewExpression",callee:{type:"Identifier",name:"TypeError"},arguments:[{type:"BinaryExpression",left:{type:"Literal",value:"Super expression must either be null or a function, not "},operator:"+",right:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"superClass"}}}]}}]},alternate:null},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"subClass"},property:{type:"Identifier",name:"prototype"},computed:false},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"create"},computed:false},arguments:[{type:"LogicalExpression",left:{type:"Identifier",name:"superClass"},operator:"&&",right:{type:"MemberExpression",object:{type:"Identifier",name:"superClass"},property:{type:"Identifier",name:"prototype"},computed:false}},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"constructor"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"subClass"},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"enumerable"},value:{type:"Literal",value:false},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"writable"},value:{type:"Literal",value:true},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"configurable"},value:{type:"Literal",value:true},kind:"init"}]},kind:"init"}]}]}}},{type:"IfStatement",test:{type:"Identifier",name:"superClass"},consequent:{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"subClass"},property:{type:"Identifier",name:"__proto__"},computed:false},right:{type:"Identifier",name:"superClass"}}},alternate:null}]},expression:false}}]},"interop-require-wildcard":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"LogicalExpression",left:{type:"Identifier",name:"obj"},operator:"&&",right:{type:"BinaryExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"constructor"},computed:false},operator:"===",right:{type:"Identifier",name:"Object"}}},consequent:{type:"Identifier",name:"obj"},alternate:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"default"},value:{type:"Identifier",name:"obj"},kind:"init"}]}}}]},expression:false}}]},"interop-require":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"LogicalExpression",left:{type:"Identifier",name:"obj"},operator:"&&",right:{type:"LogicalExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Literal",value:"default"},computed:true},operator:"||",right:{type:"Identifier",name:"obj"}}}}]},expression:false}}]},"let-scoping-return":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"RETURN"}},operator:"===",right:{type:"Literal",value:"object"}},consequent:{type:"ReturnStatement",argument:{type:"MemberExpression",object:{type:"Identifier",name:"RETURN"},property:{type:"Identifier",name:"v"},computed:false}},alternate:null}]},"object-without-properties":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"keys"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"target"},init:{type:"ObjectExpression",properties:[]}}],kind:"var"},{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:null}],kind:"var"},right:{type:"Identifier",name:"obj"},body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"keys"},property:{type:"Identifier",name:"indexOf"},computed:false},arguments:[{type:"Identifier",name:"i"}]},operator:">=",right:{type:"Literal",value:0}},consequent:{type:"ContinueStatement",label:null},alternate:null},{type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"hasOwnProperty"},computed:false},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"i"}]}},consequent:{type:"ContinueStatement",label:null},alternate:null},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"target"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"i"},computed:true}}}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"target"}}]},expression:false}}]},"property-method-assignment-wrapper":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"FUNCTION_KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"WRAPPER_KEY"},init:{type:"FunctionExpression",id:{type:"Identifier",name:"FUNCTION_ID"},params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"FUNCTION_KEY"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"ThisExpression"},{type:"Identifier",name:"arguments"}]}}]},expression:false}}],kind:"var"},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"WRAPPER_KEY"},property:{type:"Identifier",name:"toString"},computed:false},right:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"FUNCTION_KEY"},property:{type:"Identifier",name:"toString"},computed:false},arguments:[]}}]},expression:false}}},{type:"ReturnStatement",argument:{type:"Identifier",name:"WRAPPER_KEY"}}]},expression:false},arguments:[{type:"Identifier",name:"FUNCTION"}]}}]},"prototype-identifier":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"Identifier",name:"CLASS_NAME"},property:{type:"Identifier",name:"prototype"},computed:false}}]},"prototype-properties":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"},{type:"Identifier",name:"instanceProps"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"Identifier",name:"staticProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"}]}},alternate:null},{type:"IfStatement",test:{type:"Identifier",name:"instanceProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"prototype"},computed:false},{type:"Identifier",name:"instanceProps"}]}},alternate:null}]},expression:false}}]},"require-assign-key":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]},property:{type:"Identifier",name:"KEY"},computed:false}}],kind:"var"}]},require:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]}}]},rest:{type:"Program",body:[{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"LEN"},init:{type:"MemberExpression",object:{type:"Identifier",name:"ARGUMENTS"},property:{type:"Identifier",name:"length"},computed:false}},{type:"VariableDeclarator",id:{type:"Identifier",name:"ARRAY"},init:{type:"CallExpression",callee:{type:"Identifier",name:"Array"},arguments:[{type:"Identifier",name:"ARRAY_LEN"}]}},{type:"VariableDeclarator",id:{type:"Identifier",name:"KEY"},init:{type:"Identifier",name:"START"}}],kind:"var"},test:{type:"BinaryExpression",left:{type:"Identifier",name:"KEY"},operator:"<",right:{type:"Identifier",name:"LEN"}},update:{type:"UpdateExpression",operator:"++",prefix:false,argument:{type:"Identifier",name:"KEY"}},body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"ARRAY_KEY"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"ARGUMENTS"},property:{type:"Identifier",name:"KEY"},computed:true}}}]}}]},"self-global":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ConditionalExpression",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"global"}},operator:"===",right:{type:"Literal",value:"undefined"}},consequent:{type:"Identifier",name:"self"},alternate:{type:"Identifier",name:"global"}}}]},slice:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"slice"},computed:false}}]},"sliced-to-array":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"arr"},{type:"Identifier",name:"i"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"isArray"},computed:false},arguments:[{type:"Identifier",name:"arr"}]},consequent:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"arr"}}]},alternate:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"_arr"},init:{type:"ArrayExpression",elements:[]}}],kind:"var"},{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"_iterator"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"arr"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"iterator"},computed:false},computed:true},arguments:[]}},{type:"VariableDeclarator",id:{type:"Identifier",name:"_step"},init:null}],kind:"var"},test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"MemberExpression",object:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"_step"},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"_iterator"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}},property:{type:"Identifier",name:"done"},computed:false}},update:null,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"_arr"},property:{type:"Identifier",name:"push"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"_step"},property:{type:"Identifier",name:"value"},computed:false}]}},{type:"IfStatement",test:{type:"LogicalExpression",left:{type:"Identifier",name:"i"},operator:"&&",right:{type:"BinaryExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"_arr"},property:{type:"Identifier",name:"length"},computed:false},operator:"===",right:{type:"Identifier",name:"i"}}},consequent:{type:"BreakStatement",label:null},alternate:null}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"_arr"}}]}}]},expression:false}}]},system:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"System"},property:{type:"Identifier",name:"register"},computed:false},arguments:[{type:"Identifier",name:"MODULE_NAME"},{type:"Identifier",name:"MODULE_DEPENDENCIES"},{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"EXPORT_IDENTIFIER"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"setters"},value:{type:"Identifier",name:"SETTERS"},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"execute"},value:{type:"Identifier",name:"EXECUTE"},kind:"init"}]}}]},expression:false}]}}]},"tagged-template-literal-loose":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"strings"},{type:"Identifier",name:"raw"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"strings"},property:{type:"Identifier",name:"raw"},computed:false},right:{type:"Identifier",name:"raw"}}},{type:"ReturnStatement",argument:{type:"Identifier",name:"strings"}}]},expression:false}}]},"tagged-template-literal":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"strings"},{type:"Identifier",name:"raw"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"freeze"},computed:false},arguments:[{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"strings"},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"raw"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"freeze"},computed:false},arguments:[{type:"Identifier",name:"raw"}]},kind:"init"}]},kind:"init"}]}]}]}}]},expression:false}}]},"test-exports":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"exports"}},operator:"!==",right:{type:"Literal",value:"undefined"}}}]},"test-module":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"module"}},operator:"!==",right:{type:"Literal",value:"undefined"}}}]},"to-array":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"arr"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"isArray"},computed:false},arguments:[{type:"Identifier",name:"arr"}]},consequent:{type:"Identifier",name:"arr"},alternate:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"from"},computed:false},arguments:[{type:"Identifier",name:"arr"}]}}}]},expression:false}}]},"typeof":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"LogicalExpression",left:{type:"Identifier",name:"obj"},operator:"&&",right:{type:"BinaryExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"constructor"},computed:false},operator:"===",right:{type:"Identifier",name:"Symbol"}}},consequent:{type:"Literal",value:"symbol"},alternate:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"obj"}}}}]},expression:false}}]},"umd-runner-body":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"factory"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"define"}},operator:"===",right:{type:"Literal",value:"function"}},operator:"&&",right:{type:"MemberExpression",object:{type:"Identifier",name:"define"},property:{type:"Identifier",name:"amd"},computed:false}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"define"},arguments:[{type:"Identifier",name:"AMD_ARGUMENTS"},{type:"Identifier",name:"factory"}]}}]},alternate:{type:"IfStatement",test:{type:"Identifier",name:"COMMON_TEST"},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"factory"},arguments:[{type:"Identifier",name:"COMMON_ARGUMENTS"}]}}]},alternate:null}}]},expression:false}}]}}
},{}]},{},[2])(2)}); |
test/components/DummySpec.js | paulmusso/webpack-boilerplate | import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Dummy from '../../src/components/Dummy';
describe("A dummy component", () => {
beforeEach(function(){
this.TestUtils = TestUtils;
this.component = TestUtils.renderIntoDocument(<Dummy/>);
});
it("starts with a div", function(){
let root = ReactDOM.findDOMNode(this.component);
expect(root.tagName).toEqual('DIV');
})
}) |
client/src/components/profile/components/HeatMap.js | BhaveshSGupta/FreeCodeCamp | import React from 'react';
import PropTypes from 'prop-types';
import CalendarHeatMap from 'react-calendar-heatmap';
import ReactTooltip from 'react-tooltip';
import addDays from 'date-fns/add_days';
import addMonths from 'date-fns/add_months';
import startOfDay from 'date-fns/start_of_day';
import format from 'date-fns/format';
import FullWidthRow from '../../helpers/FullWidthRow';
import Spacer from '../../helpers/Spacer';
import 'react-calendar-heatmap/dist/styles.css';
import './heatmap.css';
const propTypes = {
calendar: PropTypes.object,
streak: PropTypes.shape({
current: PropTypes.number,
longest: PropTypes.number
})
};
function HeatMap({ calendar, streak }) {
const startOfToday = startOfDay(Date.now());
const sixMonthsAgo = addMonths(startOfToday, -6);
const startOfCalendar = format(addDays(sixMonthsAgo, -1), 'YYYY-MM-DD');
const endOfCalendar = format(startOfToday, 'YYYY-MM-DD');
let calendarData = {};
let dayCounter = sixMonthsAgo;
while (dayCounter <= startOfToday) {
calendarData[format(dayCounter, 'YYYY-MM-DD')] = 0;
dayCounter = addDays(dayCounter, 1);
}
for (let timestamp in calendar) {
if (calendar.hasOwnProperty(timestamp)) {
timestamp = Number(timestamp * 1000) || null;
if (timestamp) {
const startOfTimestampDay = format(startOfDay(timestamp), 'YYYY-MM-DD');
calendarData[startOfTimestampDay] =
calendarData[startOfTimestampDay] + 1 || 1;
}
}
}
const calendarValues = Object.keys(calendarData).map(key => ({
date: key,
count: calendarData[key]
}));
return (
<FullWidthRow>
<FullWidthRow>
<CalendarHeatMap
classForValue={value => {
if (!value || value.count < 1) return 'color-empty';
if (value.count < 4) return 'color-scale-1';
if (value.count < 8) return 'color-scale-2';
if (value.count >= 8) return 'color-scale-a-lot';
return 'color-empty';
}}
endDate={endOfCalendar}
startDate={startOfCalendar}
tooltipDataAttrs={value => {
let valueCount;
if (value && value.count === 1) {
valueCount = '1 point';
} else if (value && value.count > 1) {
valueCount = `${value.count} points`;
} else {
valueCount = 'No points';
}
return {
'data-tip': `<b>${valueCount}</b> on ${new Date(
value.date
).toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
})}`
};
}}
values={calendarValues}
/>
<ReactTooltip className='react-tooltip' effect='solid' html={true} />
</FullWidthRow>
<Spacer />
<FullWidthRow>
<div className='streak-container'>
<span className='streak'>
<b>Longest Streak:</b> {streak.longest || 0}
</span>
<span className='streak'>
<b>Current Streak:</b> {streak.current || 0}
</span>
</div>
</FullWidthRow>
<Spacer />
<hr />
</FullWidthRow>
);
}
HeatMap.displayName = 'HeatMap';
HeatMap.propTypes = propTypes;
export default HeatMap;
|
client/js/components/Login.js | micahp0506/jeeps | 'use strict';
import React from 'react';
import LoginStore from '../stores/LoginStore';
import LoginActions from '../actions/LoginActions';
import {Route, Router, browserHistory, Link} from 'react-router';
// Creating Login to handle actions and store
class Login extends React.Component {
constructor(props) {
super(props);
this.state = LoginStore.getState();
this.onChange = this.onChange.bind(this);
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this)
}
// Listening to changes at the store
componentDidMount() {
LoginStore.listen(this.onChange);
}
// Unlistening to changes at the store
componentWillUnmount() {
LoginStore.unlisten(this.onChange);
}
// Handling the email value change
handleEmailChange() {
this.setState({email: this.refs.email.value});
}
// Handling the password value change
handlePasswordChange() {
this.setState({password: this.refs.password.value});
}
// When change occurs handle state
onChange(state) {
this.setState(state);
if (this.state.loginState) {
this.props.history.push('/');
// console.log("this.props", this.props);
}
}
// Handling submit on users info
handleSubmit(event) {
event.preventDefault();
// Email and Password provided by user
let email = this.state.email;
let password = this.state.password;
// Handling the login of a user
if (!email) {
toastr.error('Please enter an email address.')
LoginActions.noEmail();
this.refs.nameTextField.getDOMNode().focus();
} else if (!password) {
toastr.error('Please enter a password.')
LoginActions.noPassword();
} else if (email && password) {
LoginActions.loginUser(email, password);
}
}
render() {
return (
<div className="login-container">
<form className="form-signin">
<h2 className="form-signin-heading header">ACCOUNT LOGIN</h2>
<label className="sr-only">Email address</label>
<input type="email" id="inputEmail" ref="email" className="form-control" placeholder="Email address" required autofocus value={this.state.email} onChange={this.handleEmailChange}></input>
<label className="sr-only">Password</label>
<input type="password" id="inputPassword" ref="password" className="form-control" placeholder="Password" required value={this.state.password} onChange={this.handlePasswordChange}></input>
<div className="ui message">New to us? <Link to={'/register'}>Sign Up</Link></div>
<button className="btn btn-lg btn-primary btn-block" onClick={this.handleSubmit} type="submit">Sign in</button>
</form>
</div>
)
}
}
export default Login;
|
src/botPage/view/Dialogs/LoadDialog.js | binary-com/binary-bot | import PropTypes from 'prop-types';
import React from 'react';
import Dialog from './Dialog';
import { SAVE_LOAD_TYPE, useIsMounted } from './utils';
import LoadingButton from './LoadingButton';
import * as style from '../style';
import { translate } from '../../../common/i18n';
import googleDriveUtil from '../../../common/integrations/GoogleDrive';
import { observer as globalObserver } from '../../../common/utils/observer';
const Load = React.memo(({ closeDialog }) => {
const [loadType, setLoadType] = React.useState(SAVE_LOAD_TYPE.local);
const [isLoading, setLoading] = React.useState(false);
const [isGdLoggedIn, setGdLoggedIn] = React.useState(false);
const isMounted = useIsMounted();
React.useEffect(() => {
globalObserver.register('googledrive.authorised', data => setGdLoggedIn(data));
}, []);
const onChange = e => setLoadType(e.target.value);
const onSubmit = e => {
e.preventDefault();
if (loadType === SAVE_LOAD_TYPE.google_drive) {
setLoading(true);
googleDriveUtil
.createFilePicker()
.then(() => closeDialog())
.finally(() => isMounted() && setLoading(false));
} else {
document.getElementById('files').click();
closeDialog();
}
};
return (
<form id="load-dialog" className="dialog-content" style={style.content} onSubmit={onSubmit}>
<div className="center-text input-row">
<span className="integration-option">
<input
type="radio"
id="load-local"
name="load-option"
value={SAVE_LOAD_TYPE.local}
defaultChecked
onChange={onChange}
/>
<label htmlFor="load-local">{translate('My computer')}</label>
</span>
{isGdLoggedIn && (
<span className="integration-option">
<input
type="radio"
id="load-google-drive"
name="load-option"
value={SAVE_LOAD_TYPE.google_drive}
onChange={onChange}
/>
<label htmlFor="load-google-drive">Google Drive</label>
</span>
)}
</div>
<div className="center-text input-row last">
<button id="load-strategy" type="submit" disabled={isLoading}>
{isLoading ? <LoadingButton /> : translate('Load')}
</button>
</div>
</form>
);
});
Load.propTypes = {
closeDialog: PropTypes.func.isRequired,
};
export default class LoadDialog extends Dialog {
constructor() {
const closeDialog = () => {
this.close();
};
super('load-dialog', translate('Load blocks'), <Load closeDialog={closeDialog} />, style.dialogLayout);
this.registerCloseOnOtherDialog();
}
}
|
ajax/libs/jquery.fancytree/2.8.0/jquery.fancytree.min.js | melvinsembrano/cdnjs | /*!
* jquery.fancytree.js
* Dynamic tree view control, with support for lazy loading of branches.
* https://github.com/mar10/fancytree/
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.0
* @date 2015-02-08T17:56
*/
!function(a,b,c,d){"use strict";function e(b,c){b||(c=c?": "+c:"",a.error("Fancytree assertion failed"+c))}function f(a,c){var d,e,f=b.console?b.console[a]:null;if(f)try{f.apply(b.console,c)}catch(g){for(e="",d=0;d<c.length;d++)e+=c[d];f(e)}}function g(a){return!(!a.tree||a.statusNodeType===d)}function h(b){var c,d,e,f=a.map(a.trim(b).split("."),function(a){return parseInt(a,10)}),g=a.map(Array.prototype.slice.call(arguments,1),function(a){return parseInt(a,10)});for(c=0;c<g.length;c++)if(d=f[c]||0,e=g[c]||0,d!==e)return d>e;return!0}function i(a,b,c,d,e){var f=function(){var c=b[a],f=d[a],g=b.ext[e],h=function(){return c.apply(b,arguments)},i=function(a){return c.apply(b,a)};return function(){var a=b._local,c=b._super,d=b._superApply;try{return b._local=g,b._super=h,b._superApply=i,f.apply(b,arguments)}finally{b._local=a,b._super=c,b._superApply=d}}}();return f}function j(b,c,d,e){for(var f in d)"function"==typeof d[f]?"function"==typeof b[f]?b[f]=i(f,b,c,d,e):"_"===f.charAt(0)?b.ext[e][f]=i(f,b,c,d,e):a.error("Could not override tree."+f+". Use prefix '_' to create tree."+e+"._"+f):"options"!==f&&(b.ext[e][f]=d[f])}function k(b,c){return b===d?a.Deferred(function(){this.resolve()}).promise():a.Deferred(function(){this.resolveWith(b,c)}).promise()}function l(b,c){return b===d?a.Deferred(function(){this.reject()}).promise():a.Deferred(function(){this.rejectWith(b,c)}).promise()}function m(a,b){return function(){a.resolveWith(b)}}function n(b){var c=a.extend({},b.data()),d=c.json;return delete c.fancytree,d&&(delete c.json,c=a.extend(c,d)),c}function o(a){return a=a.toLowerCase(),function(b){return b.title.toLowerCase().indexOf(a)>=0}}function p(a){var b=new RegExp("^"+a,"i");return function(a){return b.test(a.title)}}function q(b,c){var d,f,g,h;for(this.parent=b,this.tree=b.tree,this.ul=null,this.li=null,this.statusNodeType=null,this._isLoading=!1,this._error=null,this.data={},d=0,f=A.length;f>d;d++)g=A[d],this[g]=c[g];c.data&&a.extend(this.data,c.data);for(g in c)B[g]||a.isFunction(c[g])||C[g]||(this.data[g]=c[g]);null==this.key?this.tree.options.defaultKey?(this.key=this.tree.options.defaultKey(this),e(this.key,"defaultKey() must return a unique key")):this.key="_"+t._nextNodeKey++:this.key=""+this.key,c.active&&(e(null===this.tree.activeNode,"only one active node allowed"),this.tree.activeNode=this),c.selected&&(this.tree.lastSelectedNode=this),this.children=null,h=c.children,h&&h.length&&this._setChildren(h),this.tree._callHook("treeRegisterNode",this.tree,!0,this)}function r(b){this.widget=b,this.$div=b.element,this.options=b.options,this.options&&(a.isFunction(this.options.lazyload)&&!a.isFunction(this.options.lazyLoad)&&(this.options.lazyLoad=function(){return t.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead."),b.options.lazyload.apply(this,arguments)}),a.isFunction(this.options.loaderror)&&a.error("The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead."),this.options.fx!==d&&t.warn("The 'fx' options was replaced by 'toggleEffect' since 2014-11-30.")),this.ext={},this.data=n(this.$div),this._id=a.ui.fancytree._nextId++,this._ns=".fancytree-"+this._id,this.activeNode=null,this.focusNode=null,this._hasFocus=null,this.lastSelectedNode=null,this.systemFocusElement=null,this.lastQuicksearchTerm="",this.lastQuicksearchTime=0,this.statusClassPropName="span",this.ariaPropName="li",this.nodeContainerAttrName="li",this.$div.find(">ul.fancytree-container").remove();var c,e={tree:this};this.rootNode=new q(e,{title:"root",key:"root_"+this._id,children:null,expanded:!0}),this.rootNode.parent=null,c=a("<ul>",{"class":"ui-fancytree fancytree-container"}).appendTo(this.$div),this.$container=c,this.rootNode.ul=c[0],null==this.options.debugLevel&&(this.options.debugLevel=t.debugLevel),this.$container.attr("tabindex",this.options.tabbable?"0":"-1"),this.options.aria&&this.$container.attr("role","tree").attr("aria-multiselectable",!0)}if(a.ui&&a.ui.fancytree)return void a.ui.fancytree.warn("Fancytree: ignored duplicate include");e(a.ui,"Fancytree requires jQuery UI (http://jqueryui.com)");var s,t=null,u={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},v={16:!0,17:!0,18:!0},w={8:"backspace",9:"tab",10:"return",13:"return",19:"pause",20:"capslock",27:"esc",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",45:"insert",46:"del",59:";",61:"=",96:"0",97:"1",98:"2",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9",106:"*",107:"+",109:"-",110:".",111:"/",112:"f1",113:"f2",114:"f3",115:"f4",116:"f5",117:"f6",118:"f7",119:"f8",120:"f9",121:"f10",122:"f11",123:"f12",144:"numlock",145:"scroll",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},x={0:"",1:"left",2:"middle",3:"right"},y="active expanded focus folder hideCheckbox lazy selected unselectable".split(" "),z={},A="expanded extraClasses folder hideCheckbox key lazy refKey selected title tooltip unselectable".split(" "),B={},C={active:!0,children:!0,data:!0,focus:!0};for(s=0;s<y.length;s++)z[y[s]]=!0;for(s=0;s<A.length;s++)B[A[s]]=!0;q.prototype={_findDirectChild:function(a){var b,c,d=this.children;if(d)if("string"==typeof a){for(b=0,c=d.length;c>b;b++)if(d[b].key===a)return d[b]}else{if("number"==typeof a)return this.children[a];if(a.parent===this)return a}return null},_setChildren:function(a){e(a&&(!this.children||0===this.children.length),"only init supported"),this.children=[];for(var b=0,c=a.length;c>b;b++)this.children.push(new q(this,a[b]))},addChildren:function(b,c){var d,f,g,h=null,i=[];for(a.isPlainObject(b)&&(b=[b]),this.children||(this.children=[]),d=0,f=b.length;f>d;d++)i.push(new q(this,b[d]));return h=i[0],null==c?this.children=this.children.concat(i):(c=this._findDirectChild(c),g=a.inArray(c,this.children),e(g>=0,"insertBefore must be an existing child"),this.children.splice.apply(this.children,[g,0].concat(i))),(!this.parent||this.parent.ul||this.tr)&&this.render(),3===this.tree.options.selectMode&&this.fixSelection3FromEndNodes(),h},addNode:function(a,b){switch((b===d||"over"===b)&&(b="child"),b){case"after":return this.getParent().addChildren(a,this.getNextSibling());case"before":return this.getParent().addChildren(a,this);case"firstChild":var c=this.children?this.children[0]:null;return this.addChildren(a,c);case"child":case"over":return this.addChildren(a)}e(!1,"Invalid mode: "+b)},appendSibling:function(a){return this.addNode(a,"after")},applyPatch:function(b){if(null===b)return this.remove(),k(this);var c,d,e,f={children:!0,expanded:!0,parent:!0};for(c in b)e=b[c],f[c]||a.isFunction(e)||(B[c]?this[c]=e:this.data[c]=e);return b.hasOwnProperty("children")&&(this.removeChildren(),b.children&&this._setChildren(b.children)),this.isVisible()&&(this.renderTitle(),this.renderStatus()),d=b.hasOwnProperty("expanded")?this.setExpanded(b.expanded):k(this)},collapseSiblings:function(){return this.tree._callHook("nodeCollapseSiblings",this)},copyTo:function(a,b,c){return a.addNode(this.toDict(!0,c),b)},countChildren:function(a){var b,c,d,e=this.children;if(!e)return 0;if(d=e.length,a!==!1)for(b=0,c=d;c>b;b++)d+=e[b].countChildren();return d},debug:function(){this.tree.options.debugLevel>=2&&(Array.prototype.unshift.call(arguments,this.toString()),f("log",arguments))},discard:function(){return this.warn("FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead."),this.resetLazy()},findAll:function(b){b=a.isFunction(b)?b:o(b);var c=[];return this.visit(function(a){b(a)&&c.push(a)}),c},findFirst:function(b){b=a.isFunction(b)?b:o(b);var c=null;return this.visit(function(a){return b(a)?(c=a,!1):void 0}),c},_changeSelectStatusAttrs:function(a){var b=!1;switch(a){case!1:b=this.selected||this.partsel,this.selected=!1,this.partsel=!1;break;case!0:b=!this.selected||!this.partsel,this.selected=!0,this.partsel=!0;break;case d:b=this.selected||!this.partsel,this.selected=!1,this.partsel=!0;break;default:e(!1,"invalid state: "+a)}return b&&this.renderStatus(),b},fixSelection3AfterClick:function(){var a=this.isSelected();this.visit(function(b){b._changeSelectStatusAttrs(a)}),this.fixSelection3FromEndNodes()},fixSelection3FromEndNodes:function(){function a(b){var c,e,f,g,h,i,j,k=b.children;if(k&&k.length){for(i=!0,j=!1,c=0,e=k.length;e>c;c++)f=k[c],g=a(f),g!==!1&&(j=!0),g!==!0&&(i=!1);h=i?!0:j?d:!1}else h=!!b.selected;return b._changeSelectStatusAttrs(h),h}e(3===this.tree.options.selectMode,"expected selectMode 3"),a(this),this.visitParents(function(a){var b,c,e,f,g=a.children,h=!0,i=!1;for(b=0,c=g.length;c>b;b++)e=g[b],(e.selected||e.partsel)&&(i=!0),e.unselectable||e.selected||(h=!1);f=h?!0:i?d:!1,a._changeSelectStatusAttrs(f)})},fromDict:function(b){for(var c in b)B[c]?this[c]=b[c]:"data"===c?a.extend(this.data,b.data):a.isFunction(b[c])||C[c]||(this.data[c]=b[c]);b.children&&(this.removeChildren(),this.addChildren(b.children)),this.renderTitle()},getChildren:function(){return this.hasChildren()===d?d:this.children},getFirstChild:function(){return this.children?this.children[0]:null},getIndex:function(){return a.inArray(this,this.parent.children)},getIndexHier:function(b){b=b||".";var c=[];return a.each(this.getParentList(!1,!0),function(a,b){c.push(b.getIndex()+1)}),c.join(b)},getKeyPath:function(a){var b=[],c=this.tree.options.keyPathSeparator;return this.visitParents(function(a){a.parent&&b.unshift(a.key)},!a),c+b.join(c)},getLastChild:function(){return this.children?this.children[this.children.length-1]:null},getLevel:function(){for(var a=0,b=this.parent;b;)a++,b=b.parent;return a},getNextSibling:function(){if(this.parent){var a,b,c=this.parent.children;for(a=0,b=c.length-1;b>a;a++)if(c[a]===this)return c[a+1]}return null},getParent:function(){return this.parent},getParentList:function(a,b){for(var c=[],d=b?this:this.parent;d;)(a||d.parent)&&c.unshift(d),d=d.parent;return c},getPrevSibling:function(){if(this.parent){var a,b,c=this.parent.children;for(a=1,b=c.length;b>a;a++)if(c[a]===this)return c[a-1]}return null},hasChildren:function(){return this.lazy?null==this.children?d:0===this.children.length?!1:1===this.children.length&&this.children[0].isStatusNode()?d:!0:!(!this.children||!this.children.length)},hasFocus:function(){return this.tree.hasFocus()&&this.tree.focusNode===this},info:function(){this.tree.options.debugLevel>=1&&(Array.prototype.unshift.call(arguments,this.toString()),f("info",arguments))},isActive:function(){return this.tree.activeNode===this},isChildOf:function(a){return this.parent&&this.parent===a},isDescendantOf:function(a){if(!a||a.tree!==this.tree)return!1;for(var b=this.parent;b;){if(b===a)return!0;b=b.parent}return!1},isExpanded:function(){return!!this.expanded},isFirstSibling:function(){var a=this.parent;return!a||a.children[0]===this},isFolder:function(){return!!this.folder},isLastSibling:function(){var a=this.parent;return!a||a.children[a.children.length-1]===this},isLazy:function(){return!!this.lazy},isLoaded:function(){return!this.lazy||this.hasChildren()!==d},isLoading:function(){return!!this._isLoading},isRoot:function(){return this.isRootNode()},isRootNode:function(){return this.tree.rootNode===this},isSelected:function(){return!!this.selected},isStatusNode:function(){return!!this.statusNodeType},isTopLevel:function(){return this.tree.rootNode===this.parent},isUndefined:function(){return this.hasChildren()===d},isVisible:function(){var a,b,c=this.getParentList(!1,!1);for(a=0,b=c.length;b>a;a++)if(!c[a].expanded)return!1;return!0},lazyLoad:function(a){return this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead."),this.load(a)},load:function(a){var b,c,d=this;return e(this.isLazy(),"load() requires a lazy node"),a||this.isUndefined()?(this.isLoaded()&&this.resetLazy(),c=this.tree._triggerNodeEvent("lazyLoad",this),c===!1?k(this):(e("boolean"!=typeof c,"lazyLoad event must return source in data.result"),b=this.tree._callHook("nodeLoadChildren",this,c),this.expanded&&b.always(function(){d.render()}),b)):k(this)},makeVisible:function(b){var c,d=this,e=[],f=new a.Deferred,g=this.getParentList(!1,!1),h=g.length,i=!(b&&b.noAnimation===!0),j=!(b&&b.scrollIntoView===!1);for(c=h-1;c>=0;c--)e.push(g[c].setExpanded(!0,b));return a.when.apply(a,e).done(function(){j?d.scrollIntoView(i).done(function(){f.resolve()}):f.resolve()}),f.promise()},moveTo:function(b,c,f){(c===d||"over"===c)&&(c="child");var g,h=this.parent,i="child"===c?b:b.parent;if(this!==b){if(!this.parent)throw"Cannot move system root";if(i.isDescendantOf(this))throw"Cannot move a node to its own descendant";if(1===this.parent.children.length){if(this.parent===i)return;this.parent.children=this.parent.lazy?[]:null,this.parent.expanded=!1}else g=a.inArray(this,this.parent.children),e(g>=0),this.parent.children.splice(g,1);if(this.parent=i,i.hasChildren())switch(c){case"child":i.children.push(this);break;case"before":g=a.inArray(b,i.children),e(g>=0),i.children.splice(g,0,this);break;case"after":g=a.inArray(b,i.children),e(g>=0),i.children.splice(g+1,0,this);break;default:throw"Invalid mode "+c}else i.children=[this];f&&b.visit(f,!0),this.tree!==b.tree&&(this.warn("Cross-tree moveTo is experimantal!"),this.visit(function(a){a.tree=b.tree},!0)),h.isDescendantOf(i)||h.render(),i.isDescendantOf(h)||i===h||i.render()}},navigate:function(b,c){function d(d){if(d){try{d.makeVisible()}catch(e){}return a(d.span).is(":visible")?c===!1?d.setFocus():d.setActive():(d.debug("Navigate: skipping hidden node"),void d.navigate(b,c))}}var e,f,g=!0,h=a.ui.keyCode,i=null;switch(b){case h.BACKSPACE:this.parent&&this.parent.parent&&d(this.parent);break;case h.LEFT:this.expanded?(this.setExpanded(!1),d(this)):this.parent&&this.parent.parent&&d(this.parent);break;case h.RIGHT:this.expanded||!this.children&&!this.lazy?this.children&&this.children.length&&d(this.children[0]):(this.setExpanded(),d(this));break;case h.UP:for(i=this.getPrevSibling();i&&!a(i.span).is(":visible");)i=i.getPrevSibling();for(;i&&i.expanded&&i.children&&i.children.length;)i=i.children[i.children.length-1];!i&&this.parent&&this.parent.parent&&(i=this.parent),d(i);break;case h.DOWN:if(this.expanded&&this.children&&this.children.length)i=this.children[0];else for(f=this.getParentList(!1,!0),e=f.length-1;e>=0;e--){for(i=f[e].getNextSibling();i&&!a(i.span).is(":visible");)i=i.getNextSibling();if(i)break}d(i);break;default:g=!1}},remove:function(){return this.parent.removeChild(this)},removeChild:function(a){return this.tree._callHook("nodeRemoveChild",this,a)},removeChildren:function(){return this.tree._callHook("nodeRemoveChildren",this)},render:function(a,b){return this.tree._callHook("nodeRender",this,a,b)},renderTitle:function(){return this.tree._callHook("nodeRenderTitle",this)},renderStatus:function(){return this.tree._callHook("nodeRenderStatus",this)},resetLazy:function(){this.removeChildren(),this.expanded=!1,this.lazy=!0,this.children=d,this.renderStatus()},scheduleAction:function(a,b){this.tree.timer&&clearTimeout(this.tree.timer),this.tree.timer=null;var c=this;switch(a){case"cancel":break;case"expand":this.tree.timer=setTimeout(function(){c.tree.debug("setTimeout: trigger expand"),c.setExpanded(!0)},b);break;case"activate":this.tree.timer=setTimeout(function(){c.tree.debug("setTimeout: trigger activate"),c.setActive(!0)},b);break;default:throw"Invalid mode "+a}},scrollIntoView:function(f,h){h!==d&&g(h)&&(this.warn("scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead."),h={topNode:h});var i,j,l,m,n=a.extend({effects:f===!0?{duration:200,queue:!1}:f,scrollOfs:this.tree.options.scrollOfs,scrollParent:this.tree.options.scrollParent||this.tree.$container,topNode:null},h),o=new a.Deferred,p=this,q=a(this.span).height(),r=a(n.scrollParent),s=n.scrollOfs.top||0,t=n.scrollOfs.bottom||0,u=r.height(),v=r.scrollTop(),w=r,x=r[0]===b,y=n.topNode||null,z=null;return a(this.span).is(":visible")?(x?(j=a(this.span).offset().top,i=y&&y.span?a(y.span).offset().top:0,w=a("html,body")):(e(r[0]!==c&&r[0]!==c.body,"scrollParent should be an simple element or `window`, not document or body."),m=r.offset().top,j=a(this.span).offset().top-m+v,i=y?a(y.span).offset().top-m+v:0,l=Math.max(0,r.innerHeight()-r[0].clientHeight),u-=l),v+s>j?z=j-s:j+q>v+u-t&&(z=j+q-u+t,y&&(e(y.isRoot()||a(y.span).is(":visible"),"topNode must be visible"),z>i&&(z=i-s))),null!==z?n.effects?(n.effects.complete=function(){o.resolveWith(p)},w.stop(!0).animate({scrollTop:z},n.effects)):(w[0].scrollTop=z,o.resolveWith(this)):o.resolveWith(this),o.promise()):(this.warn("scrollIntoView(): node is invisible."),k())},setActive:function(a,b){return this.tree._callHook("nodeSetActive",this,a,b)},setExpanded:function(a,b){return this.tree._callHook("nodeSetExpanded",this,a,b)},setFocus:function(a){return this.tree._callHook("nodeSetFocus",this,a)},setSelected:function(a){return this.tree._callHook("nodeSetSelected",this,a)},setStatus:function(a,b,c){return this.tree._callHook("nodeSetStatus",this,a,b,c)},setTitle:function(a){this.title=a,this.renderTitle()},sortChildren:function(a,b){var c,d,e=this.children;if(e){if(a=a||function(a,b){var c=a.title.toLowerCase(),d=b.title.toLowerCase();return c===d?0:c>d?1:-1},e.sort(a),b)for(c=0,d=e.length;d>c;c++)e[c].children&&e[c].sortChildren(a,"$norender$");"$norender$"!==b&&this.render()}},toDict:function(b,c){var d,e,f,g={},h=this;if(a.each(A,function(a,b){(h[b]||h[b]===!1)&&(g[b]=h[b])}),a.isEmptyObject(this.data)||(g.data=a.extend({},this.data),a.isEmptyObject(g.data)&&delete g.data),c&&c(g),b&&this.hasChildren())for(g.children=[],d=0,e=this.children.length;e>d;d++)f=this.children[d],f.isStatusNode()||g.children.push(f.toDict(!0,c));return g},toggleExpanded:function(){return this.tree._callHook("nodeToggleExpanded",this)},toggleSelected:function(){return this.tree._callHook("nodeToggleSelected",this)},toString:function(){return"<FancytreeNode(#"+this.key+", '"+this.title+"')>"},visit:function(a,b){var c,d,e=!0,f=this.children;if(b===!0&&(e=a(this),e===!1||"skip"===e))return e;if(f)for(c=0,d=f.length;d>c&&(e=f[c].visit(a,!0),e!==!1);c++);return e},visitAndLoad:function(b,c,d){var e,f,g,h=this;return b&&c===!0&&(f=b(h),f===!1||"skip"===f)?d?f:k():h.children||h.lazy?(e=new a.Deferred,g=[],h.load().done(function(){for(var c=0,d=h.children.length;d>c;c++){if(f=h.children[c].visitAndLoad(b,!0,!0),f===!1){e.reject();break}"skip"!==f&&g.push(f)}a.when.apply(this,g).then(function(){e.resolve()})}),e.promise()):k()},visitParents:function(a,b){if(b&&a(this)===!1)return!1;for(var c=this.parent;c;){if(a(c)===!1)return!1;c=c.parent}return!0},warn:function(){Array.prototype.unshift.call(arguments,this.toString()),f("warn",arguments)}},r.prototype={_makeHookContext:function(b,c,e){var f,g;return b.node!==d?(c&&b.originalEvent!==c&&a.error("invalid args"),f=b):b.tree?(g=b.tree,f={node:b,tree:g,widget:g.widget,options:g.widget.options,originalEvent:c}):b.widget?f={node:null,tree:b,widget:b.widget,options:b.widget.options,originalEvent:c}:a.error("invalid args"),e&&a.extend(f,e),f},_callHook:function(b,c){var d=this._makeHookContext(c),e=this[b],f=Array.prototype.slice.call(arguments,2);return a.isFunction(e)||a.error("_callHook('"+b+"') is not a function"),f.unshift(d),e.apply(this,f)},_requireExtension:function(b,c,d,f){d=!!d;var g=this._local.name,h=this.options.extensions,i=a.inArray(b,h)<a.inArray(g,h),j=c&&null==this.ext[b],k=!j&&null!=d&&d!==i;return e(g&&g!==b),j||k?(f||(j||c?(f="'"+g+"' extension requires '"+b+"'",k&&(f+=" to be registered "+(d?"before":"after")+" itself")):f="If used together, `"+b+"` must be registered "+(d?"before":"after")+" `"+g+"`"),a.error(f),!1):!0},activateKey:function(a){var b=this.getNodeByKey(a);return b?b.setActive():this.activeNode&&this.activeNode.setActive(!1),b},applyPatch:function(b){var c,d,f,g,h,i,j=b.length,k=[];for(d=0;j>d;d++)f=b[d],e(2===f.length,"patchList must be an array of length-2-arrays"),g=f[0],h=f[1],i=null===g?this.rootNode:this.getNodeByKey(g),i?(c=new a.Deferred,k.push(c),i.applyPatch(h).always(m(c,i))):this.warn("could not find node with key '"+g+"'");return a.when.apply(a,k).promise()},count:function(){return this.rootNode.countChildren()},debug:function(){this.options.debugLevel>=2&&(Array.prototype.unshift.call(arguments,this.toString()),f("log",arguments))},findNextNode:function(b,c){var d=null,e=c.parent.children,f=null,g=function(a,b,c){var d,e,f=a.children,h=f.length,i=f[b];if(i&&c(i)===!1)return!1;if(i&&i.children&&i.expanded&&g(i,0,c)===!1)return!1;for(d=b+1;h>d;d++)if(g(a,d,c)===!1)return!1;return e=a.parent,e?g(e,e.children.indexOf(a)+1,c):g(a,0,c)};return b="string"==typeof b?p(b):b,c=c||this.getFirstChild(),g(c.parent,e.indexOf(c),function(e){return e===d?!1:(d=d||e,a(e.span).is(":visible")?b(e)&&(f=e,f!==c)?!1:void 0:void e.debug("quicksearch: skipping hidden node"))}),f},generateFormElements:function(b,c){var d,e=b!==!1?"ft_"+this._id+"[]":b,f=c!==!1?"ft_"+this._id+"_active":c,g="fancytree_result_"+this._id,h=a("#"+g);h.length?h.empty():h=a("<div>",{id:g}).hide().insertAfter(this.$container),e&&(d=this.getSelectedNodes(3===this.options.selectMode),a.each(d,function(b,c){h.append(a("<input>",{type:"checkbox",name:e,value:c.key,checked:!0}))})),f&&this.activeNode&&h.append(a("<input>",{type:"radio",name:f,value:this.activeNode.key,checked:!0}))},getActiveNode:function(){return this.activeNode},getFirstChild:function(){return this.rootNode.getFirstChild()},getFocusNode:function(){return this.focusNode},getNodeByKey:function(a,b){var d,e;return!b&&(d=c.getElementById(this.options.idPrefix+a))?d.ftnode?d.ftnode:null:(b=b||this.rootNode,e=null,b.visit(function(b){return b.key===a?(e=b,!1):void 0},!0),e)},getRootNode:function(){return this.rootNode},getSelectedNodes:function(a){var b=[];return this.rootNode.visit(function(c){return c.selected&&(b.push(c),a===!0)?"skip":void 0}),b},hasFocus:function(){return!!this._hasFocus},info:function(){this.options.debugLevel>=1&&(Array.prototype.unshift.call(arguments,this.toString()),f("info",arguments))},loadKeyPath:function(b,c,e){function f(a,b,d){c.call(r,b,"loading"),b.load().done(function(){r.loadKeyPath.call(r,l[a],c,b).always(m(d,r))}).fail(function(){r.warn("loadKeyPath: error loading: "+a+" (parent: "+o+")"),c.call(r,b,"error"),d.reject()})}var g,h,i,j,k,l,n,o,p,q=this.options.keyPathSeparator,r=this;for(a.isArray(b)||(b=[b]),l={},i=0;i<b.length;i++)for(o=e||this.rootNode,j=b[i],j.charAt(0)===q&&(j=j.substr(1)),p=j.split(q);p.length;){if(k=p.shift(),n=o._findDirectChild(k),!n){this.warn("loadKeyPath: key not found: "+k+" (parent: "+o+")"),c.call(this,k,"error");break}if(0===p.length){c.call(this,n,"ok");break}if(n.lazy&&n.hasChildren()===d){c.call(this,n,"loaded"),l[k]?l[k].push(p.join(q)):l[k]=[p.join(q)];break}c.call(this,n,"loaded"),o=n}g=[];for(k in l)n=o._findDirectChild(k),h=new a.Deferred,g.push(h),f(k,n,h);return a.when.apply(a,g).promise()},reactivate:function(a){var b,c=this.activeNode;return c?(this.activeNode=null,b=c.setActive(),a&&c.setFocus(),b):k()},reload:function(a){return this._callHook("treeClear",this),this._callHook("treeLoad",this,a)},render:function(a,b){return this.rootNode.render(a,b)},setFocus:function(a){return this._callHook("treeSetFocus",this,a)},toDict:function(a,b){var c=this.rootNode.toDict(!0,b);return a?c:c.children},toString:function(){return"<Fancytree(#"+this._id+")>"},_triggerNodeEvent:function(a,b,c,e){var f=this._makeHookContext(b,c,e),g=this.widget._trigger(a,c,f);return g!==!1&&f.result!==d?f.result:g},_triggerTreeEvent:function(a,b,c){var e=this._makeHookContext(this,b,c),f=this.widget._trigger(a,b,e);return f!==!1&&e.result!==d?e.result:f},visit:function(a){return this.rootNode.visit(a,!1)},warn:function(){Array.prototype.unshift.call(arguments,this.toString()),f("warn",arguments)}},a.extend(r.prototype,{nodeClick:function(a){var b,c,d=a.targetType,e=a.node;if("expander"===d)this._callHook("nodeToggleExpanded",a);else if("checkbox"===d)this._callHook("nodeToggleSelected",a),a.options.focusOnSelect&&this._callHook("nodeSetFocus",a,!0);else{if(c=!1,b=!0,e.folder)switch(a.options.clickFolderMode){case 2:c=!0,b=!1;break;case 3:b=!0,c=!0}b&&(this.nodeSetFocus(a),this._callHook("nodeSetActive",a,!0)),c&&this._callHook("nodeToggleExpanded",a)}},nodeCollapseSiblings:function(a,b){var c,d,e,f=a.node;if(f.parent)for(c=f.parent.children,d=0,e=c.length;e>d;d++)c[d]!==f&&c[d].expanded&&this._callHook("nodeSetExpanded",c[d],!1,b)},nodeDblclick:function(a){"title"===a.targetType&&4===a.options.clickFolderMode&&this._callHook("nodeToggleExpanded",a),"title"===a.targetType&&a.originalEvent.preventDefault()},nodeKeydown:function(b){var c,d,e,f=b.originalEvent,g=b.node,h=b.tree,i=b.options,j=f.which,k=String.fromCharCode(j),l=!(f.altKey||f.ctrlKey||f.metaKey||f.shiftKey),m=a(f.target),n=!0,o=!(f.ctrlKey||!i.autoActivate);if(g||((this.getActiveNode()||this.getFirstChild()).setFocus(),g=b.node=this.focusNode,g.debug("Keydown force focus on active node")),i.quicksearch&&l&&/\w/.test(k)&&!m.is(":input:enabled"))return d=(new Date).getTime(),d-h.lastQuicksearchTime>500&&(h.lastQuicksearchTerm=""),h.lastQuicksearchTime=d,h.lastQuicksearchTerm+=k,c=h.findNextNode(h.lastQuicksearchTerm,h.getActiveNode()),c&&c.setActive(),void f.preventDefault();switch(t.eventToString(f)){case"+":case"=":h.nodeSetExpanded(b,!0);break;case"-":h.nodeSetExpanded(b,!1);break;case"space":i.checkbox?h.nodeToggleSelected(b):h.nodeSetActive(b,!0);break;case"enter":h.nodeSetActive(b,!0);break;case"backspace":case"left":case"right":case"up":case"down":e=g.navigate(f.which,o);break;default:n=!1}n&&f.preventDefault()},nodeLoadChildren:function(b,c){var d,f,g,h=b.tree,i=b.node;return a.isFunction(c)&&(c=c()),c.url&&(d=a.extend({},b.options.ajax,c),d.debugDelay?(f=d.debugDelay,a.isArray(f)&&(f=f[0]+Math.random()*(f[1]-f[0])),i.debug("nodeLoadChildren waiting debug delay "+Math.round(f)+"ms"),d.debugDelay=!1,g=a.Deferred(function(b){setTimeout(function(){a.ajax(d).done(function(){b.resolveWith(this,arguments)}).fail(function(){b.rejectWith(this,arguments)})},f)})):g=a.ajax(d),c=new a.Deferred,g.done(function(d){var e,f;if("string"==typeof d&&a.error("Ajax request returned a string (did you get the JSON dataType wrong?)."),b.options.postProcess){if(f=h._triggerNodeEvent("postProcess",b,b.originalEvent,{response:d,error:null,dataType:this.dataType}),f.error)return e=a.isPlainObject(f.error)?f.error:{message:f.error},e=h._makeHookContext(i,null,e),void c.rejectWith(this,[e]);d=a.isArray(f)?f:d}else d&&d.hasOwnProperty("d")&&b.options.enableAspx&&(d="string"==typeof d.d?a.parseJSON(d.d):d.d);c.resolveWith(this,[d])}).fail(function(a,b,d){var e=h._makeHookContext(i,null,{error:a,args:Array.prototype.slice.call(arguments),message:d,details:a.status+": "+d});c.rejectWith(this,[e])})),a.isFunction(c.then)&&a.isFunction(c["catch"])&&(g=c,c=new a.Deferred,g.then(function(a){c.resolve(a)},function(a){c.reject(a)})),a.isFunction(c.promise)&&(e(!i.isLoading()),h.nodeSetStatus(b,"loading"),c.done(function(){h.nodeSetStatus(b,"ok")}).fail(function(a){var c;c=a.node&&a.error&&a.message?a:h._makeHookContext(i,null,{error:a,args:Array.prototype.slice.call(arguments),message:a?a.message||a.toString():""}),h._triggerNodeEvent("loadError",c,null)!==!1&&h.nodeSetStatus(b,"error",c.message,c.details)})),a.when(c).done(function(b){var c;a.isPlainObject(b)&&(e(a.isArray(b.children),"source must contain (or be) an array of children"),e(i.isRoot(),"source may only be an object for root nodes"),c=b,b=b.children,delete c.children,a.extend(h.data,c)),e(a.isArray(b),"expected array of children"),i._setChildren(b),h._triggerNodeEvent("loadChildren",i)})},nodeLoadKeyPath:function(){},nodeRemoveChild:function(b,c){var d,f=b.node,g=b.options,h=a.extend({},b,{node:c}),i=f.children;return 1===i.length?(e(c===i[0]),this.nodeRemoveChildren(b)):(this.activeNode&&(c===this.activeNode||this.activeNode.isDescendantOf(c))&&this.activeNode.setActive(!1),this.focusNode&&(c===this.focusNode||this.focusNode.isDescendantOf(c))&&(this.focusNode=null),this.nodeRemoveMarkup(h),this.nodeRemoveChildren(h),d=a.inArray(c,i),e(d>=0),c.visit(function(a){a.parent=null},!0),this._callHook("treeRegisterNode",this,!1,c),g.removeNode&&g.removeNode.call(b.tree,{type:"removeNode"},h),void i.splice(d,1))},nodeRemoveChildMarkup:function(b){var c=b.node;c.ul&&(c.isRoot()?a(c.ul).empty():(a(c.ul).remove(),c.ul=null),c.visit(function(a){a.li=a.ul=null}))},nodeRemoveChildren:function(b){var c,d=b.tree,e=b.node,f=e.children,g=b.options;f&&(this.activeNode&&this.activeNode.isDescendantOf(e)&&this.activeNode.setActive(!1),this.focusNode&&this.focusNode.isDescendantOf(e)&&(this.focusNode=null),this.nodeRemoveChildMarkup(b),c=a.extend({},b),e.visit(function(a){a.parent=null,d._callHook("treeRegisterNode",d,!1,a),g.removeNode&&(c.node=a,g.removeNode.call(b.tree,{type:"removeNode"},c))}),e.children=e.lazy?[]:null,this.nodeRenderStatus(b))},nodeRemoveMarkup:function(b){var c=b.node;c.li&&(a(c.li).remove(),c.li=null),this.nodeRemoveChildMarkup(b)},nodeRender:function(b,d,f,g,h){var i,j,k,l,m,n,o,p=b.node,q=b.tree,r=b.options,s=r.aria,t=!1,u=p.parent,v=!u,w=p.children;if(v||u.ul){if(e(v||u.ul,"parent UL must exist"),v||(p.li&&(d||p.li.parentNode!==p.parent.ul)&&(p.li.parentNode!==p.parent.ul&&this.debug("Unlinking "+p+" (must be child of "+p.parent+")"),this.nodeRemoveMarkup(b)),p.li?this.nodeRenderStatus(b):(t=!0,p.li=c.createElement("li"),p.li.ftnode=p,p.key&&r.generateIds&&(p.li.id=r.idPrefix+p.key),p.span=c.createElement("span"),p.span.className="fancytree-node",s&&a(p.span).attr("aria-labelledby","ftal_"+p.key),p.li.appendChild(p.span),this.nodeRenderTitle(b),r.createNode&&r.createNode.call(q,{type:"createNode"},b)),r.renderNode&&r.renderNode.call(q,{type:"renderNode"},b)),w){if(v||p.expanded||f===!0){for(p.ul||(p.ul=c.createElement("ul"),(g===!0&&!h||!p.expanded)&&(p.ul.style.display="none"),s&&a(p.ul).attr("role","group"),p.li?p.li.appendChild(p.ul):p.tree.$div.append(p.ul)),l=0,m=w.length;m>l;l++)o=a.extend({},b,{node:w[l]}),this.nodeRender(o,d,f,!1,!0);for(i=p.ul.firstChild;i;)k=i.ftnode,k&&k.parent!==p?(p.debug("_fixParent: remove missing "+k,i),n=i.nextSibling,i.parentNode.removeChild(i),i=n):i=i.nextSibling;for(i=p.ul.firstChild,l=0,m=w.length-1;m>l;l++)j=w[l],k=i.ftnode,j!==k?p.ul.insertBefore(j.li,k.li):i=i.nextSibling}}else p.ul&&(this.warn("remove child markup for "+p),this.nodeRemoveChildMarkup(b));v||t&&u.ul.appendChild(p.li)}},nodeRenderTitle:function(a,b){var c,e,f,g,h,i,j=a.node,k=a.tree,l=a.options,m=l.aria,n=j.getLevel(),o=[],p=j.data.icon;b!==d&&(j.title=b),j.span&&(n<l.minExpandLevel?(j.lazy||(j.expanded=!0),n>1&&o.push(m?"<span role='button' class='fancytree-expander fancytree-expander-fixed'></span>":"<span class='fancytree-expander fancytree-expander-fixed''></span>")):o.push(m?"<span role='button' class='fancytree-expander'></span>":"<span class='fancytree-expander'></span>"),l.checkbox&&j.hideCheckbox!==!0&&!j.isStatusNode()&&o.push(m?"<span role='checkbox' class='fancytree-checkbox'></span>":"<span class='fancytree-checkbox'></span>"),g=m?" role='img'":"",(p===!0||p!==!1&&l.icons!==!1)&&(p&&"string"==typeof p?(p="/"===p.charAt(0)?p:(l.imagePath||"")+p,o.push("<img src='"+p+"' class='fancytree-icon' alt='' />")):(e=l.iconClass&&l.iconClass.call(k,j,a)||j.data.iconclass||null,o.push(e?"<span "+g+" class='fancytree-custom-icon "+e+"'></span>":"<span "+g+" class='fancytree-icon'></span>"))),f="",l.renderTitle&&(f=l.renderTitle.call(k,{type:"renderTitle"},a)||""),f||(i=j.tooltip?" title='"+t.escapeHtml(j.tooltip)+"'":"",c=m?" id='ftal_"+j.key+"'":"",g=m?" role='treeitem'":"",h=l.titlesTabbable?" tabindex='0'":"",f="<span "+g+" class='fancytree-title'"+c+i+h+">"+j.title+"</span>"),o.push(f),j.span.innerHTML=o.join(""),this.nodeRenderStatus(a))},nodeRenderStatus:function(b){var c=b.node,d=b.tree,e=b.options,f=c.hasChildren(),g=c.isLastSibling(),h=e.aria,i=a(c.span).find(".fancytree-title"),j=e._classNames,k=[],l=c[d.statusClassPropName];
l&&(k.push(j.node),d.activeNode===c&&k.push(j.active),d.focusNode===c?(k.push(j.focused),h&&i.attr("aria-activedescendant",!0)):h&&i.removeAttr("aria-activedescendant"),c.expanded?(k.push(j.expanded),h&&i.attr("aria-expanded",!0)):h&&i.removeAttr("aria-expanded"),c.folder&&k.push(j.folder),f!==!1&&k.push(j.hasChildren),g&&k.push(j.lastsib),c.lazy&&null==c.children&&k.push(j.lazy),c.partsel&&k.push(j.partsel),c.unselectable&&k.push(j.unselectable),c._isLoading&&k.push(j.loading),c._error&&k.push(j.error),c.selected?(k.push(j.selected),h&&i.attr("aria-selected",!0)):h&&i.attr("aria-selected",!1),c.extraClasses&&k.push(c.extraClasses),k.push(f===!1?j.combinedExpanderPrefix+"n"+(g?"l":""):j.combinedExpanderPrefix+(c.expanded?"e":"c")+(c.lazy&&null==c.children?"d":"")+(g?"l":"")),k.push(j.combinedIconPrefix+(c.expanded?"e":"c")+(c.folder?"f":"")),l.className=k.join(" "),c.li&&(c.li.className=g?j.lastsib:""))},nodeSetActive:function(b,c,d){d=d||{};var f,g=b.node,h=b.tree,i=b.options,j=d.noEvents===!0,m=d.noFocus===!0,n=g===h.activeNode;return c=c!==!1,n===c?k(g):c&&!j&&this._triggerNodeEvent("beforeActivate",g,b.originalEvent)===!1?l(g,["rejected"]):void(c?(h.activeNode&&(e(h.activeNode!==g,"node was active (inconsistency)"),f=a.extend({},b,{node:h.activeNode}),h.nodeSetActive(f,!1),e(null===h.activeNode,"deactivate was out of sync?")),i.activeVisible&&g.makeVisible({scrollIntoView:!1}),h.activeNode=g,h.nodeRenderStatus(b),m||h.nodeSetFocus(b),j||h._triggerNodeEvent("activate",g,b.originalEvent)):(e(h.activeNode===g,"node was not active (inconsistency)"),h.activeNode=null,this.nodeRenderStatus(b),j||b.tree._triggerNodeEvent("deactivate",g,b.originalEvent)))},nodeSetExpanded:function(b,c,e){e=e||{};var f,g,h,i,j,m,n=b.node,o=b.tree,p=b.options,q=e.noAnimation===!0,r=e.noEvents===!0;if(c=c!==!1,n.expanded&&c||!n.expanded&&!c)return k(n);if(c&&!n.lazy&&!n.hasChildren())return k(n);if(!c&&n.getLevel()<p.minExpandLevel)return l(n,["locked"]);if(!r&&this._triggerNodeEvent("beforeExpand",n,b.originalEvent)===!1)return l(n,["rejected"]);if(q||n.isVisible()||(q=e.noAnimation=!0),g=new a.Deferred,c&&!n.expanded&&p.autoCollapse){j=n.getParentList(!1,!0),m=p.autoCollapse;try{for(p.autoCollapse=!1,h=0,i=j.length;i>h;h++)this._callHook("nodeCollapseSiblings",j[h],e)}finally{p.autoCollapse=m}}return g.done(function(){c&&p.autoScroll&&!q?n.getLastChild().scrollIntoView(!0,{topNode:n}).always(function(){r||b.tree._triggerNodeEvent(c?"expand":"collapse",b)}):r||b.tree._triggerNodeEvent(c?"expand":"collapse",b)}),f=function(d){var e,f,g=p.toggleEffect;if(n.expanded=c,o._callHook("nodeRender",b,!1,!1,!0),n.ul)if(e="none"!==n.ul.style.display,f=!!n.expanded,e===f)n.warn("nodeSetExpanded: UL.style.display already set");else{if(g&&!q)return void a(n.ul).toggle(g.effect,g.options,g.duration,function(){d()});n.ul.style.display=n.expanded||!parent?"":"none"}d()},c&&n.lazy&&n.hasChildren()===d?n.load().done(function(){g.notifyWith&&g.notifyWith(n,["loaded"]),f(function(){g.resolveWith(n)})}).fail(function(a){f(function(){g.rejectWith(n,["load failed ("+a+")"])})}):f(function(){g.resolveWith(n)}),g.promise()},nodeSetFocus:function(b,c){var d,e=b.tree,f=b.node;if(c=c!==!1,e.focusNode){if(e.focusNode===f&&c)return;d=a.extend({},b,{node:e.focusNode}),e.focusNode=null,this._triggerNodeEvent("blur",d),this._callHook("nodeRenderStatus",d)}c&&(this.hasFocus()||(f.debug("nodeSetFocus: forcing container focus"),this._callHook("treeSetFocus",b,!0,{calledByNode:!0})),f.makeVisible({scrollIntoView:!1}),e.focusNode=f,this._triggerNodeEvent("focus",b),b.options.autoScroll&&f.scrollIntoView(),this._callHook("nodeRenderStatus",b))},nodeSetSelected:function(a,b){var c=a.node,d=a.tree,e=a.options;if(b=b!==!1,c.debug("nodeSetSelected("+b+")",a),!c.unselectable){if(c.selected&&b||!c.selected&&!b)return!!c.selected;if(this._triggerNodeEvent("beforeSelect",c,a.originalEvent)===!1)return!!c.selected;b&&1===e.selectMode?d.lastSelectedNode&&d.lastSelectedNode.setSelected(!1):3===e.selectMode&&(c.selected=b,c.fixSelection3AfterClick()),c.selected=b,this.nodeRenderStatus(a),d.lastSelectedNode=b?c:null,d._triggerNodeEvent("select",a)}},nodeSetStatus:function(b,c,d,e){function f(){var a=h.children?h.children[0]:null;if(a&&a.isStatusNode()){try{h.ul&&(h.ul.removeChild(a.li),a.li=null)}catch(b){}1===h.children.length?h.children=[]:h.children.shift()}}function g(b,c){var d=h.children?h.children[0]:null;return d&&d.isStatusNode()?(a.extend(d,b),i._callHook("nodeRenderTitle",d)):(b.key="_statusNode",h._setChildren([b]),h.children[0].statusNodeType=c,i.render()),h.children[0]}var h=b.node,i=b.tree;switch(c){case"ok":f(),h._isLoading=!1,h._error=null,h.renderStatus();break;case"loading":h.parent||g({title:i.options.strings.loading+(d?" ("+d+") ":""),tooltip:e,extraClasses:"fancytree-statusnode-wait"},c),h._isLoading=!0,h._error=null,h.renderStatus();break;case"error":g({title:i.options.strings.loadError+(d?" ("+d+") ":""),tooltip:e,extraClasses:"fancytree-statusnode-error"},c),h._isLoading=!1,h._error={message:d,details:e},h.renderStatus();break;default:a.error("invalid node status "+c)}},nodeToggleExpanded:function(a){return this.nodeSetExpanded(a,!a.node.expanded)},nodeToggleSelected:function(a){return this.nodeSetSelected(a,!a.node.selected)},treeClear:function(a){var b=a.tree;b.activeNode=null,b.focusNode=null,b.$div.find(">ul.fancytree-container").empty(),b.rootNode.children=null},treeCreate:function(){},treeDestroy:function(){},treeInit:function(a){this.treeLoad(a)},treeLoad:function(b,c){var d,e,f,g=b.tree,h=b.widget.element,i=a.extend({},b,{node:this.rootNode});if(g.rootNode.children&&this.treeClear(b),c=c||this.options.source)"string"==typeof c&&a.error("Not implemented");else switch(d=h.data("type")||"html"){case"html":e=h.find(">ul:first"),e.addClass("ui-fancytree-source ui-helper-hidden"),c=a.ui.fancytree.parseHtml(e),this.data=a.extend(this.data,n(e));break;case"json":c=a.parseJSON(h.text()),c.children&&(c.title&&(g.title=c.title),c=c.children);break;default:a.error("Invalid data-type: "+d)}return f=this.nodeLoadChildren(i,c).done(function(){g.render(),3===b.options.selectMode&&g.rootNode.fixSelection3FromEndNodes(),g._triggerTreeEvent("init",null,{status:!0})}).fail(function(){g.render(),g._triggerTreeEvent("init",null,{status:!1})})},treeRegisterNode:function(){},treeSetFocus:function(a,b){b=b!==!1,b!==this.hasFocus()&&(this._hasFocus=b,!b&&this.focusNode&&this.focusNode.setFocus(!1),this.$container.toggleClass("fancytree-treefocus",b),this._triggerTreeEvent(b?"focusTree":"blurTree"))}}),a.widget("ui.fancytree",{options:{activeVisible:!0,ajax:{type:"GET",cache:!1,dataType:"json"},aria:!1,autoActivate:!0,autoCollapse:!1,autoScroll:!1,checkbox:!1,clickFolderMode:4,debugLevel:null,disabled:!1,enableAspx:!0,extensions:[],toggleEffect:{effect:"blind",options:{direction:"vertical",scale:"box"},duration:200},generateIds:!1,icons:!0,idPrefix:"ft_",focusOnSelect:!1,keyboard:!0,keyPathSeparator:"/",minExpandLevel:1,quicksearch:!1,scrollOfs:{top:0,bottom:0},scrollParent:null,selectMode:2,strings:{loading:"Loading…",loadError:"Load error!"},tabbable:!0,titlesTabbable:!1,_classNames:{node:"fancytree-node",folder:"fancytree-folder",combinedExpanderPrefix:"fancytree-exp-",combinedIconPrefix:"fancytree-ico-",hasChildren:"fancytree-has-children",active:"fancytree-active",selected:"fancytree-selected",expanded:"fancytree-expanded",lazy:"fancytree-lazy",focused:"fancytree-focused",partsel:"fancytree-partsel",unselectable:"fancytree-unselectable",lastsib:"fancytree-lastsib",loading:"fancytree-loading",error:"fancytree-error"},lazyLoad:null,postProcess:null},_create:function(){this.tree=new r(this),this.$source=this.source||"json"===this.element.data("type")?this.element:this.element.find(">ul:first");var b,c,f,g=this.options.extensions,h=this.tree;for(f=0;f<g.length;f++)c=g[f],b=a.ui.fancytree._extensions[c],b||a.error("Could not apply extension '"+c+"' (it is not registered, did you forget to include it?)"),this.tree.options[c]=a.extend(!0,{},b.options,this.tree.options[c]),e(this.tree.ext[c]===d,"Extension name must not exist as Fancytree.ext attribute: '"+c+"'"),this.tree.ext[c]={},j(this.tree,h,b,c),h=b;this.tree._callHook("treeCreate",this.tree)},_init:function(){this.tree._callHook("treeInit",this.tree),this._bind()},_setOption:function(b,c){var d=!0,e=!1;switch(b){case"aria":case"checkbox":case"icons":case"minExpandLevel":case"tabbable":this.tree._callHook("treeCreate",this.tree),e=!0;break;case"source":d=!1,this.tree._callHook("treeLoad",this.tree,c)}this.tree.debug("set option "+b+"="+c+" <"+typeof c+">"),d&&a.Widget.prototype._setOption.apply(this,arguments),e&&this.tree.render(!0,!1)},destroy:function(){this._unbind(),this.tree._callHook("treeDestroy",this.tree),this.tree.$div.find(">ul.fancytree-container").remove(),this.$source&&this.$source.removeClass("ui-helper-hidden"),a.Widget.prototype.destroy.call(this)},_unbind:function(){var b=this.tree._ns;this.element.unbind(b),this.tree.$container.unbind(b),a(c).unbind(b)},_bind:function(){var a=this,b=this.options,c=this.tree,d=c._ns;this._unbind(),c.$container.on("focusin"+d+" focusout"+d,function(a){var b=t.getNode(a),d="focusin"===a.type;b?c._callHook("nodeSetFocus",b,d):c._callHook("treeSetFocus",c,d)}).on("selectstart"+d,"span.fancytree-title",function(a){a.preventDefault()}).on("keydown"+d,function(a){if(b.disabled||b.keyboard===!1)return!0;var d,e=c.focusNode,f=c._makeHookContext(e||c,a),g=c.phase;try{return c.phase="userEvent",d=e?c._triggerNodeEvent("keydown",e,a):c._triggerTreeEvent("keydown",a),"preventNav"===d?d=!0:d!==!1&&(d=c._callHook("nodeKeydown",f)),d}finally{c.phase=g}}).on("click"+d+" dblclick"+d,function(c){if(b.disabled)return!0;var d,e=t.getEventTarget(c),f=e.node,g=a.tree,h=g.phase;if(!f)return!0;d=g._makeHookContext(f,c);try{switch(g.phase="userEvent",c.type){case"click":return d.targetType=e.type,g._triggerNodeEvent("click",d,c)===!1?!1:g._callHook("nodeClick",d);case"dblclick":return d.targetType=e.type,g._triggerNodeEvent("dblclick",d,c)===!1?!1:g._callHook("nodeDblclick",d)}}finally{g.phase=h}})},getActiveNode:function(){return this.tree.activeNode},getNodeByKey:function(a){return this.tree.getNodeByKey(a)},getRootNode:function(){return this.tree.rootNode},getTree:function(){return this.tree}}),t=a.ui.fancytree,a.extend(a.ui.fancytree,{version:"2.8.0",buildType: "production",debugLevel: 1,_nextId:1,_nextNodeKey:1,_extensions:{},_FancytreeClass:r,_FancytreeNodeClass:q,jquerySupports:{positionMyOfs:h(a.ui.version,1,9)},assert:function(a,b){return e(a,b)},debounce:function(a,b,c,d){var e;return 3===arguments.length&&"boolean"!=typeof c&&(d=c,c=!1),function(){var f=arguments;d=d||this,c&&!e&&b.apply(d,f),clearTimeout(e),e=setTimeout(function(){c||b.apply(d,f),e=null},a)}},debug:function(){a.ui.fancytree.debugLevel>=2&&f("log",arguments)},error:function(){f("error",arguments)},escapeHtml:function(a){return(""+a).replace(/[&<>"'\/]/g,function(a){return u[a]})},fixPositionOptions:function(b){if((b.offset||(""+b.my+b.at).indexOf("%")>=0)&&a.error("expected new position syntax (but '%' is not supported)"),!a.ui.fancytree.jquerySupports.positionMyOfs){var c=/(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(b.my),d=/(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(b.at),e=(c[2]?+c[2]:0)+(d[2]?+d[2]:0),f=(c[4]?+c[4]:0)+(d[4]?+d[4]:0);b=a.extend({},b,{my:c[1]+" "+c[3],at:d[1]+" "+d[3]}),(e||f)&&(b.offset=""+e+" "+f)}return b},getEventTargetType:function(a){return this.getEventTarget(a).type},getEventTarget:function(b){var c=b&&b.target?b.target.className:"",e={node:this.getNode(b.target),type:d};return/\bfancytree-title\b/.test(c)?e.type="title":/\bfancytree-expander\b/.test(c)?e.type=e.node.hasChildren()===!1?"prefix":"expander":/\bfancytree-checkbox\b/.test(c)||/\bfancytree-radio\b/.test(c)?e.type="checkbox":/\bfancytree-icon\b/.test(c)?e.type="icon":/\bfancytree-node\b/.test(c)?e.type="title":b&&b.target&&a(b.target).closest(".fancytree-title").length&&(e.type="title"),e},getNode:function(a){if(a instanceof q)return a;for(a.selector!==d?a=a[0]:a.originalEvent!==d&&(a=a.target);a;){if(a.ftnode)return a.ftnode;a=a.parentNode}return null},info:function(){a.ui.fancytree.debugLevel>=1&&f("info",arguments)},eventToString:function(a){var b=a.which,c=a.type,d=[];return a.altKey&&d.push("alt"),a.ctrlKey&&d.push("ctrl"),a.metaKey&&d.push("meta"),a.shiftKey&&d.push("shift"),"click"===c||"dblclick"===c?d.push(x[a.button]+c):v[b]||d.push(w[b]||String.fromCharCode(b).toLowerCase()),d.join("+")},keyEventToString:function(a){return this.warn("keyEventToString() is deprecated: use eventToString()"),this.eventToString(a)},parseHtml:function(b){var c,e,f,g,h,i,j,k,l=b.find(">li"),m=[];return l.each(function(){var l,o=a(this),p=o.find(">span:first",this),q=p.length?null:o.find(">a:first"),r={tooltip:null,data:{}};for(p.length?r.title=p.html():q&&q.length?(r.title=q.html(),r.data.href=q.attr("href"),r.data.target=q.attr("target"),r.tooltip=q.attr("title")):(r.title=o.html(),g=r.title.search(/<ul/i),g>=0&&(r.title=r.title.substring(0,g))),r.title=a.trim(r.title),e=0,f=y.length;f>e;e++)r[y[e]]=d;for(j=this.className.split(" "),c=[],e=0,f=j.length;f>e;e++)k=j[e],z[k]?r[k]=!0:c.push(k);if(r.extraClasses=c.join(" "),h=o.attr("title"),h&&(r.tooltip=h),h=o.attr("id"),h&&(r.key=h),l=n(o),l&&!a.isEmptyObject(l)){for(e=0,f=A.length;f>e;e++)h=A[e],i=l[h],null!=i&&(delete l[h],r[h]=i);a.extend(r.data,l)}b=o.find(">ul:first"),r.children=b.length?a.ui.fancytree.parseHtml(b):r.lazy?d:null,m.push(r)}),m},registerExtension:function(b){e(null!=b.name,"extensions must have a `name` property."),e(null!=b.version,"extensions must have a `version` property."),a.ui.fancytree._extensions[b.name]=b},unescapeHtml:function(a){var b=c.createElement("div");return b.innerHTML=a,0===b.childNodes.length?"":b.childNodes[0].nodeValue},warn:function(){f("warn",arguments)}})}(jQuery,window,document); |
torrentula/app/src/js/src/ui/torrent-buttons/torrent-buttons.js | projectnfx/projectnfx.github.io | //All stats
import React, { Component } from 'react';
import ReactInStyle from 'react-in-style';
import TorrentActions from '../../actions/download-actions';
class TorrentButtons extends Component {
renderPreviewButton(fileType) {
if (fileType === 'mp4' || fileType === 'webm') {
return <button onClick={this.props.onPreviewVideo} className="button-options"><i className='icon-play'></i></button>
} else if (fileType === 'jpg' || fileType === 'png') {
return <button onClick={this.props.onPreviewImage} className="button-options"><i className='icon-file-image'></i></button>
}
}
render() {
let fileType = null;
if (this.props.download.torrent && this.props.download.torrent.files[0]) {
fileType = this.props.download.torrent.files[0].name.split('.').pop();
}
return (
<div className='item-buttons'>
<button className='button-options' onClick={() => this.props.onExpand()}><i className='icon-share'></i></button>
{
this.props.info.completed ?
<button className='button-download' onClick={() => this.props.download.saveFile() }><i className='icon-down-circled'></i></button> :
(this.props.download.url ? <button className='button-revert' onClick={() => TorrentActions.downloadWithHttp(this.props.download)}><i className='icon-link'></i></button> : null)
}
<button className='button-clear' onClick={() => TorrentActions.clearDownload(this.props.download)}><i className='icon-cancel-circled'></i></button>
{this.renderPreviewButton(fileType)}
</div>
);
}
};
TorrentButtons.prototype.displayName = 'TorrentButtons';
export default TorrentButtons;
|
index.js | CreaturePhil/redux-todo-counter-example | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import App from './containers/App';
import configureStore from './store/configureStore';
const store = configureStore();
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
|
src/js/components/common/alert.js | michaelatmender/gui | import React from 'react';
const Alert = ({ children, className, severity, style }) => (
<div className={(className || '') + ' alert ' + (severity ? 'alert-' + severity : '')} style={style}>
{children}
</div>
);
export default Alert;
|
src/view/dashboard/components/recentSales.js | fishmankkk/mircowater2.0 | import React from 'react'
import PropTypes from 'prop-types'
import { Table, Tag } from 'antd'
import { color } from 'utils'
import styles from './recentSales.less'
const status = {
1: {
color: color.green,
text: 'SALE',
},
2: {
color: color.yellow,
text: 'REJECT',
},
3: {
color: color.red,
text: 'TAX',
},
4: {
color: color.blue,
text: 'EXTENDED',
},
}
function RecentSales ({ data }) {
const columns = [
{
title: 'NAME',
dataIndex: 'name',
}, {
title: 'STATUS',
dataIndex: 'status',
render: text => <Tag color={status[text].color}>{status[text].text}</Tag>,
}, {
title: 'DATE',
dataIndex: 'date',
render: text => new Date(text).format('yyyy-MM-dd'),
}, {
title: 'PRICE',
dataIndex: 'price',
render: (text, it) => <span style={{ color: status[it.status].color }}>${text}</span>,
},
]
return (
<div className={styles.recentsales}>
<Table pagination={false} columns={columns} rowKey={(record, key) => key} dataSource={data.filter((item, key) => key < 5)} />
</div>
)
}
RecentSales.propTypes = {
data: PropTypes.array,
}
export default RecentSales
|
src/components/Footer/index.js | tgrecojs/tgrecojs-static | // @flow
import React from 'react';
import styled from 'styled-components';
import theme from '../../lib/theme';
const Footer = styled.div`
background-color: rgb(86, 156, 183);
font-family: 'Lato';
color: ${theme.light.lighten(0.3)};
a,
a:visited {
color: ${theme.light.lighten(0.3)};
}
`;
export default () =>
<Footer className="footer">
<small className="footer--madeWith">
Made with{' '}
<span role="img" aria-label="love">
❤️
</span>{' '}
and{' '}
<a href="https://github.com/infiniteluke/next-static">
Next Static{' '}
<span role="img" aria-label="with extra sparkles">
✨
</span>
</a>
</small>
</Footer>;
|
src/components/Winner.js | ivangeorgiew/voteApp | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import * as actions from '../actions';
import '../index.scss';
export default connect(mapStateToProps)(Winner);
/* MAP STATE TO PROPS */
function mapStateToProps(state) {
return {
winner: state.winner || '',
restart: actions.restart
}
}
/* WINNER */
Winner.propTypes = {
winner: PropTypes.string.isRequired,
restart: PropTypes.func.isRequired
}
function Winner(props) {
if(!props.winner)
return false;
return (
<div className='results'>
<div className='winner'>
Winner is {props.winner}
</div>
<div className='management'>
<button
className='next'
onClick={() => props.dispatch(props.restart())}
>
Restart
</button>
</div>
</div>
);
}
|
ajax/libs/elemental/0.5.0/elemental.min.js | quba/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.Elemental=e()}}(function(){return function e(t,o,n){function a(i,l){if(!o[i]){if(!t[i]){var r="function"==typeof require&&require;if(!l&&r)return r(i,!0);if(s)return s(i,!0);var c=new Error("Cannot find module '"+i+"'");throw c.code="MODULE_NOT_FOUND",c}var p=o[i]={exports:{}};t[i][0].call(p.exports,function(e){var o=t[i][1][e];return a(o?o:e)},p,p.exports,e,t,o,n)}return o[i].exports}for(var s="function"==typeof require&&require,i=0;i<n.length;i++)a(n[i]);return a}({1:[function(e,t,o){"use strict";o.Alert=e("./components/Alert"),o.BlankState=e("./components/BlankState"),o.Button=e("./components/Button"),o.ButtonGroup=e("./components/ButtonGroup"),o.Checkbox=e("./components/Checkbox"),o.Card=e("./components/Card"),o.Col=e("./components/Col"),o.Container=e("./components/Container"),o.Dropdown=e("./components/Dropdown"),o.EmailInputGroup=e("./components/EmailInputGroup"),o.FileDragAndDrop=e("./components/FileDragAndDrop"),o.FileUpload=e("./components/FileUpload"),o.Form=e("./components/Form"),o.FormField=e("./components/FormField"),o.FormIcon=e("./components/FormIcon"),o.FormIconField=e("./components/FormIconField"),o.FormInput=e("./components/FormInput"),o.FormLabel=e("./components/FormLabel"),o.FormNote=e("./components/FormNote"),o.FormRow=e("./components/FormRow"),o.FormSelect=e("./components/FormSelect"),o.Glyph=e("./components/Glyph"),o.InputGroup=e("./components/InputGroup"),o.InputGroupSection=e("./components/InputGroupSection"),o.Modal=e("./components/Modal"),o.ModalBody=e("./components/ModalBody"),o.ModalFooter=e("./components/ModalFooter"),o.ModalHeader=e("./components/ModalHeader"),o.Pagination=e("./components/Pagination"),o.PasswordInputGroup=e("./components/PasswordInputGroup"),o.Pill=e("./components/Pill"),o.Radio=e("./components/Radio"),o.ResponsiveText=e("./components/ResponsiveText"),o.Row=e("./components/Row"),o.RadioGroup=e("./components/RadioGroup"),o.SegmentedControl=e("./components/SegmentedControl"),o.Spinner=e("./components/Spinner"),o.Table=e("./components/Table")},{"./components/Alert":3,"./components/BlankState":4,"./components/Button":5,"./components/ButtonGroup":6,"./components/Card":7,"./components/Checkbox":8,"./components/Col":9,"./components/Container":10,"./components/Dropdown":11,"./components/EmailInputGroup":12,"./components/FileDragAndDrop":13,"./components/FileUpload":14,"./components/Form":15,"./components/FormField":16,"./components/FormIcon":17,"./components/FormIconField":18,"./components/FormInput":19,"./components/FormLabel":20,"./components/FormNote":21,"./components/FormRow":22,"./components/FormSelect":23,"./components/Glyph":24,"./components/InputGroup":25,"./components/InputGroupSection":26,"./components/Modal":27,"./components/ModalBody":28,"./components/ModalFooter":29,"./components/ModalHeader":30,"./components/Pagination":31,"./components/PasswordInputGroup":32,"./components/Pill":33,"./components/Radio":34,"./components/RadioGroup":35,"./components/ResponsiveText":36,"./components/Row":37,"./components/SegmentedControl":38,"./components/Spinner":39,"./components/Table":40}],2:[function(e,t,o){"use strict";function n(e,t){return e.map(function(e){return e[t]})}var a=[{label:"Alert",value:"alert",className:"octicon octicon-alert"},{label:"Arrow Down",value:"arrow-down",className:"octicon octicon-arrow-down"},{label:"Arrow Left",value:"arrow-left",className:"octicon octicon-arrow-left"},{label:"Arrow Right",value:"arrow-right",className:"octicon octicon-arrow-right"},{label:"Arrow Small-down",value:"arrow-small-down",className:"octicon octicon-arrow-small-down"},{label:"Arrow Small-left",value:"arrow-small-left",className:"octicon octicon-arrow-small-left"},{label:"Arrow Small-right",value:"arrow-small-right",className:"octicon octicon-arrow-small-right"},{label:"Arrow Small-up",value:"arrow-small-up",className:"octicon octicon-arrow-small-up"},{label:"Arrow Up",value:"arrow-up",className:"octicon octicon-arrow-up"},{label:"Microscope",value:"microscope",className:"octicon octicon-microscope"},{label:"Beaker",value:"beaker",className:"octicon octicon-beaker"},{label:"Bell",value:"bell",className:"octicon octicon-bell"},{label:"Book",value:"book",className:"octicon octicon-book"},{label:"Bookmark",value:"bookmark",className:"octicon octicon-bookmark"},{label:"Briefcase",value:"briefcase",className:"octicon octicon-briefcase"},{label:"Broadcast",value:"broadcast",className:"octicon octicon-broadcast"},{label:"Browser",value:"browser",className:"octicon octicon-browser"},{label:"Bug",value:"bug",className:"octicon octicon-bug"},{label:"Calendar",value:"calendar",className:"octicon octicon-calendar"},{label:"Check",value:"check",className:"octicon octicon-check"},{label:"Checklist",value:"checklist",className:"octicon octicon-checklist"},{label:"Chevron Down",value:"chevron-down",className:"octicon octicon-chevron-down"},{label:"Chevron Left",value:"chevron-left",className:"octicon octicon-chevron-left"},{label:"Chevron Right",value:"chevron-right",className:"octicon octicon-chevron-right"},{label:"Chevron Up",value:"chevron-up",className:"octicon octicon-chevron-up"},{label:"Circle Slash",value:"circle-slash",className:"octicon octicon-circle-slash"},{label:"Circuit Board",value:"circuit-board",className:"octicon octicon-circuit-board"},{label:"Clippy",value:"clippy",className:"octicon octicon-clippy"},{label:"Clock",value:"clock",className:"octicon octicon-clock"},{label:"Cloud Download",value:"cloud-download",className:"octicon octicon-cloud-download"},{label:"Cloud Upload",value:"cloud-upload",className:"octicon octicon-cloud-upload"},{label:"Code",value:"code",className:"octicon octicon-code"},{label:"Color Mode",value:"color-mode",className:"octicon octicon-color-mode"},{label:"Comment Add",value:"comment-add",className:"octicon octicon-comment-add"},{label:"Comment",value:"comment",className:"octicon octicon-comment"},{label:"Comment Discussion",value:"comment-discussion",className:"octicon octicon-comment-discussion"},{label:"Credit Card",value:"credit-card",className:"octicon octicon-credit-card"},{label:"Dash",value:"dash",className:"octicon octicon-dash"},{label:"Dashboard",value:"dashboard",className:"octicon octicon-dashboard"},{label:"Database",value:"database",className:"octicon octicon-database"},{label:"Clone",value:"clone",className:"octicon octicon-clone"},{label:"Desktop Download",value:"desktop-download",className:"octicon octicon-desktop-download"},{label:"Device Camera",value:"device-camera",className:"octicon octicon-device-camera"},{label:"Device Camera-video",value:"device-camera-video",className:"octicon octicon-device-camera-video"},{label:"Device Desktop",value:"device-desktop",className:"octicon octicon-device-desktop"},{label:"Device Mobile",value:"device-mobile",className:"octicon octicon-device-mobile"},{label:"Diff",value:"diff",className:"octicon octicon-diff"},{label:"Diff Added",value:"diff-added",className:"octicon octicon-diff-added"},{label:"Diff Ignored",value:"diff-ignored",className:"octicon octicon-diff-ignored"},{label:"Diff Modified",value:"diff-modified",className:"octicon octicon-diff-modified"},{label:"Diff Removed",value:"diff-removed",className:"octicon octicon-diff-removed"},{label:"Diff Renamed",value:"diff-renamed",className:"octicon octicon-diff-renamed"},{label:"Ellipsis",value:"ellipsis",className:"octicon octicon-ellipsis"},{label:"Eye Unwatch",value:"eye-unwatch",className:"octicon octicon-eye-unwatch"},{label:"Eye Watch",value:"eye-watch",className:"octicon octicon-eye-watch"},{label:"Eye",value:"eye",className:"octicon octicon-eye"},{label:"File Binary",value:"file-binary",className:"octicon octicon-file-binary"},{label:"File Code",value:"file-code",className:"octicon octicon-file-code"},{label:"File Directory",value:"file-directory",className:"octicon octicon-file-directory"},{label:"File Media",value:"file-media",className:"octicon octicon-file-media"},{label:"File Pdf",value:"file-pdf",className:"octicon octicon-file-pdf"},{label:"File Submodule",value:"file-submodule",className:"octicon octicon-file-submodule"},{label:"File Symlink-directory",value:"file-symlink-directory",className:"octicon octicon-file-symlink-directory"},{label:"File Symlink-file",value:"file-symlink-file",className:"octicon octicon-file-symlink-file"},{label:"File Text",value:"file-text",className:"octicon octicon-file-text"},{label:"File Zip",value:"file-zip",className:"octicon octicon-file-zip"},{label:"Flame",value:"flame",className:"octicon octicon-flame"},{label:"Fold",value:"fold",className:"octicon octicon-fold"},{label:"Gear",value:"gear",className:"octicon octicon-gear"},{label:"Gift",value:"gift",className:"octicon octicon-gift"},{label:"Gist",value:"gist",className:"octicon octicon-gist"},{label:"Gist Secret",value:"gist-secret",className:"octicon octicon-gist-secret"},{label:"Git Branch-create",value:"git-branch-create",className:"octicon octicon-git-branch-create"},{label:"Git Branch-delete",value:"git-branch-delete",className:"octicon octicon-git-branch-delete"},{label:"Git Branch",value:"git-branch",className:"octicon octicon-git-branch"},{label:"Git Commit",value:"git-commit",className:"octicon octicon-git-commit"},{label:"Git Compare",value:"git-compare",className:"octicon octicon-git-compare"},{label:"Git Merge",value:"git-merge",className:"octicon octicon-git-merge"},{label:"Git Pull-request-abandoned",value:"git-pull-request-abandoned",className:"octicon octicon-git-pull-request-abandoned"},{label:"Git Pull-request",value:"git-pull-request",className:"octicon octicon-git-pull-request"},{label:"Globe",value:"globe",className:"octicon octicon-globe"},{label:"Graph",value:"graph",className:"octicon octicon-graph"},{label:"Heart",value:"heart",className:"octicon octicon-heart"},{label:"History",value:"history",className:"octicon octicon-history"},{label:"Home",value:"home",className:"octicon octicon-home"},{label:"Horizontal Rule",value:"horizontal-rule",className:"octicon octicon-horizontal-rule"},{label:"Hubot",value:"hubot",className:"octicon octicon-hubot"},{label:"Inbox",value:"inbox",className:"octicon octicon-inbox"},{label:"Info",value:"info",className:"octicon octicon-info"},{label:"Issue Closed",value:"issue-closed",className:"octicon octicon-issue-closed"},{label:"Issue Opened",value:"issue-opened",className:"octicon octicon-issue-opened"},{label:"Issue Reopened",value:"issue-reopened",className:"octicon octicon-issue-reopened"},{label:"Jersey",value:"jersey",className:"octicon octicon-jersey"},{label:"Key",value:"key",className:"octicon octicon-key"},{label:"Keyboard",value:"keyboard",className:"octicon octicon-keyboard"},{label:"Law",value:"law",className:"octicon octicon-law"},{label:"Light Bulb",value:"light-bulb",className:"octicon octicon-light-bulb"},{label:"Link",value:"link",className:"octicon octicon-link"},{label:"Link External",value:"link-external",className:"octicon octicon-link-external"},{label:"List Ordered",value:"list-ordered",className:"octicon octicon-list-ordered"},{label:"List Unordered",value:"list-unordered",className:"octicon octicon-list-unordered"},{label:"Location",value:"location",className:"octicon octicon-location"},{label:"Gist Private",value:"gist-private",className:"octicon octicon-gist-private"},{label:"Mirror Private",value:"mirror-private",className:"octicon octicon-mirror-private"},{label:"Git Fork-private",value:"git-fork-private",className:"octicon octicon-git-fork-private"},{label:"Lock",value:"lock",className:"octicon octicon-lock"},{label:"Logo Github",value:"logo-github",className:"octicon octicon-logo-github"},{label:"Mail",value:"mail",className:"octicon octicon-mail"},{label:"Mail Read",value:"mail-read",className:"octicon octicon-mail-read"},{label:"Mail Reply",value:"mail-reply",className:"octicon octicon-mail-reply"},{label:"Mark Github",value:"mark-github",className:"octicon octicon-mark-github"},{label:"Markdown",value:"markdown",className:"octicon octicon-markdown"},{label:"Megaphone",value:"megaphone",className:"octicon octicon-megaphone"},{label:"Mention",value:"mention",className:"octicon octicon-mention"},{label:"Milestone",value:"milestone",className:"octicon octicon-milestone"},{label:"Mirror Public",value:"mirror-public",className:"octicon octicon-mirror-public"},{label:"Mirror",value:"mirror",className:"octicon octicon-mirror"},{label:"Mortar Board",value:"mortar-board",className:"octicon octicon-mortar-board"},{label:"Mute",value:"mute",className:"octicon octicon-mute"},{label:"No Newline",value:"no-newline",className:"octicon octicon-no-newline"},{label:"Octoface",value:"octoface",className:"octicon octicon-octoface"},{label:"Organization",value:"organization",className:"octicon octicon-organization"},{label:"Package",value:"package",className:"octicon octicon-package"},{label:"Paintcan",value:"paintcan",className:"octicon octicon-paintcan"},{label:"Pencil",value:"pencil",className:"octicon octicon-pencil"},{label:"Person Add",value:"person-add",className:"octicon octicon-person-add"},{label:"Person Follow",value:"person-follow",className:"octicon octicon-person-follow"},{label:"Person",value:"person",className:"octicon octicon-person"},{label:"Pin",value:"pin",className:"octicon octicon-pin"},{label:"Plug",value:"plug",className:"octicon octicon-plug"},{label:"Repo Create",value:"repo-create",className:"octicon octicon-repo-create"},{label:"Gist New",value:"gist-new",className:"octicon octicon-gist-new"},{label:"File Directory-create",value:"file-directory-create",className:"octicon octicon-file-directory-create"},{label:"File Add",value:"file-add",className:"octicon octicon-file-add"},{label:"Plus",value:"plus",className:"octicon octicon-plus"},{label:"Primitive Dot",value:"primitive-dot",className:"octicon octicon-primitive-dot"},{label:"Primitive Square",value:"primitive-square",className:"octicon octicon-primitive-square"},{label:"Pulse",value:"pulse",className:"octicon octicon-pulse"},{label:"Question",value:"question",className:"octicon octicon-question"},{label:"Quote",value:"quote",className:"octicon octicon-quote"},{label:"Radio Tower",value:"radio-tower",className:"octicon octicon-radio-tower"},{label:"Repo Delete",value:"repo-delete",className:"octicon octicon-repo-delete"},{label:"Repo",value:"repo",className:"octicon octicon-repo"},{label:"Repo Clone",value:"repo-clone",className:"octicon octicon-repo-clone"},{label:"Repo Force-push",value:"repo-force-push",className:"octicon octicon-repo-force-push"},{label:"Gist Fork",value:"gist-fork",className:"octicon octicon-gist-fork"},{label:"Repo Forked",value:"repo-forked",className:"octicon octicon-repo-forked"},{label:"Repo Pull",value:"repo-pull",className:"octicon octicon-repo-pull"},{label:"Repo Push",value:"repo-push",className:"octicon octicon-repo-push"},{label:"Rocket",value:"rocket",className:"octicon octicon-rocket"},{label:"Rss",value:"rss",className:"octicon octicon-rss"},{label:"Ruby",value:"ruby",className:"octicon octicon-ruby"},{label:"Screen Full",value:"screen-full",className:"octicon octicon-screen-full"},{label:"Screen Normal",value:"screen-normal",className:"octicon octicon-screen-normal"},{label:"Search Save",value:"search-save",className:"octicon octicon-search-save"},{label:"Search",value:"search",className:"octicon octicon-search"},{label:"Server",value:"server",className:"octicon octicon-server"},{label:"Settings",value:"settings",className:"octicon octicon-settings"},{label:"Shield",value:"shield",className:"octicon octicon-shield"},{label:"Log In",value:"log-in",className:"octicon octicon-log-in"},{label:"Sign In",value:"sign-in",className:"octicon octicon-sign-in"},{label:"Log Out",value:"log-out",className:"octicon octicon-log-out"},{label:"Sign Out",value:"sign-out",className:"octicon octicon-sign-out"},{label:"Squirrel",value:"squirrel",className:"octicon octicon-squirrel"},{label:"Star Add",value:"star-add",className:"octicon octicon-star-add"},{label:"Star Delete",value:"star-delete",className:"octicon octicon-star-delete"},{label:"Star",value:"star",className:"octicon octicon-star"},{label:"Stop",value:"stop",className:"octicon octicon-stop"},{label:"Repo Sync",value:"repo-sync",className:"octicon octicon-repo-sync"},{label:"Sync",value:"sync",className:"octicon octicon-sync"},{label:"Tag Remove",value:"tag-remove",className:"octicon octicon-tag-remove"},{label:"Tag Add",value:"tag-add",className:"octicon octicon-tag-add"},{label:"Tag",value:"tag",className:"octicon octicon-tag"},{label:"Telescope",value:"telescope",className:"octicon octicon-telescope"},{label:"Terminal",value:"terminal",className:"octicon octicon-terminal"},{label:"Three Bars",value:"three-bars",className:"octicon octicon-three-bars"},{label:"Thumbsdown",value:"thumbsdown",className:"octicon octicon-thumbsdown"},{label:"Thumbsup",value:"thumbsup",className:"octicon octicon-thumbsup"},{label:"Tools",value:"tools",className:"octicon octicon-tools"},{label:"Trashcan",value:"trashcan",className:"octicon octicon-trashcan"},{label:"Triangle Down",value:"triangle-down",className:"octicon octicon-triangle-down"},{label:"Triangle Left",value:"triangle-left",className:"octicon octicon-triangle-left"},{label:"Triangle Right",value:"triangle-right",className:"octicon octicon-triangle-right"},{label:"Triangle Up",value:"triangle-up",className:"octicon octicon-triangle-up"},{label:"Unfold",value:"unfold",className:"octicon octicon-unfold"},{label:"Unmute",value:"unmute",className:"octicon octicon-unmute"},{label:"Versions",value:"versions",className:"octicon octicon-versions"},{label:"Watch",value:"watch",className:"octicon octicon-watch"},{label:"Remove Close",value:"remove-close",className:"octicon octicon-remove-close"},{label:"X",value:"x",className:"octicon octicon-x"},{label:"Zap",value:"zap",className:"octicon octicon-zap"}],s={};a.forEach(function(e){s[e.value]=e}),t.exports={list:a,keys:n(a,"value"),map:s}},{}],3:[function(e,t,o){(function(o){"use strict";var n="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,a=e("classnames"),s=["danger","error","info","primary","success","warning"];t.exports=n.createClass({displayName:"ElementalAlert",propTypes:{children:n.PropTypes.node.isRequired,className:n.PropTypes.string,type:n.PropTypes.oneOf(s).isRequired},render:function(){var e=a("Alert","Alert--"+this.props.type,this.props.className);return n.createElement("div",{className:e},this.props.children)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],4:[function(e,t,o){(function(e){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},n="undefined"!=typeof window?window.React:"undefined"!=typeof e?e.React:null;t.exports=n.createClass({displayName:"BlankState",propTypes:{children:n.PropTypes.node.isRequired},render:function(){return n.createElement("div",o({className:"BlankState"},this.props))}}),t.exports.Heading=n.createClass({displayName:"BlankStateHeading",propTypes:{children:n.PropTypes.node.isRequired},render:function(){return n.createElement("h2",o({className:"BlankState__heading"},this.props))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],5:[function(e,t,o){(function(o){"use strict";var n="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,a=e("classnames"),s=e("blacklist"),i=["lg","sm","xs"],l=["default","default-primary","default-success","default-warning","default-danger","hollow-primary","hollow-success","hollow-warning","hollow-danger","primary","success","warning","danger","link","link-text","link-cancel","link-delete"];t.exports=n.createClass({displayName:"Button",propTypes:{block:n.PropTypes.bool,className:n.PropTypes.string,href:n.PropTypes.string,isActive:n.PropTypes.bool,size:n.PropTypes.oneOf(i),submit:n.PropTypes.bool,type:n.PropTypes.oneOf(l)},getDefaultProps:function(){return{type:"default"}},render:function(){var e=a("Button","Button--"+this.props.type,this.props.size?"Button--"+this.props.size:null,{"Button--block":this.props.block,"is-active":this.props.isActive},this.props.className),t=s(this.props,"type","size","className");t.className=e;var o="button";return t.type=this.props.submit?"submit":"button",t.href&&(o="a",t.type=null),n.createElement(o,t,this.props.children)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{blacklist:void 0,classnames:void 0}],6:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a=e("classnames"),s="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null;t.exports=s.createClass({displayName:"ButtonGroup",propTypes:{children:s.PropTypes.node.isRequired,className:s.PropTypes.string},render:function(){var e=a("ButtonGroup",this.props.className);return s.createElement("div",n({},this.props,{className:e}))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],7:[function(e,t,o){(function(o){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},s=e("../constants"),i=n(s),l="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null;t.exports=l.createClass({displayName:"Card",propTypes:{children:l.PropTypes.node.isRequired,style:l.PropTypes.object},render:function(){var e={backgroundColor:"white",borderRadius:i["default"].borderRadius.sm,boxShadow:"0 2px 3px rgba(0, 0, 0, 0.075), 0 0 0 1px rgba(0,0,0,0.1)",marginBottom:i["default"].spacing.md,padding:i["default"].spacing.md};return l.createElement("div",a({},this.props,{style:a(e,this.props.style)}))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../constants":41}],8:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a=e("blacklist"),s=e("classnames"),i="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,l=i.createClass({displayName:"Checkbox",propTypes:{className:i.PropTypes.string,disabled:i.PropTypes.bool,focusOnMount:i.PropTypes.bool,indeterminate:i.PropTypes.bool,inline:i.PropTypes.bool,label:i.PropTypes.string,style:i.PropTypes.object,title:i.PropTypes.string},componentDidMount:function(){this.props.focusOnMount&&this.refs.target.focus(),this.setIndeterminate(this.props.indeterminate)},componentWillReceiveProps:function(e){this.setIndeterminate(e.indeterminate)},setIndeterminate:function(e){this.refs.target.indeterminate=e},render:function(){var e=s("Checkbox",{"Checkbox--disabled":this.props.disabled,"Checkbox--inline":this.props.inline},this.props.className),t=a(this.props,"className","label","style","title");return i.createElement("label",{className:e,style:this.props.style,title:this.props.title},i.createElement("input",n({ref:"target",type:"checkbox",className:"Checkbox__input"},t)),this.props.label&&i.createElement("span",{className:"Checkbox__label"},this.props.label))}});t.exports=l}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{blacklist:void 0,classnames:void 0}],9:[function(e,t,o){(function(o){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},s="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,i=n(s),l=e("blacklist"),r=n(l),c=e("../constants"),p=n(c);t.exports=i["default"].createClass({displayName:"Col",propTypes:{basis:i["default"].PropTypes.oneOfType([i["default"].PropTypes.number,i["default"].PropTypes.string]),children:i["default"].PropTypes.node,gutter:i["default"].PropTypes.number,style:i["default"].PropTypes.object,lg:i["default"].PropTypes.string,md:i["default"].PropTypes.string,sm:i["default"].PropTypes.string,xs:i["default"].PropTypes.string},getDefaultProps:function(){return{gutter:p["default"].width.gutter}},getInitialState:function(){return{windowWidth:window.innerWidth}},componentDidMount:function(){window.addEventListener("resize",this.handleResize)},componentWillUnmount:function(){window.removeEventListener("resize",this.handleResize)},handleResize:function(){this.setState({windowWidth:window.innerWidth})},render:function(){var e=this.props,t=e.basis,o=e.gutter,n=e.xs,s=e.sm,l=e.md,c=e.lg,d=this.state.windowWidth,u={minHeight:1,paddingLeft:o/2,paddingRight:o/2};t||n||s||l||c||(u.flex="1 1 auto",u.msFlex="1 1 auto",u.WebkitFlex="1 1 auto"),t?(u.flex="1 0 "+t,u.msFlex="1 0 "+t,u.WebkitFlex="1 0 "+t):d<p["default"].breakpoint.xs?u.width=n:d<p["default"].breakpoint.sm?u.width=s||n:d<p["default"].breakpoint.md?u.width=l||s||n:u.width=c||l||s||n,u.width||(u.width="100%"),u.width in p["default"].fractions&&(u.width=p["default"].fractions[u.width]);var f=r["default"](this.props,"basis","gutter","style","xs","sm","md","lg");return i["default"].createElement("div",a({style:a(u,this.props.style)},f))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../constants":41,blacklist:void 0}],10:[function(e,t,o){(function(o){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},s="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,i=n(s),l=e("blacklist"),r=n(l),c=e("../constants"),p=n(c);t.exports=i["default"].createClass({displayName:"Container",propTypes:{children:i["default"].PropTypes.node.isRequired,clearfix:i["default"].PropTypes.bool,gutter:i["default"].PropTypes.number,maxWidth:i["default"].PropTypes.number,style:i["default"].PropTypes.object},getDefaultProps:function(){return{gutter:p["default"].width.gutter,maxWidth:p["default"].width.container}},render:function(){var e=this.props,t=e.gutter,o=e.maxWidth,n={marginLeft:"auto",marginRight:"auto",paddingLeft:t,paddingRight:t,maxWidth:o},s={clear:"both",display:"table"},l=r["default"](this.props,"gutter","maxWidth","style");return this.props.clearfix?i["default"].createElement("div",a({style:a(n,this.props.style)},l),i["default"].createElement("span",{style:s}),this.props.children,i["default"].createElement("span",{style:s})):i["default"].createElement("div",a({style:a(n,this.props.style)},l))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../constants":41,blacklist:void 0}],11:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,s=e("react-addons-css-transition-group"),i=e("blacklist"),l=e("classnames"),r=e("./Button"),c=27;t.exports=a.createClass({displayName:"Dropdown",propTypes:{alignRight:a.PropTypes.bool,buttonHasDisclosureArrow:a.PropTypes.bool,buttonLabel:a.PropTypes.string,buttonType:a.PropTypes.string,children:a.PropTypes.element,className:a.PropTypes.string,isOpen:a.PropTypes.bool,items:a.PropTypes.array.isRequired,onSelect:a.PropTypes.func},getDefaultProps:function(){return{buttonHasDisclosureArrow:!0,onSelect:function(){}}},getInitialState:function(){return{isOpen:this.props.isOpen||!1}},openDropdown:function(){this.setState({isOpen:!0})},closeDropdown:function(){this.setState({isOpen:!1})},componentWillUpdate:function(e,t){t.isOpen?window.addEventListener("keydown",this.handleKeyDown):window.removeEventListener("keydown",this.handleKeyDown)},handleKeyDown:function(e){e.keyCode===c&&this.closeDropdown()},renderChildren:function(){var e=this;return a.Children.map(this.props.children,function(t){return a.cloneElement(t,{onClick:e.state.isOpen?e.closeDropdown:e.openDropdown,className:l(t.props.className,"Dropdown-toggle")})})},renderButton:function(){var e=this.props.buttonHasDisclosureArrow?a.createElement("span",{className:"disclosure-arrow"}):null;return a.createElement(r,{type:this.props.buttonType,onClick:this.state.isOpen?this.closeDropdown:this.openDropdown,className:"Dropdown-toggle"},this.props.buttonLabel,e)},onClick:function(e){this.setState({isOpen:!this.state.isOpen}),this.props.onSelect(e)},renderDropdownMenu:function(){var e=this;if(!this.state.isOpen)return null;var t=this.props.items.map(function(t,o){var n;return n="header"===t.type?a.createElement("li",{key:"item-"+o,className:"Dropdown-menu__header"},t.label):"divider"===t.type?a.createElement("li",{key:"item-"+o,className:"Dropdown-menu__divider"}):a.createElement("li",{key:"item-"+o,className:"Dropdown-menu__item"},a.createElement("span",{className:"Dropdown-menu__action",onClick:e.onClick.bind(e,t.value)},t.label))});return a.createElement("ul",{key:"Dropdown-menu",className:"Dropdown-menu",role:"menu"},t)},renderDropdownMenuBackground:function(){return this.state.isOpen?a.createElement("div",{className:"Dropdown-menu-backdrop",onClick:this.closeDropdown}):null},render:function(){var e=l("Dropdown",{"is-open":this.state.isOpen,"align-right":this.props.alignRight},this.props.className),t=i(this.props,"alignRight","buttonHasDisclosureArrow","buttonLabel","buttonType","className","isOpen","items");return a.createElement("span",n({className:e},t),a.Children.count(this.props.children)?this.renderChildren():this.renderButton(),a.createElement(s,{transitionName:"Dropdown-menu",transitionEnterTimeout:100,transitionLeaveTimeout:100},this.renderDropdownMenu()),this.renderDropdownMenuBackground())}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./Button":5,blacklist:void 0,classnames:void 0,"react-addons-css-transition-group":void 0}],12:[function(e,t,o){(function(o){"use strict";function n(e){return i.test(e)}var a="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,s=e("classnames"),i=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;t.exports=a.createClass({displayName:"EmailInputGroup",propTypes:{alwaysValidate:a.PropTypes.bool,className:a.PropTypes.string,invalidMessage:a.PropTypes.string,label:a.PropTypes.string,onChange:a.PropTypes.func,required:a.PropTypes.bool,requiredMessage:a.PropTypes.string,value:a.PropTypes.string},getDefaultProps:function(){return{requiredMessage:"Email address is required",invalidMessage:"Please enter a valid email address"}},getInitialState:function(){return{isValid:!0,validationIsActive:this.props.alwaysValidate}},componentDidMount:function(){this.state.validationIsActive&&this.validateInput(this.props.value)},componentWillReceiveProps:function(e){if(this.state.validationIsActive){if(e.value!==this.props.value&&e.value!==this._lastChangeValue&&!e.alwaysValidate)return this.setState({isValid:!0,validationIsActive:!1});this.validateInput(e.value)}},handleChange:function(e){this._lastChangeValue=e.target.value,
this.props.onChange&&this.props.onChange(e)},handleBlur:function(){this.props.alwaysValidate||this.setState({validationIsActive:!1}),this.validateInput(this.props.value)},validateInput:function(e){var t={isValid:!0};(e.length&&!n(e)||!e.length&&this.props.required)&&(t.isValid=!1),t.isValid||(t.validationIsActive=!0),this.setState(t)},render:function(){var e;this.state.isValid||(e=a.createElement("div",{className:"form-validation is-invalid"},this.props.value.length?this.props.invalidMessage:this.props.requiredMessage));var t=s("FormField",{"is-invalid":!this.state.isValid},this.props.className),o=this.props.label?a.createElement("label",{className:"FormLabel",htmlFor:"inputEmail"},this.props.label):null;return a.createElement("div",{className:t},o,a.createElement("input",{onChange:this.handleChange,onBlur:this.handleBlur,value:this.props.value,type:"email",className:"FormInput",placeholder:"Enter email",id:"inputEmail"}),e)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],13:[function(e,t,o){(function(o){"use strict";var n="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,a=e("classnames"),s=n.createClass({displayName:"Dropzone",propTypes:{className:n.PropTypes.string,label:n.PropTypes.string,labelActive:n.PropTypes.string,onDrop:n.PropTypes.func.isRequired},getDefaultProps:function(){return{label:"Drag Files Here",labelActive:"Drop to Upload"}},getInitialState:function(){return{isDragActive:!1}},onDragLeave:function(){this.setState({isDragActive:!1})},onDragOver:function(e){e.preventDefault(),e.dataTransfer.dropEffect="copy",this.setState({isDragActive:!0})},onDrop:function(e){e.preventDefault(),this.setState({isDragActive:!1});var t;e.dataTransfer?t=e.dataTransfer.files:e.target&&(t=e.target.files),this.props.onDrop&&(t=Array.prototype.slice.call(t),this.props.onDrop(t))},onClick:function(){this.refs.fileInput.click()},render:function(){var e=a("FileDragAndDrop",{active:this.state.isDragActive},this.props.className);return n.createElement("button",{className:e,onClick:this.onClick,onDragLeave:this.onDragLeave,onDragOver:this.onDragOver,onDrop:this.onDrop},n.createElement("input",{style:{display:"none"},type:"file",multiple:!0,ref:"fileInput",onChange:this.onDrop}),n.createElement("div",{className:"FileDragAndDrop__label"},this.state.isDragActive?this.props.labelActive:this.props.label),this.props.children)}});t.exports=s}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],14:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,s=e("blacklist"),i=e("./Button"),l=e("./Spinner");t.exports=a.createClass({displayName:"FileUpload",propTypes:{buttonLabelChange:a.PropTypes.string,buttonLabelInitial:a.PropTypes.string,disabled:a.PropTypes.bool,file:a.PropTypes.object,onChange:a.PropTypes.func},getDefaultProps:function(){return{buttonLabelInitial:"Upload File",buttonLabelChange:"Change File"}},getInitialState:function(){return{file:{},loading:!1}},componentDidMount:function(){this.refs.fileInput.addEventListener("click",function(){this.value=""},!1)},triggerFileBrowser:function(){this.refs.fileInput.click()},handleChange:function(e){var t=this,o=new FileReader,n=e.target.files[0];o.readAsDataURL(n),o.onloadstart=function(){console.time("onLoad"),t.setState({loading:!0})},o.onloadend=function(e){console.timeEnd("onLoad"),t.setState({loading:!1,file:n,dataURI:e.target.result})}},cancelUpload:function(){this.setState({dataURI:!1,file:{}})},render:function(){var e=this.state,t=e.dataURI,o=e.file,r=s(this.props,"buttonClassChange","buttonClassInitial","buttonLabelChange","buttonLabelInitial","disabled","file","onChange"),c=a.createElement(i,{onClick:this.triggerFileBrowser,disabled:this.props.disabled||this.state.loading},this.state.loading&&a.createElement(l,null),this.props.buttonLabelInitial);return t&&(c=a.createElement("div",{className:"FileUpload"},a.createElement("div",{className:"FileUpload__image"},a.createElement("img",{className:"FileUpload__image-src",src:t})),a.createElement("div",{className:"FileUpload__content"},a.createElement("div",{className:"FileUpload__message"},o.name," (",Math.round(o.size/1024),"Kb)"),a.createElement("div",{className:"FileUpload__buttons"},a.createElement(i,{onClick:this.triggerFileBrowser,disabled:this.state.loading},this.state.loading&&a.createElement(l,null),this.props.buttonLabelChange),a.createElement(i,{onClick:this.cancelUpload,type:"link-cancel",disabled:this.state.loading},"Cancel"))))),a.createElement("div",null,c,a.createElement("input",n({style:{display:"none"},type:"file",ref:"fileInput",onChange:this.handleChange},r)))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./Button":5,"./Spinner":39,blacklist:void 0}],15:[function(e,t,o){(function(o){"use strict";var n=e("blacklist"),a=e("classnames"),s="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null;t.exports=s.createClass({displayName:"Form",propTypes:{children:s.PropTypes.node.isRequired,className:s.PropTypes.string,component:s.PropTypes.oneOfType([s.PropTypes.element,s.PropTypes.string]),type:s.PropTypes.oneOf(["basic","horizontal","inline"])},getDefaultProps:function(){return{component:"form",type:"basic"}},render:function(){var e=n(this.props,"children","type");return e.className=a("Form","Form--"+this.props.type,this.props.className),s.createElement(this.props.component,e,this.props.children)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{blacklist:void 0,classnames:void 0}],16:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,s=e("blacklist"),i=e("classnames");t.exports=a.createClass({displayName:"FormField",propTypes:{className:a.PropTypes.string,htmlFor:a.PropTypes.string,id:a.PropTypes.string,label:a.PropTypes.string,offsetAbsentLabel:a.PropTypes.bool,width:a.PropTypes.oneOf(["one-half","two-quarters","three-sixths","one-quarter","three-quarters","one-third","two-sixths","two-thirds","four-sixths","one-fifth","two-fifths","three-fifths","four-fifths","one-sixth","five-sixths"])},render:function(){var e=i("FormField",{"offset-absent-label":this.props.offsetAbsentLabel},this.props.width,this.props.className),t=s(this.props,"className","label","offsetAbsentLabel","width"),o=this.props.label?a.createElement("label",{className:"FormLabel",htmlFor:this.props.id||this.props.htmlFor},this.props.label):null;return a.createElement("div",n({className:e},t),o,this.props.children)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{blacklist:void 0,classnames:void 0}],17:[function(e,t,o){(function(o){"use strict";var n="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,a=e("classnames"),s=e("./Spinner"),i=e("../Octicons").map;t.exports=n.createClass({displayName:"FormIcon",propTypes:{className:n.PropTypes.string,color:n.PropTypes.oneOf(["danger","default","muted","primary","success","warning"]),fill:n.PropTypes.oneOf(["danger","default","muted","primary","success","warning"]),icon:n.PropTypes.string,isLoading:n.PropTypes.bool,type:n.PropTypes.string},render:function(){var e=a("IconField__icon",i[this.props.icon].className,this.props.fill?"IconField__icon-fill--"+this.props.fill:null,this.props.type?"IconField__icon-color--"+this.props.type:null,this.props.className),t=this.props.isLoading?n.createElement(s,{size:"sm"}):n.createElement("div",{className:e});return t}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../Octicons":2,"./Spinner":39,classnames:void 0}],18:[function(e,t,o){(function(o){"use strict";var n="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,a=e("blacklist"),s=e("classnames"),i=e("./FormField"),l=e("./Spinner"),r=e("../Octicons").map,c=e("../Octicons").keys,p=["danger","default","primary","success","warning"];t.exports=n.createClass({displayName:"FormIconField",propTypes:{className:n.PropTypes.string,iconColor:n.PropTypes.oneOf(p),iconFill:n.PropTypes.oneOf(p),iconIsLoading:n.PropTypes.bool,iconKey:n.PropTypes.oneOf(c).isRequired,iconPosition:n.PropTypes.oneOf(["left","right"])},getDefaultProps:function(){return{iconPosition:"left"}},render:function(){var e=a(this.props,"children","iconPosition","iconKey","iconFill","iconColor","iconIsLoading"),t=s("IconField",{"has-fill-icon":this.props.iconFill,"is-loading-icon":this.props.iconIsLoading},this.props.iconFill?"field-context-"+this.props.iconFill:null,this.props.iconColor?"field-context-"+this.props.iconColor:null,this.props.iconPosition),o=s("IconField__icon",this.props.iconFill?"IconField__icon-fill--"+this.props.iconFill:null,this.props.iconColor?"IconField__icon-color--"+this.props.iconColor:null,r[this.props.iconKey].className),c=this.props.iconIsLoading?n.createElement(l,{size:"sm"}):n.createElement("span",{className:o});return n.createElement(i,e,n.createElement("div",{className:t},this.props.children,c))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../Octicons":2,"./FormField":16,"./Spinner":39,blacklist:void 0,classnames:void 0}],19:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,s=e("blacklist"),i=e("classnames");t.exports=a.createClass({displayName:"FormInput",propTypes:{className:a.PropTypes.string,disabled:a.PropTypes.bool,focusOnMount:a.PropTypes.bool,href:a.PropTypes.string,id:a.PropTypes.string,multiline:a.PropTypes.bool,name:a.PropTypes.string,noedit:a.PropTypes.bool,onChange:a.PropTypes.func,size:a.PropTypes.oneOf(["lg","sm","xs"]),type:a.PropTypes.string,value:a.PropTypes.oneOfType([a.PropTypes.number,a.PropTypes.string])},getDefaultProps:function(){return{type:"text"}},componentDidMount:function(){},focus:function(){},render:function(){var e=i({"FormInput-noedit":this.props.noedit,"FormInput-noedit--multiline":this.props.noedit&&this.props.multiline,FormInput:!this.props.noedit},this.props.size?"FormInput--"+this.props.size:null,this.props.className),t=n(s(this.props,"className"),{className:e,id:this.props.id||this.props.name}),o="input";return this.props.noedit&&this.props.href?(o="a",t.type=null,t.children=t.children||t.value):this.props.noedit?(o="div",t.type=null,t.children=t.children||t.value):this.props.multiline&&(o="textarea"),a.createElement(o,t)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{blacklist:void 0,classnames:void 0}],20:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,s=e("blacklist"),i=e("classnames");t.exports=a.createClass({displayName:"FormLabel",propTypes:{className:a.PropTypes.string,htmlFor:a.PropTypes.string,id:a.PropTypes.string,style:a.PropTypes.object,verticalAlign:a.PropTypes.oneOf(["baseline","bottom","inherit","initial","middle","sub","super","text-bottom","text-top","top"])},render:function(){var e,t=i("FormLabel",this.props.className),o=s(this.props,"htmlFor","id","className","style");return this.props.verticalAlign&&(e={verticalAlign:this.props.verticalAlign}),a.createElement("label",n({className:t,htmlFor:this.props.htmlFor||this.props.id,style:e||this.props.style},o),this.props.children)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{blacklist:void 0,classnames:void 0}],21:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,s=e("blacklist"),i=e("classnames"),l=["default","primary","success","warning","danger"];t.exports=a.createClass({displayName:"FormNote",propTypes:{className:a.PropTypes.string,note:a.PropTypes.string,type:a.PropTypes.oneOf(l)},getDefaultProps:function(){return{type:"default"}},render:function(){var e=i("FormNote",this.props.type?"FormNote--"+this.props.type:null,this.props.className),t=s(this.props,"className","note","type");return a.createElement("div",n({className:e,dangerouslySetInnerHTML:this.props.note?{__html:this.props.note}:null},t),this.props.children)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{blacklist:void 0,classnames:void 0}],22:[function(e,t,o){(function(o){"use strict";var n="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,a=e("classnames");t.exports=n.createClass({displayName:"FormRow",propTypes:{className:n.PropTypes.string},render:function(){var e=a("FormRow",this.props.className);return n.createElement("div",{className:e},this.props.children)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],23:[function(e,t,o){(function(o){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},s=e("blacklist"),i=n(s),l=e("classnames"),r=n(l),c="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,p=n(c),d=e("../icons"),u=n(d);t.exports=p["default"].createClass({displayName:"FormSelect",propTypes:{alwaysValidate:p["default"].PropTypes.bool,className:p["default"].PropTypes.string,disabled:p["default"].PropTypes.bool,firstOption:p["default"].PropTypes.string,htmlFor:p["default"].PropTypes.string,id:p["default"].PropTypes.string,label:p["default"].PropTypes.string,onChange:p["default"].PropTypes.func.isRequired,options:p["default"].PropTypes.arrayOf(p["default"].PropTypes.shape({label:p["default"].PropTypes.string,value:p["default"].PropTypes.string})).isRequired,prependEmptyOption:p["default"].PropTypes.bool,required:p["default"].PropTypes.bool,requiredMessage:p["default"].PropTypes.string,value:p["default"].PropTypes.string},getDefaultProps:function(){return{requiredMessage:"This field is required"}},getInitialState:function(){return{isValid:!0,validationIsActive:this.props.alwaysValidate}},componentDidMount:function(){this.state.validationIsActive&&this.validateInput(this.props.value)},componentWillReceiveProps:function(e){if(this.state.validationIsActive){if(e.value!==this.props.value&&e.value!==this._lastChangeValue&&!e.alwaysValidate)return this.setState({isValid:!0,validationIsActive:!1});this.validateInput(e.value)}},handleChange:function(e){this._lastChangeValue=e.target.value,this.props.onChange&&this.props.onChange(e.target.value)},handleBlur:function(){this.props.alwaysValidate||this.setState({validationIsActive:!1}),this.validateInput(this.props.value)},validateInput:function(e){var t={isValid:!0};this.props.required&&(!e||e&&!e.length)&&(t.isValid=!1),t.isValid||(t.validationIsActive=!0),this.setState(t)},renderIcon:function(e){var t=r["default"]("FormSelect__arrows",{"FormSelect__arrows--disabled":this.props.disabled});return p["default"].createElement("span",{dangerouslySetInnerHTML:{__html:e},className:t})},render:function(){var e=i["default"](this.props,"prependEmptyOption","firstOption","alwaysValidate","htmlFor","id","label","onChange","options","required","requiredMessage","className"),t=r["default"]("FormField",{"is-invalid":!this.state.isValid},this.props.className),o=void 0;this.state.isValid||(o=p["default"].createElement("div",{className:"form-validation is-invalid"},this.props.requiredMessage));var n=this.props.htmlFor||this.props.id,s=this.props.label?p["default"].createElement("label",{className:"FormLabel",htmlFor:n},this.props.label):null,l=this.props.options.map(function(e,t){return p["default"].createElement("option",{key:"option-"+t,value:e.value},e.label)});return(this.props.prependEmptyOption||this.props.firstOption)&&l.unshift(p["default"].createElement("option",{key:"option-blank",value:""},this.props.firstOption?this.props.firstOption:"Select...")),p["default"].createElement("div",{className:t},s,p["default"].createElement("select",a({className:"FormInput FormSelect",id:n,onChange:this.handleChange,onBlur:this.handleBlur},e),l),this.renderIcon(u["default"].selectArrows),o)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../icons":42,blacklist:void 0,classnames:void 0}],24:[function(e,t,o){(function(o){"use strict";var n="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,a=e("classnames"),s=e("../Octicons").map,i=e("../Octicons").keys,l=n.createClass({displayName:"Glyph",propTypes:{className:n.PropTypes.string,icon:n.PropTypes.oneOf(i),type:n.PropTypes.oneOf(["danger","default","muted","primary","success","warning"])},render:function(){var e=a("Glyph__icon",s[this.props.icon].className,this.props.type?"IconField__icon-color--"+this.props.type:null,this.props.className);return n.createElement("i",{className:e})}});t.exports=l,t.exports.names=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../Octicons":2,classnames:void 0}],25:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,s=e("classnames");t.exports=a.createClass({displayName:"InputGroup",propTypes:{className:a.PropTypes.string,contiguous:a.PropTypes.bool},render:function(){var e=s("InputGroup",{"InputGroup--contiguous":this.props.contiguous},this.props.className);return a.createElement("div",n({},this.props,{className:e}))}}),t.exports.Section=e("./InputGroupSection")}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./InputGroupSection":26,classnames:void 0}],26:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,s=e("classnames");t.exports=a.createClass({displayName:"InputGroupSection",propTypes:{className:a.PropTypes.string,grow:a.PropTypes.bool},render:function(){var e=s("InputGroup_section",{"InputGroup_section--grow":this.props.grow},this.props.className);return a.createElement("div",n({},this.props,{className:e}))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],27:[function(e,t,o){(function(o){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},s="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,i=n(s),l=e("react-dom"),r=n(l),c=e("react-addons-css-transition-group"),p=n(c),d=e("blacklist"),u=n(d),f=e("classnames"),m=n(f),h=i["default"].createClass({displayName:"TransitionPortal",portalElement:null,render:function(){return null},componentDidMount:function(){var e=document.createElement("div");document.body.appendChild(e),this.portalElement=e,this.componentDidUpdate()},componentWillUnmount:function(){document.body.removeChild(this.portalElement)},componentDidUpdate:function(){r["default"].render(i["default"].createElement(p["default"],this.props,this.props.children),this.portalElement)}});t.exports=i["default"].createClass({displayName:"Modal",propTypes:{backdropClosesModal:i["default"].PropTypes.bool,className:i["default"].PropTypes.string,isOpen:i["default"].PropTypes.bool,onCancel:i["default"].PropTypes.func},componentWillReceiveProps:function(e){e.isOpen?(window.addEventListener("keydown",this.handleKeyDown),document.body.style.overflow="hidden"):(window.removeEventListener("keydown",this.handleKeyDown),document.body.style.overflow=null)},handleKeyDown:function(e){27===e.keyCode&&this.props.onCancel()},handleModalClick:function(e){e.target.dataset.modal&&this.props.onCancel()},renderDialog:function(){return this.props.isOpen?i["default"].createElement("div",{className:"Modal-dialog"},i["default"].createElement("div",{className:"Modal-content"},this.props.children)):void 0},renderBackdrop:function(){return this.props.isOpen?i["default"].createElement("div",{className:"Modal-backdrop",onClick:this.props.backdropClosesModal?this.props.onCancel:null}):void 0},render:function(){var e=m["default"]("Modal",{"is-open":this.props.isOpen},this.props.className),t=u["default"](this.props,"backdropClosesModal","className","isOpen","onCancel");return i["default"].createElement("div",null,i["default"].createElement(h,a({},t,{"data-modal":"true",className:e,onClick:this.handleModalClick,transitionName:"Modal-dialog",transitionEnterTimeout:260,transitionLeaveTimeout:140,component:"div"}),this.renderDialog()),i["default"].createElement(h,{transitionName:"Modal-background",transitionEnterTimeout:140,transitionLeaveTimeout:240,component:"div"},this.renderBackdrop()))}}),t.exports.Body=e("./ModalBody"),t.exports.Footer=e("./ModalFooter"),t.exports.Header=e("./ModalHeader")}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./ModalBody":28,"./ModalFooter":29,"./ModalHeader":30,blacklist:void 0,classnames:void 0,"react-addons-css-transition-group":void 0,"react-dom":void 0}],28:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a=e("classnames"),s="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null;t.exports=s.createClass({displayName:"ModalBody",propTypes:{children:s.PropTypes.node.isRequired,className:s.PropTypes.string},render:function(){var e=a("Modal__body",this.props.className);return s.createElement("div",n({},this.props,{className:e}))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],29:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a=e("classnames"),s="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null;t.exports=s.createClass({displayName:"ModalFooter",propTypes:{children:s.PropTypes.node.isRequired,className:s.PropTypes.string},render:function(){var e=a("Modal__footer",this.props.className);return s.createElement("div",n({},this.props,{className:e}))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],30:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a=e("classnames"),s="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null;t.exports=s.createClass({displayName:"ModalHeader",propTypes:{children:s.PropTypes.node,className:s.PropTypes.string,onClose:s.PropTypes.func,showCloseButton:s.PropTypes.bool,text:s.PropTypes.string},render:function(){var e=a("Modal__header",this.props.className),t=this.props.showCloseButton?s.createElement("button",{type:"button",onClick:this.props.onClose,className:"Modal__header__close"}):null,o=this.props.text?s.createElement("h4",{className:"Modal__header__text"},this.props.text):null;return s.createElement("div",n({},this.props,{className:e}),t,o,this.props.children)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],31:[function(e,t,o){(function(o){"use strict";var n="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,a=e("classnames");t.exports=n.createClass({displayName:"Pagination",propTypes:{className:n.PropTypes.string,currentPage:n.PropTypes.number.isRequired,onPageSelect:n.PropTypes.func,pageSize:n.PropTypes.number.isRequired,plural:n.PropTypes.string,singular:n.PropTypes.string,style:n.PropTypes.object,total:n.PropTypes.number.isRequired,limit:n.PropTypes.number},renderCount:function(){var e="",t=this.props,o=t.currentPage,a=t.pageSize,s=t.plural,i=t.singular,l=t.total;if(l)if(l>a){var r=a*(o-1)+1,c=Math.min(r+a-1,l);e="Showing "+r+" to "+c+" of "+l}else e="Showing "+l,l>1&&s?e+=" "+s:1===l&&i&&(e+=" "+i);else e="No "+(s||"records");return n.createElement("div",{className:"Pagination__count"},e)},onPageSelect:function(e){this.props.onPageSelect&&this.props.onPageSelect(e)},renderPages:function(){var e=this;if(this.props.total<=this.props.pageSize)return null;var t=[],o=this.props,s=o.currentPage,i=o.pageSize,l=o.total,r=o.limit,c=Math.ceil(l/i),p=0,d=c;r&&c>r&&(r=Math.floor(r/2),p=s-r-1,d=s+r,0>p&&(d-=p,p=0),d>c&&(p=c-2*r-1,d=c)),p>0&&t.push(n.createElement("button",{key:"page_start",className:"Pagination__list__item",onClick:function(){return e.onPageSelect(1)}},"..."));for(var u=function(o){var i=o+1,l=i===s,r=a("Pagination__list__item",{"is-selected":l});t.push(n.createElement("button",{key:"page_"+i,className:r,onClick:function(){return e.onPageSelect(i)}},i))},f=p;d>f;f++)u(f);return c>d&&t.push(n.createElement("button",{key:"page_end",className:"Pagination__list__item",onClick:function(){return e.onPageSelect(c)}},"...")),n.createElement("div",{className:"Pagination__list"},t)},render:function(){var e=a("Pagination",this.props.className);return n.createElement("div",{className:e,style:this.props.style},this.renderCount(),this.renderPages())}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],32:[function(e,t,o){(function(o){"use strict";function n(e){return e.length>=8}var a="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,s=e("classnames");t.exports=a.createClass({displayName:"PasswordInputGroup",propTypes:{alwaysValidate:a.PropTypes.bool,className:a.PropTypes.string,validatePassword:a.PropTypes.func,invalidMessage:a.PropTypes.string,label:a.PropTypes.string,onChange:a.PropTypes.func,required:a.PropTypes.bool,requiredMessage:a.PropTypes.string,value:a.PropTypes.string},getDefaultProps:function(){return{validatePassword:n,requiredMessage:"Password is required",invalidMessage:"Password must be at least 8 characters in length"}},getInitialState:function(){return{isValid:!0,validationIsActive:this.props.alwaysValidate}},componentDidMount:function(){this.state.validationIsActive&&this.validateInput(this.props.value)},componentWillReceiveProps:function(e){if(this.state.validationIsActive){if(e.value!==this.props.value&&e.value!==this._lastChangeValue&&!e.alwaysValidate)return this.setState({isValid:!0,validationIsActive:!1});this.validateInput(e.value)}},handleChange:function(e){this._lastChangeValue=e.target.value,this.props.onChange&&this.props.onChange(e)},handleBlur:function(){this.props.alwaysValidate||this.setState({validationIsActive:!1}),this.validateInput(this.props.value)},validateInput:function(e){var t={isValid:!0};(e.length&&!this.props.validatePassword(e)||!e.length&&this.props.required)&&(t.isValid=!1),t.isValid||(t.validationIsActive=!0),this.setState(t)},render:function(){var e;this.state.isValid||(e=a.createElement("div",{className:"form-validation is-invalid"},this.props.value.length?this.props.invalidMessage:this.props.requiredMessage));var t=s("FormField",{"is-invalid":!this.state.isValid},this.props.className),o=this.props.label?a.createElement("label",{className:"FormLabel",htmlFor:"inputPassword"},this.props.label):null;return a.createElement("div",{className:t},o,a.createElement("input",{onChange:this.handleChange,onBlur:this.handleBlur,value:this.props.value,type:"password",className:"FormInput",placeholder:"Enter password",id:"inputPassword"}),e)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],33:[function(e,t,o){(function(o){"use strict";var n="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,a=e("blacklist"),s=e("classnames"),i=["danger","default","info","primary","success","warning","danger-inverted","default-inverted","info-inverted","primary-inverted","success-inverted","warning-inverted"];t.exports=n.createClass({displayName:"Pill",propTypes:{className:n.PropTypes.string,label:n.PropTypes.string.isRequired,onClear:n.PropTypes.func,onClick:n.PropTypes.func,type:n.PropTypes.oneOf(i)},getDefaultProps:function(){return{type:"default"}},renderClearButton:function(){return this.props.onClear?n.createElement("button",{type:"button",onClick:this.props.onClear,className:"Pill__clear"},"×"):null},render:function(){var e=s("Pill","Pill--"+this.props.type,this.props.className),t=a(this.props,"className","label","onClear","onClick","type");return t.className=e,n.createElement("div",t,n.createElement("button",{type:"button",onClick:this.props.onClick,className:"Pill__label"},this.props.label),this.renderClearButton())}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{blacklist:void 0,classnames:void 0}],34:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a=e("blacklist"),s=e("classnames"),i="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,l=i.createClass({displayName:"Radio",propTypes:{className:i.PropTypes.string,disabled:i.PropTypes.bool,inline:i.PropTypes.bool,label:i.PropTypes.string},render:function(){var e=s("Radio",{"Radio--disabled":this.props.disabled,"Radio--inline":this.props.inline},this.props.className),t=a(this.props,"className","label");return i.createElement("label",{className:e},i.createElement("input",n({type:"radio",className:"Radio__input"},t)),this.props.label&&i.createElement("span",{className:"Radio__label"},this.props.label))}});t.exports=l}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{blacklist:void 0,classnames:void 0}],35:[function(e,t,o){(function(o){"use strict";var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},a="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,s=e("blacklist"),i=e("classnames");
t.exports=a.createClass({displayName:"RadioGroup",propTypes:{alwaysValidate:a.PropTypes.bool,className:a.PropTypes.string,inline:a.PropTypes.bool,label:a.PropTypes.string,onChange:a.PropTypes.func.isRequired,options:a.PropTypes.array.isRequired,required:a.PropTypes.bool,requiredMessage:a.PropTypes.string,value:a.PropTypes.string},getDefaultProps:function(){return{requiredMessage:"This field is required"}},getInitialState:function(){return{isValid:!0,validationIsActive:this.props.alwaysValidate}},componentDidMount:function(){this.state.validationIsActive&&this.validateInput(this.props.value)},componentWillReceiveProps:function(e){if(this.state.validationIsActive){if(e.value!==this.props.value&&e.value!==this._lastChangeValue&&!e.alwaysValidate)return this.setState({isValid:!0,validationIsActive:!1});this.validateInput(e.value)}},handleChange:function(e){this._lastChangeValue=e.target.value,this.props.onChange&&this.props.onChange(e.target.value)},handleBlur:function(){this.props.alwaysValidate||this.setState({validationIsActive:!1}),this.validateInput(this.props.value)},validateInput:function(e){var t={isValid:!0};this.props.required&&(!e||e&&!e.length)&&(t.isValid=!1),t.isValid||(t.validationIsActive=!0),this.setState(t)},render:function(){var e,t=this,o=s(this.props,"alwaysValidate","label","onChange","options","required","requiredMessage","value"),l=i("FormField",{"is-invalid":!this.state.isValid},this.props.className);this.state.isValid||(e=a.createElement("div",{className:"form-validation is-invalid"},this.props.requiredMessage));var r=this.props.label?a.createElement("label",{className:"FormLabel"},this.props.label):null,c=this.props.options.map(function(e,o){return a.createElement("label",{key:"radio-"+o,className:"Radio"},a.createElement("input",{value:e.value,type:"radio",onChange:t.handleChange,onBlur:t.handleBlur,name:t.props.name,className:"Radio__input"}),a.createElement("span",{className:"Radio__label"},e.label))});return this.props.inline&&(c=a.createElement("div",{className:"inline-controls"},c)),a.createElement("div",n({className:l},o),r,c,e)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{blacklist:void 0,classnames:void 0}],36:[function(e,t,o){(function(o){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}var a="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,s=n(a),i=e("blacklist"),l=n(i),r=e("../constants"),c=n(r);t.exports=s["default"].createClass({displayName:"ResponsiveText",propTypes:{hiddenLG:s["default"].PropTypes.string,hiddenMD:s["default"].PropTypes.string,hiddenSM:s["default"].PropTypes.string,hiddenXS:s["default"].PropTypes.string,visibleLG:s["default"].PropTypes.string,visibleMD:s["default"].PropTypes.string,visibleSM:s["default"].PropTypes.string,visibleXS:s["default"].PropTypes.string},getInitialState:function(){return{windowWidth:window.innerWidth}},componentDidMount:function(){window.addEventListener("resize",this.handleResize)},componentWillUnmount:function(){window.removeEventListener("resize",this.handleResize)},handleResize:function(){this.setState({windowWidth:window.innerWidth})},render:function(){var e=this.props,t=e.hiddenXS,o=e.hiddenSM,n=e.hiddenMD,a=e.hiddenLG,i=e.visibleXS,r=e.visibleSM,p=e.visibleMD,d=e.visibleLG,u=this.state.windowWidth,f=void 0;f=u<c["default"].breakpoint.xs?i||o||n||a:u<c["default"].breakpoint.sm?t||r||n||a:u<c["default"].breakpoint.md?t||o||p||a:t||o||n||d;var m=l["default"](this.props,{hiddenXS:!0,hiddenSM:!0,hiddenMD:!0,hiddenLG:!0,visibleXS:!0,visibleSM:!0,visibleMD:!0,visibleLG:!0});return s["default"].createElement("span",m,f)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../constants":41,blacklist:void 0}],37:[function(e,t,o){(function(o){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},s="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,i=n(s),l=e("blacklist"),r=n(l),c=e("classnames"),p=n(c),d=e("../constants"),u=n(d);t.exports=i["default"].createClass({displayName:"Row",propTypes:{children:i["default"].PropTypes.node.isRequired,className:i["default"].PropTypes.string,gutter:i["default"].PropTypes.number,style:i["default"].PropTypes.object},getDefaultProps:function(){return{gutter:u["default"].width.gutter}},render:function(){var e=this.props.gutter,t={display:"flex",flexWrap:"wrap",msFlexWrap:"wrap",WebkitFlexWrap:"wrap",marginLeft:e/-2,marginRight:e/-2},o=p["default"]("Row",this.props.className),n=r["default"](this.props,"className","gutter","style");return i["default"].createElement("div",a({},n,{style:a(t,this.props.style),className:o}))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../constants":41,blacklist:void 0,classnames:void 0}],38:[function(e,t,o){(function(o){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}var a=e("classnames"),s=n(a),i="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,l=n(i);t.exports=l["default"].createClass({displayName:"SegmentedControl",propTypes:{className:l["default"].PropTypes.string,equalWidthSegments:l["default"].PropTypes.bool,onChange:l["default"].PropTypes.func.isRequired,options:l["default"].PropTypes.array.isRequired,type:l["default"].PropTypes.oneOf(["default","muted","danger","info","primary","success","warning"]),value:l["default"].PropTypes.string},getDefaultProps:function(){return{type:"default"}},onChange:function(e){this.props.onChange(e)},render:function(){var e=this,t=s["default"]("SegmentedControl","SegmentedControl--"+this.props.type,{"SegmentedControl--equal-widths":this.props.equalWidthSegments},this.props.className),o=this.props.options.map(function(t){var o=s["default"]("SegmentedControl__button",{"is-selected":t.value===e.props.value});return l["default"].createElement("span",{key:"option-"+t.value,className:"SegmentedControl__item"},l["default"].createElement("button",{type:"button",onClick:e.onChange.bind(e,t.value),className:o},t.label))});return l["default"].createElement("div",{className:t},o)}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],39:[function(e,t,o){(function(o){"use strict";var n="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,a=e("classnames");t.exports=n.createClass({displayName:"Spinner",propTypes:{className:n.PropTypes.string,size:n.PropTypes.oneOf(["sm","md","lg"]),type:n.PropTypes.oneOf(["default","primary","inverted"])},getDefaultProps:function(){return{type:"default",size:"sm"}},render:function(){var e=a("Spinner","Spinner--"+this.props.type,"Spinner--"+this.props.size,this.props.className);return n.createElement("div",{className:e},n.createElement("span",{className:"Spinner_dot Spinner_dot--first"}),n.createElement("span",{className:"Spinner_dot Spinner_dot--second"}),n.createElement("span",{className:"Spinner_dot Spinner_dot--third"}))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],40:[function(e,t,o){(function(o){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},s=e("classnames"),i=n(s),l="undefined"!=typeof window?window.React:"undefined"!=typeof o?o.React:null,r=n(l);t.exports=r["default"].createClass({displayName:"Table",propTypes:{children:r["default"].PropTypes.any,className:r["default"].PropTypes.string},render:function(){var e=i["default"]("Table",this.props.className);return r["default"].createElement("table",a({className:e},this.props))}})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{classnames:void 0}],41:[function(e,t,o){"use strict";function n(e){return 100*e+"%"}function a(e){for(var t=2;20>=t;t++)t>e&&(o.fractions[e+"/"+t]=n(e/t))}o.breakpoint={xs:480,sm:768,md:992,lg:1200},o.borderRadius={xs:2,sm:4,md:8,lg:16,xl:32},o.color={appDanger:"#d64242",appInfo:"#56cdfc",appPrimary:"#1385e5",appSuccess:"#34c240",appWarning:"#fa9f47",brandPrimary:"#31adb8"},o.spacing={xs:5,sm:10,md:20,lg:40,xl:80},o.width={container:1170,gutter:20},o.fractions={};for(var s=1;19>=s;s++)a(s)},{}],42:[function(e,t,o){"use strict";t.exports={selectArrows:e("./selectArrows")}},{"./selectArrows":43}],43:[function(e,t,o){"use strict";t.exports='<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg width="7px" height="11px" viewBox="0 0 7 11" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M3.5,0 L7,4 L0,4 L3.5,0 Z M3.5,11 L7,7 L0,7 L3.5,11 Z" /></svg>'},{}]},{},[1])(1)}); |
src/forms/formGroup.js | ikanedo/react-redux-simple-validate | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Validator from '../validators/validator';
import formElementFromEvt from './formElement/formElementFromEvt';
import formBuilder from './formBuilder';
import { filterValidation, getFormData } from './formUtils';
import * as FormActions from './formActions';
class FormGroupDefault extends Component {
constructor(props) {
super(props);
this.onValidate = this.onValidate.bind(this);
this.onInvalidate = this.onInvalidate.bind(this);
this.onValueChange = this.onValueChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.formValidator = new Validator(filterValidation(props));
this.stringRefs = {};
}
componentDidMount() {
const {
formName,
defaultErrors,
defaultValues,
setInitialData
} = this.props;
if (defaultErrors || defaultValues) {
setInitialData(
formName,
defaultValues,
defaultErrors
);
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.validation !== this.props.validation) {
this.formValidator.setConstraints(filterValidation(nextProps));
}
if (nextProps.isTriggerValidation) {
this.onSubmit();
this.props.triggerValidate(nextProps.formName, false);
}
}
shouldComponentUpdate(nextProps) {
const {
values,
errors,
children
} = this.props;
const isSameValues = JSON.stringify(values) === JSON.stringify(nextProps.values);
const isSameErrors = JSON.stringify(errors) === JSON.stringify(nextProps.errors);
const isSameChildren = children === nextProps.children;
return !(isSameValues && isSameErrors && isSameChildren);
}
onSubmit() {
const {
children,
formName,
setValidity,
handleValidForm,
handleInvalidForm
} = this.props;
const formData = getFormData(children, this.stringRefs);
const errorMsgs = this.formValidator.validate(formData);
setValidity(formName, errorMsgs);
const isValid = !errorMsgs;
if (isValid) {
handleValidForm(formData, formName);
} else {
handleInvalidForm(errorMsgs, formName);
}
}
onValidate(e) {
const {
children,
formName,
setSingleValidity
} = this.props;
const formData = getFormData(children, this.stringRefs);
const errorMsgs = this.formValidator.single(e.target.name, formData);
const isValid = !errorMsgs;
if (isValid) {
setSingleValidity(
formName,
{ [e.target.name]: errorMsgs }
);
}
}
onInvalidate(e) {
const {
children,
formName,
setSingleValidity
} = this.props;
const formData = getFormData(children, this.stringRefs);
const errorMsgs = this.formValidator.single(e.target.name, formData);
const isValid = !errorMsgs;
if (!isValid) {
setSingleValidity(
formName,
{ [e.target.name]: errorMsgs }
);
}
}
onValueChange(e) {
const {
formName,
setInputValue
} = this.props;
setInputValue(
formName,
{ [e.target.name]: formElementFromEvt(e).getVal() }
);
}
render() {
const {
children,
values,
errors,
invalidateEvent,
validateEvent,
className
} = this.props;
const formElements = formBuilder({
stringRefs: this.stringRefs,
onValidate: this.onValidate,
onInvalidate: this.onInvalidate,
onValueChange: this.onValueChange,
values,
errors,
children,
invalidateEvent,
validateEvent
});
return (
<div className={`form-group ${className || ''}`}>
{formElements}
</div>
);
}
}
FormGroupDefault.displayName = 'FormGroup';
FormGroupDefault.defaultProps = {
invalidateEvent: 'onBlur',
validateEvent: 'onChange',
handleInvalidForm() {}
};
FormGroupDefault.propTypes = {
children: PropTypes.node.isRequired,
validation: PropTypes.shape({
rules: PropTypes.object.isRequired,
messages: PropTypes.object.isRequired
}),
handleValidForm: PropTypes.func.isRequired,
handleInvalidForm: PropTypes.func,
formName: PropTypes.string.isRequired,
values: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired,
defaultValues: PropTypes.object,
defaultErrors: PropTypes.object,
setInitialData: PropTypes.func.isRequired,
setValidity: PropTypes.func.isRequired,
setSingleValidity: PropTypes.func.isRequired,
setInputValue: PropTypes.func.isRequired,
triggerValidate: PropTypes.func,
invalidateEvent: PropTypes.string,
validateEvent: PropTypes.string,
className: PropTypes.string
};
function mapStateToProps(state, props) {
const formState = state.Forms[props.formName] || {};
return {
values: formState.values || {},
errors: formState.errors || {},
isTriggerValidation: !!formState.isTriggerValidation
};
}
export default connect(mapStateToProps, FormActions)(FormGroupDefault);
|
modules/experimental/AsyncProps.js | kenwheeler/react-router | import React from 'react';
import invariant from 'invariant';
var { func, array, shape, object } = React.PropTypes;
var contextTypes = {
asyncProps: shape({
reloadComponent: func,
propsArray: array,
componentsArray: array
})
};
var _serverPropsArray = null;
function setServerPropsArray(array) {
invariant(!_serverPropsArray, 'You cannot call AsyncProps.hydrate more than once');
_serverPropsArray = array;
}
export function _clearCacheForTesting() {
_serverPropsArray = null;
}
function hydrate(routerState, cb) {
var { components, params } = routerState;
var flatComponents = filterAndFlattenComponents(components);
loadAsyncProps(flatComponents, params, cb);
}
function eachComponents(components, iterator) {
for (var i = 0, l = components.length; i < l; i++) {
if (typeof components[i] === 'object') {
for (var key in components[i]) {
iterator(components[i][key], i, key);
}
} else {
iterator(components[i], i);
}
}
}
function filterAndFlattenComponents(components) {
var flattened = [];
eachComponents(components, function(Component) {
if (Component.loadProps)
flattened.push(Component);
});
return flattened;
}
function loadAsyncProps(components, params, cb) {
var propsArray = [];
var componentsArray = [];
var canceled = false;
var needToLoadCounter = components.length;
components.forEach(function(Component, index) {
Component.loadProps(params, function(error, props) {
needToLoadCounter--;
propsArray[index] = props;
componentsArray[index] = Component;
maybeFinish();
});
});
function maybeFinish() {
if (canceled === false && needToLoadCounter === 0)
cb(null, {propsArray, componentsArray});
}
return {
cancel () {
canceled = true;
}
};
}
function getPropsForComponent(Component, componentsArray, propsArray) {
var index = componentsArray.indexOf(Component);
return propsArray[index];
}
function mergeAsyncProps(current, changes) {
for (var i = 0, l = changes.propsArray.length; i < l; i++) {
let Component = changes.componentsArray[i];
let position = current.componentsArray.indexOf(Component);
let isNew = position === -1;
if (isNew) {
current.propsArray.push(changes.propsArray[i]);
current.componentsArray.push(changes.componentsArray[i]);
} else {
current.propsArray[position] = changes.propsArray[i];
}
}
}
function arrayDiff(previous, next) {
var diff = [];
for (var i = 0, l = next.length; i < l; i++)
if (previous.indexOf(next[i]) === -1)
diff.push(next[i]);
return diff;
}
function shallowEqual(a, b) {
var key;
var ka = 0;
var kb = 0;
for (key in a) {
if (a.hasOwnProperty(key) && a[key] !== b[key])
return false;
ka++;
}
for (key in b)
if (b.hasOwnProperty(key))
kb++;
return ka === kb;
}
var RouteComponentWrapper = React.createClass({
contextTypes: contextTypes,
// this is here to meet the case of reloading the props when a component's params change,
// the place we know that is here, but the problem is we get occasional waterfall loads
// when clicking links quickly at the same route, AsyncProps doesn't know to load the next
// props until the previous finishes rendering.
//
// if we could tell that a component needs its props reloaded in AsyncProps instead of here
// (by the arrayDiff stuff in componentWillReceiveProps) then we wouldn't need this code at
// all, and we coudl get rid of the terrible forceUpdate hack as well. I'm just not sure
// right now if we can know to reload a pivot transition.
componentWillReceiveProps(nextProps, context) {
var paramsChanged = !shallowEqual(
this.props.routerState.routeParams,
nextProps.routerState.routeParams
);
if (paramsChanged) {
this.reloadProps(nextProps.routerState.routeParams);
}
},
reloadProps(params) {
this.context.asyncProps.reloadComponent(
this.props.Component,
params || this.props.routerState.routeParams,
this
);
},
render() {
var { Component, routerState } = this.props;
var { componentsArray, propsArray, loading } = this.context.asyncProps;
var asyncProps = getPropsForComponent(Component, componentsArray, propsArray);
return <Component {...routerState} {...asyncProps} loading={loading} reloadAsyncProps={this.reloadProps} />;
}
});
var AsyncProps = React.createClass({
statics: {
hydrate: hydrate,
rehydrate: setServerPropsArray,
createElement(Component, state) {
return typeof Component.loadProps === 'function' ?
<RouteComponentWrapper Component={Component} routerState={state}/> :
<Component {...state}/>;
}
},
childContextTypes: contextTypes,
getChildContext() {
return {
asyncProps: Object.assign({
reloadComponent: this.reloadComponent,
loading: this.state.previousProps !== null
}, this.state.asyncProps),
};
},
getInitialState() {
return {
asyncProps: {
propsArray: _serverPropsArray,
componentsArray: _serverPropsArray ? filterAndFlattenComponents(this.props.components) : null,
},
previousProps: null
};
},
componentDidMount() {
var initialLoad = this.state.asyncProps.propsArray === null;
if (initialLoad) {
hydrate(this.props, (err, asyncProps) => {
this.setState({ asyncProps });
});
}
},
componentWillReceiveProps(nextProps) {
var routerTransitioned = nextProps.location !== this.props.location;
if (!routerTransitioned)
return;
var oldComponents = this.props.components;
var newComponents = nextProps.components;
var components = arrayDiff(
filterAndFlattenComponents(oldComponents),
filterAndFlattenComponents(newComponents)
);
if (components.length === 0)
return;
this.loadAsyncProps(components, nextProps.params);
},
beforeLoad(cb) {
this.setState({
previousProps: this.props
}, cb);
},
afterLoad(err, asyncProps, cb) {
this.inflightLoader = null;
mergeAsyncProps(this.state.asyncProps, asyncProps);
this.setState({
previousProps: null,
asyncProps: this.state.asyncProps
}, cb);
},
loadAsyncProps(components, params, cb) {
if (this.inflightLoader) {
this.inflightLoader.cancel();
}
this.beforeLoad(() => {
this.inflightLoader = loadAsyncProps(components, params, (err, asyncProps) => {
this.afterLoad(err, asyncProps, cb);
});
});
},
reloadComponent(Component, params, instance) {
this.loadAsyncProps([Component], params, () => {
// gotta fix this hack ... change in context doesn't cause the
// RouteComponentWrappers to rerender (first one will because
// of cloneElement)
if (instance.isMounted())
instance.forceUpdate();
});
},
render() {
var { route } = this.props;
var { asyncProps, previousProps } = this.state;
var initialLoad = asyncProps.propsArray === null;
if (initialLoad)
return route.renderInitialLoad ? route.renderInitialLoad() : null;
else if (previousProps)
return React.cloneElement(previousProps.children, { loading: true });
else
return this.props.children;
}
});
export default AsyncProps;
|
src/svg-icons/editor/insert-chart.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorInsertChart = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
</SvgIcon>
);
EditorInsertChart = pure(EditorInsertChart);
EditorInsertChart.displayName = 'EditorInsertChart';
EditorInsertChart.muiName = 'SvgIcon';
export default EditorInsertChart;
|
cdap-ui/app/cdap/components/CaskWizards/StreamCreate/SchemaStep/index.js | caskdata/cdap | /*
* Copyright © 2016 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
import React from 'react';
import {connect, Provider} from 'react-redux';
import {Col, FormGroup, Label, Form} from 'reactstrap';
import T from 'i18n-react';
import SelectWithOptions from 'components/SelectWithOptions';
import SimpleSchema from 'components/SimpleSchema';
import CreateStreamStore, { defaultSchemaFormats } from 'services/WizardStores/CreateStream/CreateStreamStore';
import CreateStreamActions from 'services/WizardStores/CreateStream/CreateStreamActions';
const mapStateToSchemaTypeProps = (state) => {
return {
value: state.schema.format,
options: defaultSchemaFormats
};
};
const mapDispatchToSchemaTypeProps = (dispatch) => {
return {
onChange: (e) => (dispatch({
type: CreateStreamActions.setSchemaFormat,
payload: { format: e.target.value}
}))
};
};
const SchemaType = connect(
mapStateToSchemaTypeProps,
mapDispatchToSchemaTypeProps
)(SelectWithOptions);
const SimpleSchemaWrapper = connect(
state => {
return {
schema: state.schema.value,
};
},
dispatch => {
return {
onSchemaChange: (schema) => {
dispatch({
type: CreateStreamActions.setSchema,
payload: { schema }
});
}
};
}
)(SimpleSchema);
export default function SchemaStep() {
return (
<Provider store={CreateStreamStore}>
<Form
className="form-horizontal"
onSubmit={(e) => {
e.preventDefault();
return false;
}}
>
<FormGroup>
<Col xs="2">
<Label className="control-label">{T.translate('commons.formatLabel')}</Label>
</Col>
<Col xs="4">
<SchemaType className="input-sm"/>
</Col>
</FormGroup>
<FormGroup>
<Col xs="12">
<Label className="control-label">{T.translate('commons.schemaLabel')}</Label>
</Col>
<Col xs="12">
<SimpleSchemaWrapper />
</Col>
</FormGroup>
</Form>
</Provider>
);
}
|
packages/cf-component-icon/src/reactsvgs/ResizeHorizontal.js | jroyal/cf-ui | import React from 'react';
import PropTypes from 'prop-types';
const ResizeHorizontal = ({ className, label }) => (
<svg
className={className}
aria-label={label}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
>
<path d="M6.847,4.184,3.1,7.931a.279.279,0,0,0,0,.394l3.746,3.746a.279.279,0,0,0,.476-.2V4.381A.279.279,0,0,0,6.847,4.184Z" />
<path d="M9.3,4.206l3.746,3.746a.279.279,0,0,1,0,.394L9.3,12.093a.279.279,0,0,1-.476-.2V4.4A.279.279,0,0,1,9.3,4.206Z" />
</svg>
);
ResizeHorizontal.propTypes = {
className: PropTypes.string.isRequired,
label: PropTypes.string.isRequired
};
export default ResizeHorizontal;
|
ajax/libs/mobx/6.1.3/mobx.esm.development.min.js | cdnjs/cdnjs | var niceErrors={0:"Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'",1:function(e,t){return"Cannot apply '"+e+"' to '"+t.toString()+"': Field not found."},5:"'keys()' can only be used on observable objects, arrays, sets and maps",6:"'values()' can only be used on observable objects, arrays, sets and maps",7:"'entries()' can only be used on observable objects, arrays and maps",8:"'set()' can only be used on observable objects, arrays and maps",9:"'remove()' can only be used on observable objects, arrays and maps",10:"'has()' can only be used on observable objects, arrays and maps",11:"'get()' can only be used on observable objects, arrays and maps",12:"Invalid annotation",13:"Dynamic observable objects cannot be frozen",14:"Intercept handlers should return nothing or a change object",15:"Observable arrays cannot be frozen",16:"Modification exception: the internal structure of an observable array was changed.",17:function(e,t){return"[mobx.array] Index out of bounds, "+e+" is larger than "+t},18:"mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js",19:function(e){return"Cannot initialize from classes that inherit from Map: "+e.constructor.name},20:function(e){return"Cannot initialize map from "+e},21:function(e){return"Cannot convert to map from '"+e+"'"},22:"mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js",23:"It is not possible to get index atoms from arrays",24:function(e){return"Cannot obtain administration from "+e},25:function(e,t){return"the entry '"+e+"' does not exist in the observable map '"+t+"'"},26:"please specify a property",27:function(e,t){return"no observable property '"+e.toString()+"' found on the observable object '"+t+"'"},28:function(e){return"Cannot obtain atom from "+e},29:"Expecting some object",30:"invalid action stack. did you forget to finish an action?",31:"missing option for computed: get",32:function(e,t){return"Cycle detected in computation "+e+": "+t},33:function(e){return"The setter of computed value '"+e+"' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?"},34:function(e){return"[ComputedValue '"+e+"'] It is not possible to assign a new value to a computed value."},35:"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`",36:"isolateGlobalState should be called before MobX is running any reactions",37:function(e){return"[mobx] `observableArray."+e+"()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice()."+e+"()` instead"}},errors=niceErrors;function die(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var a="string"==typeof e?e:errors[e];throw"function"==typeof a&&(a=a.apply(null,n)),new Error("[MobX] "+a)}var mockGlobal={};function getGlobal(){return"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:mockGlobal}var assign=Object.assign,getDescriptor=Object.getOwnPropertyDescriptor,defineProperty=Object.defineProperty,objectPrototype=Object.prototype,EMPTY_ARRAY=[];Object.freeze(EMPTY_ARRAY);var EMPTY_OBJECT={};Object.freeze(EMPTY_OBJECT);var hasProxy="undefined"!=typeof Proxy,plainObjectString=Object.toString();function assertProxies(){hasProxy||die("`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`")}function warnAboutProxyRequirement(e){globalState.verifyProxies&&die("MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to "+e)}function getNextId(){return++globalState.mobxGuid}function once(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}var noop=function(){};function isFunction(e){return"function"==typeof e}function isStringish(e){switch(typeof e){case"string":case"symbol":case"number":return!0}return!1}function isObject(e){return null!==e&&"object"==typeof e}function isPlainObject(e){var t;if(!isObject(e))return!1;var n=Object.getPrototypeOf(e);return null==n||(null==(t=n.constructor)?void 0:t.toString())===plainObjectString}function isGenerator(e){var t=null==e?void 0:e.constructor;return!!t&&("GeneratorFunction"===t.name||"GeneratorFunction"===t.displayName)}function addHiddenProp(e,t,n){defineProperty(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function addHiddenFinalProp(e,t,n){defineProperty(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function createInstanceofPredicate(e,t){var n="isMobX"+e;return t.prototype[n]=!0,function(e){return isObject(e)&&!0===e[n]}}function isES6Map(e){return e instanceof Map}function isES6Set(e){return e instanceof Set}var hasGetOwnPropertySymbols=void 0!==Object.getOwnPropertySymbols;function getPlainObjectKeys(e){var t=Object.keys(e);if(!hasGetOwnPropertySymbols)return t;var n=Object.getOwnPropertySymbols(e);return n.length?[].concat(t,n.filter(function(t){return objectPrototype.propertyIsEnumerable.call(e,t)})):t}var ownKeys="undefined"!=typeof Reflect&&Reflect.ownKeys?Reflect.ownKeys:hasGetOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames;function stringifyKey(e){return"string"==typeof e?e:"symbol"==typeof e?e.toString():new String(e).toString()}function toPrimitive(e){return null===e?null:"object"==typeof e?""+e:e}function hasProp(e,t){return objectPrototype.hasOwnProperty.call(e,t)}var getOwnPropertyDescriptors=Object.getOwnPropertyDescriptors||function(e){var t={};return ownKeys(e).forEach(function(n){t[n]=getDescriptor(e,n)}),t};function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}function _extends(){return(_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function _createForOfIteratorHelperLoose(e,t){var n;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(n=_unsupportedIterableToArray(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(n=e[Symbol.iterator]()).next.bind(n)}var storedAnnotationsSymbol=Symbol("mobx-stored-annotations");function createDecoratorAnnotation(e){return Object.assign(function(t,n){storeAnnotation(t,n,e)},e)}function storeAnnotation(e,t,n){(hasProp(e,storedAnnotationsSymbol)||addHiddenProp(e,storedAnnotationsSymbol,_extends({},e[storedAnnotationsSymbol])),isOverride(n)&&!hasProp(e[storedAnnotationsSymbol],t))&&die("'"+(e.constructor.name+".prototype."+t.toString())+"' is decorated with 'override', but no such decorated member was found on prototype.");assertNotDecorated(e,n,t),isOverride(n)||(e[storedAnnotationsSymbol][t]=_extends({},n,{isDecorator_:!0}))}function assertNotDecorated(e,t,n){if(!isOverride(t)&&hasProp(e[storedAnnotationsSymbol],n)){var r=e.constructor.name+".prototype."+n.toString(),a=e[storedAnnotationsSymbol][n].annotationType_;die("Cannot apply '@"+t.annotationType_+"' to '"+r+"':\nThe field is already decorated with '@"+a+"'.\nRe-decorating fields is not allowed.\nUse '@override' decorator for methods overriden by subclass.")}}function collectStoredAnnotations(e){return hasProp(e,storedAnnotationsSymbol)||(e[storedAnnotationsSymbol]||die("No annotations were passed to makeObservable, but no decorated members have been found either"),addHiddenProp(e,storedAnnotationsSymbol,_extends({},e[storedAnnotationsSymbol]))),e[storedAnnotationsSymbol]}var $mobx=Symbol("mobx administration"),Atom=function(){function e(e){void 0===e&&(e="Atom@"+getNextId()),this.name_=void 0,this.isPendingUnobservation_=!1,this.isBeingObserved_=!1,this.observers_=new Set,this.diffValue_=0,this.lastAccessedBy_=0,this.lowestObserverState_=IDerivationState_.NOT_TRACKING_,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}var t=e.prototype;return t.onBO=function(){this.onBOL&&this.onBOL.forEach(function(e){return e()})},t.onBUO=function(){this.onBUOL&&this.onBUOL.forEach(function(e){return e()})},t.reportObserved=function(){return reportObserved(this)},t.reportChanged=function(){startBatch(),propagateChanged(this),endBatch()},t.toString=function(){return this.name_},e}(),isAtom=createInstanceofPredicate("Atom",Atom);function createAtom(e,t,n){void 0===t&&(t=noop),void 0===n&&(n=noop);var r=new Atom(e);return t!==noop&&onBecomeObserved(r,t),n!==noop&&onBecomeUnobserved(r,n),r}function identityComparer(e,t){return e===t}function structuralComparer(e,t){return deepEqual(e,t)}function shallowComparer(e,t){return deepEqual(e,t,1)}function defaultComparer(e,t){return Object.is(e,t)}var comparer={identity:identityComparer,structural:structuralComparer,default:defaultComparer,shallow:shallowComparer};function deepEnhancer(e,t,n){return isObservable(e)?e:Array.isArray(e)?observable.array(e,{name:n}):isPlainObject(e)?observable.object(e,void 0,{name:n}):isES6Map(e)?observable.map(e,{name:n}):isES6Set(e)?observable.set(e,{name:n}):e}function shallowEnhancer(e,t,n){return null==e?e:isObservableObject(e)||isObservableArray(e)||isObservableMap(e)||isObservableSet(e)?e:Array.isArray(e)?observable.array(e,{name:n,deep:!1}):isPlainObject(e)?observable.object(e,void 0,{name:n,deep:!1}):isES6Map(e)?observable.map(e,{name:n,deep:!1}):isES6Set(e)?observable.set(e,{name:n,deep:!1}):void die("The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets")}function referenceEnhancer(e){return e}function refStructEnhancer(e,t){return isObservable(e)&&die("observable.struct should not be used with observable values"),deepEqual(e,t)?t:e}var OVERRIDE="override",override=createDecoratorAnnotation({annotationType_:OVERRIDE,make_:make_,extend_:extend_});function isOverride(e){return e.annotationType_===OVERRIDE}function make_(e,t){e.isPlainObject_&&die("Cannot apply '"+this.annotationType_+"' to '"+e.name_+"."+t.toString()+"':\n'"+this.annotationType_+"' cannot be used on plain objects."),hasProp(e.appliedAnnotations_,t)||die("'"+e.name_+"."+t.toString()+"' is annotated with '"+this.annotationType_+"', but no such annotated member was found on prototype.")}function extend_(e,t,n,r){die("'"+this.annotationType_+"' can only be used with 'makeObservable'")}function createActionAnnotation(e,t){return{annotationType_:e,options_:t,make_:make_$1,extend_:extend_$1}}function make_$1(e,t){for(var n,r,a=!1,o=e.target_,i=null!=(n=null==(r=this.options_)?void 0:r.bound)&&n;o&&o!==objectPrototype;){var s=getDescriptor(o,t);if(s){if(o===e.target_||i){var c=createActionDescriptor(e,this,t,s);if(!e.defineProperty_(t,c))return;if(a=!0,i)break}if(o!==e.target_){if(isAction(s.value)){a=!0;break}var l=createActionDescriptor(e,this,t,s);defineProperty(o,t,l),a=!0}}o=Object.getPrototypeOf(o)}a?recordAnnotationApplied(e,this,t):this.isDecorator_||die(1,this.annotationType_,e.name_+"."+t.toString())}function extend_$1(e,t,n,r){var a=createActionDescriptor(e,this,t,n);return e.defineProperty_(t,a,r)}function assertActionDescriptor(e,t,n,r){var a=t.annotationType_;isFunction(r.value)||die("Cannot apply '"+a+"' to '"+e.name_+"."+n.toString()+"':\n'"+a+"' can only be used on properties with a function value.")}function createActionDescriptor(e,t,n,r){var a,o,i,s,c;assertActionDescriptor(e,t,n,r);var l,u=r.value;(null==(a=t.options_)?void 0:a.bound)&&(u=u.bind(null!=(l=e.proxy_)?l:e.target_));return{value:createAction(null!=(o=null==(i=t.options_)?void 0:i.name)?o:n.toString(),u,null!=(s=null==(c=t.options_)?void 0:c.autoAction)&&s),configurable:!globalState.safeDescriptors||e.isPlainObject_,enumerable:!1,writable:!globalState.safeDescriptors}}function createFlowAnnotation(e,t){return{annotationType_:e,options_:t,make_:make_$2,extend_:extend_$2}}function make_$2(e,t){for(var n=!1,r=e.target_;r&&r!==objectPrototype;){var a=getDescriptor(r,t);if(a){if(r!==e.target_){if(isFlow(a.value)){n=!0;break}var o=createFlowDescriptor(e,this,t,a);defineProperty(r,t,o)}else{var i=createFlowDescriptor(e,this,t,a);if(!e.defineProperty_(t,i))return}n=!0}r=Object.getPrototypeOf(r)}n?recordAnnotationApplied(e,this,t):this.isDecorator_||die(1,this.annotationType_,e.name_+"."+t.toString())}function extend_$2(e,t,n,r){var a=createFlowDescriptor(e,this,t,n);return e.defineProperty_(t,a,r)}function assertFlowDescriptor(e,t,n,r){var a=t.annotationType_;isFunction(r.value)||die("Cannot apply '"+a+"' to '"+e.name_+"."+n.toString()+"':\n'"+a+"' can only be used on properties with a generator function value.")}function createFlowDescriptor(e,t,n,r){return assertFlowDescriptor(e,t,n,r),{value:flow(r.value),configurable:!globalState.safeDescriptors||e.isPlainObject_,enumerable:!1,writable:!globalState.safeDescriptors}}function createComputedAnnotation(e,t){return{annotationType_:e,options_:t,make_:make_$3,extend_:extend_$3}}function make_$3(e,t){for(var n=e.target_;n&&n!==objectPrototype;){var r=getDescriptor(n,t);if(r){if(assertComputedDescriptor(e,this,t,r),!e.defineComputedProperty_(t,_extends({},this.options_,{get:r.get,set:r.set})))return;return void recordAnnotationApplied(e,this,t)}n=Object.getPrototypeOf(n)}this.isDecorator_||die(1,this.annotationType_,e.name_+"."+t.toString())}function extend_$3(e,t,n,r){return assertComputedDescriptor(e,this,t,n),e.defineComputedProperty_(t,_extends({},this.options_,{get:n.get,set:n.set}),r)}function assertComputedDescriptor(e,t,n,r){var a=t.annotationType_;r.get||die("Cannot apply '"+a+"' to '"+e.name_+"."+n.toString()+"':\n'"+a+"' can only be used on getter(+setter) properties.")}function createObservableAnnotation(e,t){return{annotationType_:e,options_:t,make_:make_$4,extend_:extend_$4}}function make_$4(e,t){for(var n=e.target_;n&&n!==objectPrototype;){var r=getDescriptor(n,t);if(r){var a,o;if(assertObservableDescriptor(e,this,t,r),!e.defineObservableProperty_(t,r.value,null!=(a=null==(o=this.options_)?void 0:o.enhancer)?a:deepEnhancer))return;return void recordAnnotationApplied(e,this,t)}n=Object.getPrototypeOf(n)}this.isDecorator_||die(1,this.annotationType_,e.name_+"."+t.toString())}function extend_$4(e,t,n,r){var a,o;return assertObservableDescriptor(e,this,t,n),e.defineObservableProperty_(t,n.value,null!=(a=null==(o=this.options_)?void 0:o.enhancer)?a:deepEnhancer,r)}function assertObservableDescriptor(e,t,n,r){var a=t.annotationType_;"value"in r||die("Cannot apply '"+a+"' to '"+e.name_+"."+n.toString()+"':\n'"+a+"' cannot be used on getter/setter properties")}var defaultCreateObservableOptions={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};function asCreateObservableOptions(e){return e||defaultCreateObservableOptions}Object.freeze(defaultCreateObservableOptions);var observableAnnotation=createObservableAnnotation("observable"),observableRefAnnotation=createObservableAnnotation("observable.ref",{enhancer:referenceEnhancer}),observableShallowAnnotation=createObservableAnnotation("observable.shallow",{enhancer:shallowEnhancer}),observableStructAnnotation=createObservableAnnotation("observable.struct",{enhancer:refStructEnhancer}),observableDecoratorAnnotation=createDecoratorAnnotation(observableAnnotation);function getEnhancerFromOptions(e){return!0===e.deep?deepEnhancer:!1===e.deep?referenceEnhancer:getEnhancerFromAnnotation(e.defaultDecorator)}function getAnnotationFromOptions(e){return e?!0===e.deep?observableAnnotation:!1===e.deep?observableRefAnnotation:e.defaultDecorator:void 0}function getEnhancerFromAnnotation(e){var t,n;return e&&null!=(t=null==(n=e.options_)?void 0:n.enhancer)?t:deepEnhancer}function createObservable(e,t,n){if(!isStringish(t))return isObservable(e)?e:isPlainObject(e)?observable.object(e,t,n):Array.isArray(e)?observable.array(e,t):isES6Map(e)?observable.map(e,t):isES6Set(e)?observable.set(e,t):"object"==typeof e&&null!==e?e:observable.box(e);storeAnnotation(e,t,observableAnnotation)}Object.assign(createObservable,observableDecoratorAnnotation);var _getDescriptor$config,_getDescriptor,observableFactories={box:function(e,t){var n=asCreateObservableOptions(t);return new ObservableValue(e,getEnhancerFromOptions(n),n.name,!0,n.equals)},array:function(e,t){var n=asCreateObservableOptions(t);return(!1===globalState.useProxies||!1===n.proxy?createLegacyArray:createObservableArray)(e,getEnhancerFromOptions(n),n.name)},map:function(e,t){var n=asCreateObservableOptions(t);return new ObservableMap(e,getEnhancerFromOptions(n),n.name)},set:function(e,t){var n=asCreateObservableOptions(t);return new ObservableSet(e,getEnhancerFromOptions(n),n.name)},object:function(e,t,n){return extendObservable(!1===globalState.useProxies||!1===(null==n?void 0:n.proxy)?asObservableObject({},n):asDynamicObservableObject({},n),e,t)},ref:createDecoratorAnnotation(observableRefAnnotation),shallow:createDecoratorAnnotation(observableShallowAnnotation),deep:observableDecoratorAnnotation,struct:createDecoratorAnnotation(observableStructAnnotation)},observable=assign(createObservable,observableFactories),COMPUTED="computed",COMPUTED_STRUCT="computed.struct",computedAnnotation=createComputedAnnotation(COMPUTED),computedStructAnnotation=createComputedAnnotation(COMPUTED_STRUCT,{equals:comparer.structural}),computed=function(e,t){if(isStringish(t))return storeAnnotation(e,t,computedAnnotation);if(isPlainObject(e))return createDecoratorAnnotation(createComputedAnnotation(COMPUTED,e));isFunction(e)||die("First argument to `computed` should be an expression."),isFunction(t)&&die("A setter as second argument is no longer supported, use `{ set: fn }` option instead");var n=isPlainObject(t)?t:{};return n.get=e,n.name=n.name||e.name||"",new ComputedValue(n)};Object.assign(computed,computedAnnotation),computed.struct=createDecoratorAnnotation(computedStructAnnotation);var _Symbol$toPrimitive,currentActionId=0,nextActionId=1,isFunctionNameConfigurable=null!=(_getDescriptor$config=null==(_getDescriptor=getDescriptor(function(){},"name"))?void 0:_getDescriptor.configurable)&&_getDescriptor$config,tmpNameDescriptor={value:"action",configurable:!0,writable:!1,enumerable:!1};function createAction(e,t,n,r){function a(){return executeAction(e,n,t,r||this,arguments)}return void 0===n&&(n=!1),isFunction(t)||die("`action` can only be invoked on functions"),"string"==typeof e&&e||die("actions should have valid names, got: '"+e+"'"),a.isMobxAction=!0,isFunctionNameConfigurable&&(tmpNameDescriptor.value=e,Object.defineProperty(a,"name",tmpNameDescriptor)),a}function executeAction(e,t,n,r,a){var o=_startAction(e,t,r,a);try{return n.apply(r,a)}catch(e){throw o.error_=e,e}finally{_endAction(o)}}function _startAction(e,t,n,r){var a=isSpyEnabled()&&!!e,o=0;if(a){o=Date.now();var i=r?Array.from(r):EMPTY_ARRAY;spyReportStart({type:ACTION,name:e,object:n,arguments:i})}var s=globalState.trackingDerivation,c=!t||!s;startBatch();var l=globalState.allowStateChanges;c&&(untrackedStart(),l=allowStateChangesStart(!0));var u={runAsAction_:c,prevDerivation_:s,prevAllowStateChanges_:l,prevAllowStateReads_:allowStateReadsStart(!0),notifySpy_:a,startTime_:o,actionId_:nextActionId++,parentActionId_:currentActionId};return currentActionId=u.actionId_,u}function _endAction(e){currentActionId!==e.actionId_&&die(30),currentActionId=e.parentActionId_,void 0!==e.error_&&(globalState.suppressReactionErrors=!0),allowStateChangesEnd(e.prevAllowStateChanges_),allowStateReadsEnd(e.prevAllowStateReads_),endBatch(),e.runAsAction_&&untrackedEnd(e.prevDerivation_),e.notifySpy_&&spyReportEnd({time:Date.now()-e.startTime_}),globalState.suppressReactionErrors=!1}function allowStateChanges(e,t){var n=allowStateChangesStart(e);try{return t()}finally{allowStateChangesEnd(n)}}function allowStateChangesStart(e){var t=globalState.allowStateChanges;return globalState.allowStateChanges=e,t}function allowStateChangesEnd(e){globalState.allowStateChanges=e}var CREATE="create";_Symbol$toPrimitive=Symbol.toPrimitive;var _Symbol$toPrimitive$1,ObservableValue=function(e){function t(t,n,r,a,o){var i;return void 0===r&&(r="ObservableValue@"+getNextId()),void 0===a&&(a=!0),void 0===o&&(o=comparer.default),(i=e.call(this,r)||this).enhancer=void 0,i.name_=void 0,i.equals=void 0,i.hasUnreportedChange_=!1,i.interceptors_=void 0,i.changeListeners_=void 0,i.value_=void 0,i.dehancer=void 0,i.enhancer=n,i.name_=r,i.equals=o,i.value_=n(t,void 0,r),a&&isSpyEnabled()&&spyReport({type:CREATE,object:_assertThisInitialized(i),observableKind:"value",debugObjectName:i.name_,newValue:""+i.value_}),i}_inheritsLoose(t,e);var n=t.prototype;return n.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},n.set=function(e){var t=this.value_;if((e=this.prepareNewValue_(e))!==globalState.UNCHANGED){var n=isSpyEnabled();n&&spyReportStart({type:UPDATE,object:this,observableKind:"value",debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&spyReportEnd()}},n.prepareNewValue_=function(e){if(checkIfStateModificationsAreAllowed(this),hasInterceptors(this)){var t=interceptChange(this,{object:this,type:UPDATE,newValue:e});if(!t)return globalState.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.value_,this.name_),this.equals(this.value_,e)?globalState.UNCHANGED:e},n.setNewValue_=function(e){var t=this.value_;this.value_=e,this.reportChanged(),hasListeners(this)&¬ifyListeners(this,{type:UPDATE,object:this,newValue:e,oldValue:t})},n.get=function(){return this.reportObserved(),this.dehanceValue(this.value_)},n.intercept_=function(e){return registerInterceptor(this,e)},n.observe_=function(e,t){return t&&e({observableKind:"value",debugObjectName:this.name_,object:this,type:UPDATE,newValue:this.value_,oldValue:void 0}),registerListener(this,e)},n.raw=function(){return this.value_},n.toJSON=function(){return this.get()},n.toString=function(){return this.name_+"["+this.value_+"]"},n.valueOf=function(){return toPrimitive(this.get())},n[_Symbol$toPrimitive]=function(){return this.valueOf()},t}(Atom),isObservableValue=createInstanceofPredicate("ObservableValue",ObservableValue);_Symbol$toPrimitive$1=Symbol.toPrimitive;var IDerivationState_,TraceMode,ComputedValue=function(){function e(e){this.dependenciesState_=IDerivationState_.NOT_TRACKING_,this.observing_=[],this.newObserving_=null,this.isBeingObserved_=!1,this.isPendingUnobservation_=!1,this.observers_=new Set,this.diffValue_=0,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=IDerivationState_.UP_TO_DATE_,this.unboundDepsCount_=0,this.mapid_="#"+getNextId(),this.value_=new CaughtException(null),this.name_=void 0,this.triggeredBy_=void 0,this.isComputing_=!1,this.isRunningSetter_=!1,this.derivation=void 0,this.setter_=void 0,this.isTracing_=TraceMode.NONE,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||die(31),this.derivation=e.get,this.name_=e.name||"ComputedValue@"+getNextId(),e.set&&(this.setter_=createAction(this.name_+"-setter",e.set)),this.equals_=e.equals||(e.compareStructural||e.struct?comparer.structural:comparer.default),this.scope_=e.context,this.requiresReaction_=!!e.requiresReaction,this.keepAlive_=!!e.keepAlive}var t=e.prototype;return t.onBecomeStale_=function(){propagateMaybeChanged(this)},t.onBO=function(){this.onBOL&&this.onBOL.forEach(function(e){return e()})},t.onBUO=function(){this.onBUOL&&this.onBUOL.forEach(function(e){return e()})},t.get=function(){if(this.isComputing_&&die(32,this.name_,this.derivation),0!==globalState.inBatch||0!==this.observers_.size||this.keepAlive_){if(reportObserved(this),shouldCompute(this)){var e=globalState.trackingContext;this.keepAlive_&&!e&&(globalState.trackingContext=this),this.trackAndCompute()&&propagateChangeConfirmed(this),globalState.trackingContext=e}}else shouldCompute(this)&&(this.warnAboutUntrackedRead_(),startBatch(),this.value_=this.computeValue_(!1),endBatch());var t=this.value_;if(isCaughtException(t))throw t.cause;return t},t.set=function(e){if(this.setter_){this.isRunningSetter_&&die(33,this.name_),this.isRunningSetter_=!0;try{this.setter_.call(this.scope_,e)}finally{this.isRunningSetter_=!1}}else die(34,this.name_)},t.trackAndCompute=function(){var e=this.value_,t=this.dependenciesState_===IDerivationState_.NOT_TRACKING_,n=this.computeValue_(!0);isSpyEnabled()&&spyReport({observableKind:"computed",debugObjectName:this.name_,object:this.scope_,type:"update",oldValue:this.value_,newValue:n});var r=t||isCaughtException(e)||isCaughtException(n)||!this.equals_(e,n);return r&&(this.value_=n),r},t.computeValue_=function(e){this.isComputing_=!0;var t,n=allowStateChangesStart(!1);if(e)t=trackDerivedFunction(this,this.derivation,this.scope_);else if(!0===globalState.disableErrorBoundaries)t=this.derivation.call(this.scope_);else try{t=this.derivation.call(this.scope_)}catch(e){t=new CaughtException(e)}return allowStateChangesEnd(n),this.isComputing_=!1,t},t.suspend_=function(){this.keepAlive_||(clearObserving(this),this.value_=void 0)},t.observe_=function(e,t){var n=this,r=!0,a=void 0;return autorun(function(){var o=n.get();if(!r||t){var i=untrackedStart();e({observableKind:"computed",debugObjectName:n.name_,type:UPDATE,object:n,newValue:o,oldValue:a}),untrackedEnd(i)}r=!1,a=o})},t.warnAboutUntrackedRead_=function(){!0===this.requiresReaction_&&die("[mobx] Computed value "+this.name_+" is read outside a reactive context"),this.isTracing_!==TraceMode.NONE&&console.log("[mobx.trace] '"+this.name_+"' is being read outside a reactive context. Doing a full recompute"),globalState.computedRequiresReaction&&console.warn("[mobx] Computed value "+this.name_+" is being read outside a reactive context. Doing a full recompute")},t.toString=function(){return this.name_+"["+this.derivation.toString()+"]"},t.valueOf=function(){return toPrimitive(this.get())},t[_Symbol$toPrimitive$1]=function(){return this.valueOf()},e}(),isComputedValue=createInstanceofPredicate("ComputedValue",ComputedValue);!function(e){e[e.NOT_TRACKING_=-1]="NOT_TRACKING_",e[e.UP_TO_DATE_=0]="UP_TO_DATE_",e[e.POSSIBLY_STALE_=1]="POSSIBLY_STALE_",e[e.STALE_=2]="STALE_"}(IDerivationState_||(IDerivationState_={})),function(e){e[e.NONE=0]="NONE",e[e.LOG=1]="LOG",e[e.BREAK=2]="BREAK"}(TraceMode||(TraceMode={}));var CaughtException=function(e){this.cause=void 0,this.cause=e};function isCaughtException(e){return e instanceof CaughtException}function shouldCompute(e){switch(e.dependenciesState_){case IDerivationState_.UP_TO_DATE_:return!1;case IDerivationState_.NOT_TRACKING_:case IDerivationState_.STALE_:return!0;case IDerivationState_.POSSIBLY_STALE_:for(var t=allowStateReadsStart(!0),n=untrackedStart(),r=e.observing_,a=r.length,o=0;o<a;o++){var i=r[o];if(isComputedValue(i)){if(globalState.disableErrorBoundaries)i.get();else try{i.get()}catch(e){return untrackedEnd(n),allowStateReadsEnd(t),!0}if(e.dependenciesState_===IDerivationState_.STALE_)return untrackedEnd(n),allowStateReadsEnd(t),!0}}return changeDependenciesStateTo0(e),untrackedEnd(n),allowStateReadsEnd(t),!1}}function isComputingDerivation(){return null!==globalState.trackingDerivation}function checkIfStateModificationsAreAllowed(e){var t=e.observers_.size>0;globalState.allowStateChanges||!t&&"always"!==globalState.enforceActions||console.warn("[MobX] "+(globalState.enforceActions?"Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: ":"Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: ")+e.name_)}function checkIfStateReadsAreAllowed(e){!globalState.allowStateReads&&globalState.observableRequiresReaction&&console.warn("[mobx] Observable "+e.name_+" being read outside a reactive context")}function trackDerivedFunction(e,t,n){var r=allowStateReadsStart(!0);changeDependenciesStateTo0(e),e.newObserving_=new Array(e.observing_.length+100),e.unboundDepsCount_=0,e.runId_=++globalState.runId;var a,o=globalState.trackingDerivation;if(globalState.trackingDerivation=e,globalState.inBatch++,!0===globalState.disableErrorBoundaries)a=t.call(n);else try{a=t.call(n)}catch(e){a=new CaughtException(e)}return globalState.inBatch--,globalState.trackingDerivation=o,bindDependencies(e),warnAboutDerivationWithoutDependencies(e),allowStateReadsEnd(r),a}function warnAboutDerivationWithoutDependencies(e){0===e.observing_.length&&(globalState.reactionRequiresObservable||e.requiresObservable_)&&console.warn("[mobx] Derivation "+e.name_+" is created/updated without reading any observable value")}function bindDependencies(e){for(var t=e.observing_,n=e.observing_=e.newObserving_,r=IDerivationState_.UP_TO_DATE_,a=0,o=e.unboundDepsCount_,i=0;i<o;i++){var s=n[i];0===s.diffValue_&&(s.diffValue_=1,a!==i&&(n[a]=s),a++),s.dependenciesState_>r&&(r=s.dependenciesState_)}for(n.length=a,e.newObserving_=null,o=t.length;o--;){var c=t[o];0===c.diffValue_&&removeObserver(c,e),c.diffValue_=0}for(;a--;){var l=n[a];1===l.diffValue_&&(l.diffValue_=0,addObserver(l,e))}r!==IDerivationState_.UP_TO_DATE_&&(e.dependenciesState_=r,e.onBecomeStale_())}function clearObserving(e){var t=e.observing_;e.observing_=[];for(var n=t.length;n--;)removeObserver(t[n],e);e.dependenciesState_=IDerivationState_.NOT_TRACKING_}function untracked(e){var t=untrackedStart();try{return e()}finally{untrackedEnd(t)}}function untrackedStart(){var e=globalState.trackingDerivation;return globalState.trackingDerivation=null,e}function untrackedEnd(e){globalState.trackingDerivation=e}function allowStateReadsStart(e){var t=globalState.allowStateReads;return globalState.allowStateReads=e,t}function allowStateReadsEnd(e){globalState.allowStateReads=e}function changeDependenciesStateTo0(e){if(e.dependenciesState_!==IDerivationState_.UP_TO_DATE_){e.dependenciesState_=IDerivationState_.UP_TO_DATE_;for(var t=e.observing_,n=t.length;n--;)t[n].lowestObserverState_=IDerivationState_.UP_TO_DATE_}}var persistentKeys=["mobxGuid","spyListeners","enforceActions","computedRequiresReaction","reactionRequiresObservable","observableRequiresReaction","allowStateReads","disableErrorBoundaries","runId","UNCHANGED","useProxies"],MobXGlobals=function(){this.version=6,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.useProxies=!0,this.verifyProxies=!1,this.safeDescriptors=!0},canMergeGlobalState=!0,isolateCalled=!1,globalState=function(){var e=getGlobal();return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(canMergeGlobalState=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==(new MobXGlobals).version&&(canMergeGlobalState=!1),canMergeGlobalState?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new MobXGlobals):(setTimeout(function(){isolateCalled||die(35)},1),new MobXGlobals)}();function isolateGlobalState(){if((globalState.pendingReactions.length||globalState.inBatch||globalState.isRunningReactions)&&die(36),isolateCalled=!0,canMergeGlobalState){var e=getGlobal();0==--e.__mobxInstanceCount&&(e.__mobxGlobals=void 0),globalState=new MobXGlobals}}function getGlobalState(){return globalState}function resetGlobalState(){var e=new MobXGlobals;for(var t in e)-1===persistentKeys.indexOf(t)&&(globalState[t]=e[t]);globalState.allowStateChanges=!globalState.enforceActions}function hasObservers(e){return e.observers_&&e.observers_.size>0}function getObservers(e){return e.observers_}function addObserver(e,t){e.observers_.add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function removeObserver(e,t){e.observers_.delete(t),0===e.observers_.size&&queueForUnobservation(e)}function queueForUnobservation(e){!1===e.isPendingUnobservation_&&(e.isPendingUnobservation_=!0,globalState.pendingUnobservations.push(e))}function startBatch(){globalState.inBatch++}function endBatch(){if(0==--globalState.inBatch){runReactions();for(var e=globalState.pendingUnobservations,t=0;t<e.length;t++){var n=e[t];n.isPendingUnobservation_=!1,0===n.observers_.size&&(n.isBeingObserved_&&(n.isBeingObserved_=!1,n.onBUO()),n instanceof ComputedValue&&n.suspend_())}globalState.pendingUnobservations=[]}}function reportObserved(e){checkIfStateReadsAreAllowed(e);var t=globalState.trackingDerivation;return null!==t?(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved_&&globalState.trackingContext&&(e.isBeingObserved_=!0,e.onBO())),!0):(0===e.observers_.size&&globalState.inBatch>0&&queueForUnobservation(e),!1)}function propagateChanged(e){e.lowestObserverState_!==IDerivationState_.STALE_&&(e.lowestObserverState_=IDerivationState_.STALE_,e.observers_.forEach(function(t){t.dependenciesState_===IDerivationState_.UP_TO_DATE_&&(t.isTracing_!==TraceMode.NONE&&logTraceInfo(t,e),t.onBecomeStale_()),t.dependenciesState_=IDerivationState_.STALE_}))}function propagateChangeConfirmed(e){e.lowestObserverState_!==IDerivationState_.STALE_&&(e.lowestObserverState_=IDerivationState_.STALE_,e.observers_.forEach(function(t){t.dependenciesState_===IDerivationState_.POSSIBLY_STALE_?t.dependenciesState_=IDerivationState_.STALE_:t.dependenciesState_===IDerivationState_.UP_TO_DATE_&&(e.lowestObserverState_=IDerivationState_.UP_TO_DATE_)}))}function propagateMaybeChanged(e){e.lowestObserverState_===IDerivationState_.UP_TO_DATE_&&(e.lowestObserverState_=IDerivationState_.POSSIBLY_STALE_,e.observers_.forEach(function(t){t.dependenciesState_===IDerivationState_.UP_TO_DATE_&&(t.dependenciesState_=IDerivationState_.POSSIBLY_STALE_,t.isTracing_!==TraceMode.NONE&&logTraceInfo(t,e),t.onBecomeStale_())}))}function logTraceInfo(e,t){if(console.log("[mobx.trace] '"+e.name_+"' is invalidated due to a change in: '"+t.name_+"'"),e.isTracing_===TraceMode.BREAK){var n=[];printDepTree(getDependencyTree(e),n,1),new Function("debugger;\n/*\nTracing '"+e.name_+"'\n\nYou are entering this break point because derivation '"+e.name_+"' is being traced and '"+t.name_+"' is now forcing it to update.\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\n\n"+(e instanceof ComputedValue?e.derivation.toString().replace(/[*]\//g,"/"):"")+"\n\nThe dependencies for this derivation are:\n\n"+n.join("\n")+"\n*/\n ")()}}function printDepTree(e,t,n){t.length>=1e3?t.push("(and many more)"):(t.push(""+new Array(n).join("\t")+e.name),e.dependencies&&e.dependencies.forEach(function(e){return printDepTree(e,t,n+1)}))}var Reaction=function(){function e(e,t,n,r){void 0===e&&(e="Reaction@"+getNextId()),void 0===r&&(r=!1),this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=IDerivationState_.NOT_TRACKING_,this.diffValue_=0,this.runId_=0,this.unboundDepsCount_=0,this.mapid_="#"+getNextId(),this.isDisposed_=!1,this.isScheduled_=!1,this.isTrackPending_=!1,this.isRunning_=!1,this.isTracing_=TraceMode.NONE,this.name_=e,this.onInvalidate_=t,this.errorHandler_=n,this.requiresObservable_=r}var t=e.prototype;return t.onBecomeStale_=function(){this.schedule_()},t.schedule_=function(){this.isScheduled_||(this.isScheduled_=!0,globalState.pendingReactions.push(this),runReactions())},t.isScheduled=function(){return this.isScheduled_},t.runReaction_=function(){if(!this.isDisposed_){startBatch(),this.isScheduled_=!1;var e=globalState.trackingContext;if(globalState.trackingContext=this,shouldCompute(this)){this.isTrackPending_=!0;try{this.onInvalidate_(),this.isTrackPending_&&isSpyEnabled()&&spyReport({name:this.name_,type:"scheduled-reaction"})}catch(e){this.reportExceptionInDerivation_(e)}}globalState.trackingContext=e,endBatch()}},t.track=function(e){if(!this.isDisposed_){startBatch();var t,n=isSpyEnabled();n&&(t=Date.now(),spyReportStart({name:this.name_,type:"reaction"})),this.isRunning_=!0;var r=globalState.trackingContext;globalState.trackingContext=this;var a=trackDerivedFunction(this,e,void 0);globalState.trackingContext=r,this.isRunning_=!1,this.isTrackPending_=!1,this.isDisposed_&&clearObserving(this),isCaughtException(a)&&this.reportExceptionInDerivation_(a.cause),n&&spyReportEnd({time:Date.now()-t}),endBatch()}},t.reportExceptionInDerivation_=function(e){var t=this;if(this.errorHandler_)this.errorHandler_(e,this);else{if(globalState.disableErrorBoundaries)throw e;var n="[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '"+this+"'";globalState.suppressReactionErrors?console.warn("[mobx] (error in reaction '"+this.name_+"' suppressed, fix error of causing action below)"):console.error(n,e),isSpyEnabled()&&spyReport({type:"error",name:this.name_,message:n,error:""+e}),globalState.globalReactionErrorHandlers.forEach(function(n){return n(e,t)})}},t.dispose=function(){this.isDisposed_||(this.isDisposed_=!0,this.isRunning_||(startBatch(),clearObserving(this),endBatch()))},t.getDisposer_=function(){var e=this.dispose.bind(this);return e[$mobx]=this,e},t.toString=function(){return"Reaction["+this.name_+"]"},t.trace=function(e){void 0===e&&(e=!1),trace(this,e)},e}();function onReactionError(e){return globalState.globalReactionErrorHandlers.push(e),function(){var t=globalState.globalReactionErrorHandlers.indexOf(e);t>=0&&globalState.globalReactionErrorHandlers.splice(t,1)}}var MAX_REACTION_ITERATIONS=100,reactionScheduler=function(e){return e()};function runReactions(){globalState.inBatch>0||globalState.isRunningReactions||reactionScheduler(runReactionsHelper)}function runReactionsHelper(){globalState.isRunningReactions=!0;for(var e=globalState.pendingReactions,t=0;e.length>0;){++t===MAX_REACTION_ITERATIONS&&(console.error("Reaction doesn't converge to a stable state after "+MAX_REACTION_ITERATIONS+" iterations. Probably there is a cycle in the reactive function: "+e[0]),e.splice(0));for(var n=e.splice(0),r=0,a=n.length;r<a;r++)n[r].runReaction_()}globalState.isRunningReactions=!1}var isReaction=createInstanceofPredicate("Reaction",Reaction);function setReactionScheduler(e){var t=reactionScheduler;reactionScheduler=function(n){return e(function(){return t(n)})}}function isSpyEnabled(){return!!globalState.spyListeners.length}function spyReport(e){if(globalState.spyListeners.length)for(var t=globalState.spyListeners,n=0,r=t.length;n<r;n++)t[n](e)}function spyReportStart(e){spyReport(_extends({},e,{spyReportStart:!0}))}var END_EVENT={type:"report-end",spyReportEnd:!0};function spyReportEnd(e){spyReport(e?_extends({},e,{type:"report-end",spyReportEnd:!0}):END_EVENT)}function spy(e){return globalState.spyListeners.push(e),once(function(){globalState.spyListeners=globalState.spyListeners.filter(function(t){return t!==e})})}var ACTION="action",ACTION_BOUND="action.bound",AUTOACTION="autoAction",AUTOACTION_BOUND="autoAction.bound",DEFAULT_ACTION_NAME="<unnamed action>",actionAnnotation=createActionAnnotation(ACTION),actionBoundAnnotation=createActionAnnotation(ACTION_BOUND,{bound:!0}),autoActionAnnotation=createActionAnnotation(AUTOACTION,{autoAction:!0}),autoActionBoundAnnotation=createActionAnnotation(AUTOACTION_BOUND,{autoAction:!0,bound:!0});function createActionFactory(e){return function(t,n){return isFunction(t)?createAction(t.name||DEFAULT_ACTION_NAME,t,e):isFunction(n)?createAction(t,n,e):isStringish(n)?storeAnnotation(t,n,e?autoActionAnnotation:actionAnnotation):isStringish(t)?createDecoratorAnnotation(createActionAnnotation(e?AUTOACTION:ACTION,{name:t,autoAction:e})):void die("Invalid arguments for `action`")}}var action=createActionFactory(!1);Object.assign(action,actionAnnotation);var autoAction=createActionFactory(!0);function runInAction(e){return executeAction(e.name||DEFAULT_ACTION_NAME,!1,e,this,void 0)}function isAction(e){return isFunction(e)&&!0===e.isMobxAction}function autorun(e,t){void 0===t&&(t=EMPTY_OBJECT),isFunction(e)||die("Autorun expects a function as first argument"),isAction(e)&&die("Autorun does not accept actions since actions are untrackable");var n,r=t&&t.name||e.name||"Autorun@"+getNextId();if(!t.scheduler&&!t.delay)n=new Reaction(r,function(){this.track(i)},t.onError,t.requiresObservable);else{var a=createSchedulerFromOptions(t),o=!1;n=new Reaction(r,function(){o||(o=!0,a(function(){o=!1,n.isDisposed_||n.track(i)}))},t.onError,t.requiresObservable)}function i(){e(n)}return n.schedule_(),n.getDisposer_()}Object.assign(autoAction,autoActionAnnotation),action.bound=createDecoratorAnnotation(actionBoundAnnotation),autoAction.bound=createDecoratorAnnotation(autoActionBoundAnnotation);var run=function(e){return e()};function createSchedulerFromOptions(e){return e.scheduler?e.scheduler:e.delay?function(t){return setTimeout(t,e.delay)}:run}function reaction(e,t,n){void 0===n&&(n=EMPTY_OBJECT),isFunction(e)&&isFunction(t)||die("First and second argument to reaction should be functions"),isPlainObject(n)||die("Third argument of reactions should be an object");var r,a=n.name||"Reaction@"+getNextId(),o=action(a,n.onError?wrapErrorHandler(n.onError,t):t),i=!n.scheduler&&!n.delay,s=createSchedulerFromOptions(n),c=!0,l=!1,u=void 0,d=n.compareStructural?comparer.structural:n.equals||comparer.default,b=new Reaction(a,function(){c||i?h():l||(l=!0,s(h))},n.onError,n.requiresObservable);function h(){if(l=!1,!b.isDisposed_){var t=!1;b.track(function(){var n=allowStateChanges(!1,function(){return e(b)});t=c||!d(r,n),u=r,r=n}),c&&n.fireImmediately?o(r,u,b):!c&&t&&o(r,u,b),c=!1}}return b.schedule_(),b.getDisposer_()}function wrapErrorHandler(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}var ON_BECOME_OBSERVED="onBO",ON_BECOME_UNOBSERVED="onBUO";function onBecomeObserved(e,t,n){return interceptHook(ON_BECOME_OBSERVED,e,t,n)}function onBecomeUnobserved(e,t,n){return interceptHook(ON_BECOME_UNOBSERVED,e,t,n)}function interceptHook(e,t,n,r){var a="function"==typeof r?getAtom(t,n):getAtom(t),o=isFunction(r)?r:n,i=e+"L";return a[i]?a[i].add(o):a[i]=new Set([o]),function(){var e=a[i];e&&(e.delete(o),0===e.size&&delete a[i])}}var NEVER="never",ALWAYS="always",OBSERVED="observed";function configure(e){!0===e.isolateGlobalState&&isolateGlobalState();var t=e.useProxies,n=e.enforceActions;if(void 0!==t&&(globalState.useProxies=t===ALWAYS||t!==NEVER&&"undefined"!=typeof Proxy),"ifavailable"===t&&(globalState.verifyProxies=!0),void 0!==n){var r=n===ALWAYS?ALWAYS:n===OBSERVED;globalState.enforceActions=r,globalState.allowStateChanges=!0!==r&&r!==ALWAYS}["computedRequiresReaction","reactionRequiresObservable","observableRequiresReaction","disableErrorBoundaries","safeDescriptors"].forEach(function(t){t in e&&(globalState[t]=!!e[t])}),globalState.allowStateReads=!globalState.observableRequiresReaction,!0===globalState.disableErrorBoundaries&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&setReactionScheduler(e.reactionScheduler)}function extendObservable(e,t,n,r){arguments.length>4&&die("'extendObservable' expected 2-4 arguments"),"object"!=typeof e&&die("'extendObservable' expects an object as first argument"),isObservableMap(e)&&die("'extendObservable' should not be used on maps, use map.merge instead"),isPlainObject(t)||die("'extendObservabe' only accepts plain objects as second argument"),(isObservable(t)||isObservable(n))&&die("Extending an object with another observable (object) is not supported");var a=getOwnPropertyDescriptors(t),o=asObservableObject(e,r)[$mobx];startBatch();try{ownKeys(a).forEach(function(e){o.extend_(e,a[e],!n||(!(e in n)||n[e]))})}finally{endBatch()}return e}function getDependencyTree(e,t){return nodeToDependencyTree(getAtom(e,t))}function nodeToDependencyTree(e){var t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=unique(e.observing_).map(nodeToDependencyTree)),t}function getObserverTree(e,t){return nodeToObserverTree(getAtom(e,t))}function nodeToObserverTree(e){var t={name:e.name_};return hasObservers(e)&&(t.observers=Array.from(getObservers(e)).map(nodeToObserverTree)),t}function unique(e){return Array.from(new Set(e))}var generatorId=0;function FlowCancellationError(){this.message="FLOW_CANCELLED"}function isFlowCancellationError(e){return e instanceof FlowCancellationError}FlowCancellationError.prototype=Object.create(Error.prototype);var flowAnnotation=createFlowAnnotation("flow"),flow=Object.assign(function(e,t){if(isStringish(t))return storeAnnotation(e,t,flowAnnotation);1!==arguments.length&&die("Flow expects single argument with generator function");var n=e,r=n.name||"<unnamed flow>",a=function(){var e,t=arguments,a=++generatorId,o=action(r+" - runid: "+a+" - init",n).apply(this,t),i=void 0,s=new Promise(function(t,n){var s=0;function c(e){var t;i=void 0;try{t=action(r+" - runid: "+a+" - yield "+s++,o.next).call(o,e)}catch(e){return n(e)}u(t)}function l(e){var t;i=void 0;try{t=action(r+" - runid: "+a+" - yield "+s++,o.throw).call(o,e)}catch(e){return n(e)}u(t)}function u(e){if(!isFunction(null==e?void 0:e.then))return e.done?t(e.value):(i=Promise.resolve(e.value)).then(c,l);e.then(u,n)}e=n,c(void 0)});return s.cancel=action(r+" - runid: "+a+" - cancel",function(){try{i&&cancelPromise(i);var t=o.return(void 0),n=Promise.resolve(t.value);n.then(noop,noop),cancelPromise(n),e(new FlowCancellationError)}catch(t){e(t)}}),s};return a.isMobXFlow=!0,a},flowAnnotation);function cancelPromise(e){isFunction(e.cancel)&&e.cancel()}function flowResult(e){return e}function isFlow(e){return!0===(null==e?void 0:e.isMobXFlow)}function interceptReads(e,t,n){var r;if(isObservableMap(e)||isObservableArray(e)||isObservableValue(e))r=getAdministration(e);else{if(!isObservableObject(e))return die("Expected observable map, object or array as first array");if(!isStringish(t))return die("InterceptReads can only be used with a specific property, not with an object in general");r=getAdministration(e,t)}return void 0!==r.dehancer?die("An intercept reader was already established"):(r.dehancer="function"==typeof t?t:n,function(){r.dehancer=void 0})}function intercept(e,t,n){return isFunction(n)?interceptProperty(e,t,n):interceptInterceptable(e,t)}function interceptInterceptable(e,t){return getAdministration(e).intercept_(t)}function interceptProperty(e,t,n){return getAdministration(e,t).intercept_(n)}function _isComputed(e,t){if(void 0!==t){if(!1===isObservableObject(e))return!1;if(!e[$mobx].values_.has(t))return!1;var n=getAtom(e,t);return isComputedValue(n)}return isComputedValue(e)}function isComputed(e){return arguments.length>1?die("isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property"):_isComputed(e)}function isComputedProp(e,t){return isStringish(t)?_isComputed(e,t):die("isComputed expected a property name as second argument")}function _isObservable(e,t){return!!e&&(void 0!==t?isObservableMap(e)||isObservableArray(e)?die("isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead."):!!isObservableObject(e)&&e[$mobx].values_.has(t):isObservableObject(e)||!!e[$mobx]||isAtom(e)||isReaction(e)||isComputedValue(e))}function isObservable(e){return 1!==arguments.length&&die("isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property"),_isObservable(e)}function isObservableProp(e,t){return isStringish(t)?_isObservable(e,t):die("expected a property name as second argument")}function keys(e){return isObservableObject(e)?e[$mobx].keys_():isObservableMap(e)||isObservableSet(e)?Array.from(e.keys()):isObservableArray(e)?e.map(function(e,t){return t}):void die(5)}function values(e){return isObservableObject(e)?keys(e).map(function(t){return e[t]}):isObservableMap(e)?keys(e).map(function(t){return e.get(t)}):isObservableSet(e)?Array.from(e.values()):isObservableArray(e)?e.slice():void die(6)}function entries(e){return isObservableObject(e)?keys(e).map(function(t){return[t,e[t]]}):isObservableMap(e)?keys(e).map(function(t){return[t,e.get(t)]}):isObservableSet(e)?Array.from(e.entries()):isObservableArray(e)?e.map(function(e,t){return[t,e]}):void die(7)}function set(e,t,n){if(2!==arguments.length||isObservableSet(e))isObservableObject(e)?e[$mobx].set_(t,n):isObservableMap(e)?e.set(t,n):isObservableSet(e)?e.add(t):isObservableArray(e)?("number"!=typeof t&&(t=parseInt(t,10)),t<0&&die("Invalid index: '"+t+"'"),startBatch(),t>=e.length&&(e.length=t+1),e[t]=n,endBatch()):die(8);else{startBatch();var r=t;try{for(var a in r)set(e,a,r[a])}finally{endBatch()}}}function remove(e,t){isObservableObject(e)?e[$mobx].delete_(t):isObservableMap(e)?e.delete(t):isObservableSet(e)?e.delete(t):isObservableArray(e)?("number"!=typeof t&&(t=parseInt(t,10)),e.splice(t,1)):die(9)}function has(e,t){return isObservableObject(e)?e[$mobx].has_(t):isObservableMap(e)?e.has(t):isObservableSet(e)?e.has(t):isObservableArray(e)?t>=0&&t<e.length:void die(10)}function get(e,t){if(has(e,t))return isObservableObject(e)?e[$mobx].get_(t):isObservableMap(e)?e.get(t):isObservableArray(e)?e[t]:void die(11)}function observe(e,t,n,r){return isFunction(n)?observeObservableProperty(e,t,n,r):observeObservable(e,t,n)}function observeObservable(e,t,n){return getAdministration(e).observe_(t,n)}function observeObservableProperty(e,t,n,r){return getAdministration(e,t).observe_(n,r)}function cache(e,t,n){return e.set(t,n),n}function toJSHelper(e,t){if(null==e||"object"!=typeof e||e instanceof Date||!isObservable(e))return e;if(isObservableValue(e))return toJSHelper(e.get(),t);if(t.has(e))return t.get(e);if(isObservableArray(e)){var n=cache(t,e,new Array(e.length));return e.forEach(function(e,r){n[r]=toJSHelper(e,t)}),n}if(isObservableSet(e)){var r=cache(t,e,new Set);return e.forEach(function(e){r.add(toJSHelper(e,t))}),r}if(isObservableMap(e)){var a=cache(t,e,new Map);return e.forEach(function(e,n){a.set(n,toJSHelper(e,t))}),a}keys(e);var o=cache(t,e,{});return getPlainObjectKeys(e).forEach(function(n){o[n]=toJSHelper(e[n],t)}),o}function toJS(e,t){return t&&die("toJS no longer supports options"),toJSHelper(e,new Map)}function trace(){for(var e=!1,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];"boolean"==typeof n[n.length-1]&&(e=n.pop());var a=getAtomFromArgs(n);if(!a)return die("'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly");a.isTracing_===TraceMode.NONE&&console.log("[mobx.trace] '"+a.name_+"' tracing enabled"),a.isTracing_=e?TraceMode.BREAK:TraceMode.LOG}function getAtomFromArgs(e){switch(e.length){case 0:return globalState.trackingDerivation;case 1:return getAtom(e[0]);case 2:return getAtom(e[0],e[1])}}function transaction(e,t){void 0===t&&(t=void 0),startBatch();try{return e.apply(t)}finally{endBatch()}}function when(e,t,n){return 1===arguments.length||t&&"object"==typeof t?whenPromise(e,t):_when(e,t,n||{})}function _when(e,t,n){var r;"number"==typeof n.timeout&&(r=setTimeout(function(){if(!o[$mobx].isDisposed_){o();var e=new Error("WHEN_TIMEOUT");if(!n.onError)throw e;n.onError(e)}},n.timeout)),n.name=n.name||"When@"+getNextId();var a=createAction(n.name+"-effect",t),o=autorun(function(t){allowStateChanges(!1,e)&&(t.dispose(),r&&clearTimeout(r),a())},n);return o}function whenPromise(e,t){if(t&&t.onError)return die("the options 'onError' and 'promise' cannot be combined");var n,r=new Promise(function(r,a){var o=_when(e,r,_extends({},t,{onError:a}));n=function(){o(),a("WHEN_CANCELLED")}});return r.cancel=n,r}function getAdm(e){return e[$mobx]}var objectProxyTraps={has:function(e,t){return globalState.trackingDerivation&&warnAboutProxyRequirement("detect new properties using the 'in' operator. Use 'has' from 'mobx' instead."),getAdm(e).has_(t)},get:function(e,t){return getAdm(e).get_(t)},set:function(e,t,n){var r;return!!isStringish(t)&&(getAdm(e).values_.has(t)||warnAboutProxyRequirement("add a new observable property through direct assignment. Use 'set' from 'mobx' instead."),null==(r=getAdm(e).set_(t,n,!0))||r)},deleteProperty:function(e,t){var n;return warnAboutProxyRequirement("delete properties from an observable object. Use 'remove' from 'mobx' instead."),!!isStringish(t)&&(null==(n=getAdm(e).delete_(t,!0))||n)},defineProperty:function(e,t,n){var r;return warnAboutProxyRequirement("define property on an observable object. Use 'defineProperty' from 'mobx' instead."),null==(r=getAdm(e).defineProperty_(t,n))||r},ownKeys:function(e){return globalState.trackingDerivation&&warnAboutProxyRequirement("iterate keys to detect added / removed properties. Use `keys` from 'mobx' instead."),getAdm(e).ownKeys_()},preventExtensions:function(e){die(13)}};function asDynamicObservableObject(e,t){var n,r;return assertProxies(),null!=(r=(n=(e=asObservableObject(e,t))[$mobx]).proxy_)?r:n.proxy_=new Proxy(e,objectProxyTraps)}function hasInterceptors(e){return void 0!==e.interceptors_&&e.interceptors_.length>0}function registerInterceptor(e,t){var n=e.interceptors_||(e.interceptors_=[]);return n.push(t),once(function(){var e=n.indexOf(t);-1!==e&&n.splice(e,1)})}function interceptChange(e,t){var n=untrackedStart();try{for(var r=[].concat(e.interceptors_||[]),a=0,o=r.length;a<o&&((t=r[a](t))&&!t.type&&die(14),t);a++);return t}finally{untrackedEnd(n)}}function hasListeners(e){return void 0!==e.changeListeners_&&e.changeListeners_.length>0}function registerListener(e,t){var n=e.changeListeners_||(e.changeListeners_=[]);return n.push(t),once(function(){var e=n.indexOf(t);-1!==e&&n.splice(e,1)})}function notifyListeners(e,t){var n=untrackedStart(),r=e.changeListeners_;if(r){for(var a=0,o=(r=r.slice()).length;a<o;a++)r[a](t);untrackedEnd(n)}}function makeObservable(e,t,n){var r=asObservableObject(e,n)[$mobx];startBatch();try{null!=t||(t=collectStoredAnnotations(e)),ownKeys(t).forEach(function(e){return r.make_(e,t[e])})}finally{endBatch()}return e}function makeAutoObservable(e,t,n){if(isPlainObject(e)||isPlainObject(Object.getPrototypeOf(e))||die("'makeAutoObservable' can only be used for classes that don't have a superclass"),isObservableObject(e)&&die("makeAutoObservable can only be used on objects not already made observable"),isPlainObject(e))return extendObservable(e,e,t,n);var r=asObservableObject(e,n)[$mobx];startBatch();try{if(e[inferredAnnotationsSymbol])for(var a in e[inferredAnnotationsSymbol])r.make_(a,e[inferredAnnotationsSymbol][a]);else for(var o,i=((o={})[$mobx]=1,o[inferredAnnotationsSymbol]=1,o.constructor=1,o),s=function(e){i[e]||(i[e]=1,r.make_(e,!t||(!(e in t)||t[e])))},c=e;c&&c!==objectPrototype;)ownKeys(c).forEach(s),c=Object.getPrototypeOf(c)}finally{endBatch()}return e}var SPLICE="splice",UPDATE="update",MAX_SPLICE_SIZE=1e4,arrayTraps={get:function(e,t){var n=e[$mobx];return t===$mobx?n:"length"===t?n.getArrayLength_():"string"!=typeof t||isNaN(t)?hasProp(arrayExtensions,t)?arrayExtensions[t]:e[t]:n.get_(parseInt(t))},set:function(e,t,n){var r=e[$mobx];return"length"===t&&r.setArrayLength_(n),"symbol"==typeof t||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions:function(){die(15)}},ObservableArrayAdministration=function(){function e(e,t,n,r){this.owned_=void 0,this.legacyMode_=void 0,this.atom_=void 0,this.values_=[],this.interceptors_=void 0,this.changeListeners_=void 0,this.enhancer_=void 0,this.dehancer=void 0,this.proxy_=void 0,this.lastKnownLength_=0,this.owned_=n,this.legacyMode_=r,this.atom_=new Atom(e||"ObservableArray@"+getNextId()),this.enhancer_=function(n,r){return t(n,r,e+"[..]")}}var t=e.prototype;return t.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},t.dehanceValues_=function(e){return void 0!==this.dehancer&&e.length>0?e.map(this.dehancer):e},t.intercept_=function(e){return registerInterceptor(this,e)},t.observe_=function(e,t){return void 0===t&&(t=!1),t&&e({observableKind:"array",object:this.proxy_,debugObjectName:this.atom_.name_,type:"splice",index:0,added:this.values_.slice(),addedCount:this.values_.length,removed:[],removedCount:0}),registerListener(this,e)},t.getArrayLength_=function(){return this.atom_.reportObserved(),this.values_.length},t.setArrayLength_=function(e){("number"!=typeof e||e<0)&&die("Out of range: "+e);var t=this.values_.length;if(e!==t)if(e>t){for(var n=new Array(e-t),r=0;r<e-t;r++)n[r]=void 0;this.spliceWithArray_(t,0,n)}else this.spliceWithArray_(e,t-e)},t.updateArrayLength_=function(e,t){e!==this.lastKnownLength_&&die(16),this.lastKnownLength_+=t,this.legacyMode_&&t>0&&reserveArrayBuffer(e+t+1)},t.spliceWithArray_=function(e,t,n){var r=this;checkIfStateModificationsAreAllowed(this.atom_);var a=this.values_.length;if(void 0===e?e=0:e>a?e=a:e<0&&(e=Math.max(0,a+e)),t=1===arguments.length?a-e:null==t?0:Math.max(0,Math.min(t,a-e)),void 0===n&&(n=EMPTY_ARRAY),hasInterceptors(this)){var o=interceptChange(this,{object:this.proxy_,type:SPLICE,index:e,removedCount:t,added:n});if(!o)return EMPTY_ARRAY;t=o.removedCount,n=o.added}n=0===n.length?n:n.map(function(e){return r.enhancer_(e,void 0)}),this.legacyMode_;var i=n.length-t;this.updateArrayLength_(a,i);var s=this.spliceItemsIntoValues_(e,t,n);return 0===t&&0===n.length||this.notifyArraySplice_(e,n,s),this.dehanceValues_(s)},t.spliceItemsIntoValues_=function(e,t,n){var r;if(n.length<MAX_SPLICE_SIZE)return(r=this.values_).splice.apply(r,[e,t].concat(n));var a=this.values_.slice(e,e+t),o=this.values_.slice(e+t);this.values_.length=e+n.length-t;for(var i=0;i<n.length;i++)this.values_[e+i]=n[i];for(var s=0;s<o.length;s++)this.values_[e+n.length+s]=o[s];return a},t.notifyArrayChildUpdate_=function(e,t,n){var r=!this.owned_&&isSpyEnabled(),a=hasListeners(this),o=a||r?{observableKind:"array",object:this.proxy_,type:UPDATE,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&spyReportStart(o),this.atom_.reportChanged(),a&¬ifyListeners(this,o),r&&spyReportEnd()},t.notifyArraySplice_=function(e,t,n){var r=!this.owned_&&isSpyEnabled(),a=hasListeners(this),o=a||r?{observableKind:"array",object:this.proxy_,debugObjectName:this.atom_.name_,type:SPLICE,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&spyReportStart(o),this.atom_.reportChanged(),a&¬ifyListeners(this,o),r&&spyReportEnd()},t.get_=function(e){if(e<this.values_.length)return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e]);console.warn("[mobx] Out of bounds read: "+e)},t.set_=function(e,t){var n=this.values_;if(e<n.length){checkIfStateModificationsAreAllowed(this.atom_);var r=n[e];if(hasInterceptors(this)){var a=interceptChange(this,{type:UPDATE,object:this.proxy_,index:e,newValue:t});if(!a)return;t=a.newValue}(t=this.enhancer_(t,r))!==r&&(n[e]=t,this.notifyArrayChildUpdate_(e,t,r))}else e===n.length?this.spliceWithArray_(e,0,[t]):die(17,e,n.length)},e}();function createObservableArray(e,t,n,r){void 0===n&&(n="ObservableArray@"+getNextId()),void 0===r&&(r=!1),assertProxies();var a=new ObservableArrayAdministration(n,t,r,!1);addHiddenFinalProp(a.values_,$mobx,a);var o=new Proxy(a.values_,arrayTraps);if(a.proxy_=o,e&&e.length){var i=allowStateChangesStart(!0);a.spliceWithArray_(0,0,e),allowStateChangesEnd(i)}return o}var arrayExtensions={clear:function(){return this.splice(0)},replace:function(e){var t=this[$mobx];return t.spliceWithArray_(0,t.values_.length,e)},toJSON:function(){return this.slice()},splice:function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),a=2;a<n;a++)r[a-2]=arguments[a];var o=this[$mobx];switch(arguments.length){case 0:return[];case 1:return o.spliceWithArray_(e);case 2:return o.spliceWithArray_(e,t)}return o.spliceWithArray_(e,t,r)},spliceWithArray:function(e,t,n){return this[$mobx].spliceWithArray_(e,t,n)},push:function(){for(var e=this[$mobx],t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.spliceWithArray_(e.values_.length,0,n),e.values_.length},pop:function(){return this.splice(Math.max(this[$mobx].values_.length-1,0),1)[0]},shift:function(){return this.splice(0,1)[0]},unshift:function(){for(var e=this[$mobx],t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.spliceWithArray_(0,0,n),e.values_.length},reverse:function(){return globalState.trackingDerivation&&die(37,"reverse"),this.replace(this.slice().reverse()),this},sort:function(){globalState.trackingDerivation&&die(37,"sort");var e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove:function(e){var t=this[$mobx],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};function addArrayExtension(e,t){"function"==typeof Array.prototype[e]&&(arrayExtensions[e]=t(e))}function simpleFunc(e){return function(){var t=this[$mobx];t.atom_.reportObserved();var n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function mapLikeFunc(e){return function(t,n){var r=this,a=this[$mobx];return a.atom_.reportObserved(),a.dehanceValues_(a.values_)[e](function(e,a){return t.call(n,e,a,r)})}}function reduceLikeFunc(e){return function(){var t=this,n=this[$mobx];n.atom_.reportObserved();var r=n.dehanceValues_(n.values_),a=arguments[0];return arguments[0]=function(e,n,r){return a(e,n,r,t)},r[e].apply(r,arguments)}}addArrayExtension("concat",simpleFunc),addArrayExtension("flat",simpleFunc),addArrayExtension("includes",simpleFunc),addArrayExtension("indexOf",simpleFunc),addArrayExtension("join",simpleFunc),addArrayExtension("lastIndexOf",simpleFunc),addArrayExtension("slice",simpleFunc),addArrayExtension("toString",simpleFunc),addArrayExtension("toLocaleString",simpleFunc),addArrayExtension("every",mapLikeFunc),addArrayExtension("filter",mapLikeFunc),addArrayExtension("find",mapLikeFunc),addArrayExtension("findIndex",mapLikeFunc),addArrayExtension("flatMap",mapLikeFunc),addArrayExtension("forEach",mapLikeFunc),addArrayExtension("map",mapLikeFunc),addArrayExtension("some",mapLikeFunc),addArrayExtension("reduce",reduceLikeFunc),addArrayExtension("reduceRight",reduceLikeFunc);var _Symbol$iterator,_Symbol$toStringTag,isObservableArrayAdministration=createInstanceofPredicate("ObservableArrayAdministration",ObservableArrayAdministration);function isObservableArray(e){return isObject(e)&&isObservableArrayAdministration(e[$mobx])}var ObservableMapMarker={},ADD="add",DELETE="delete";_Symbol$iterator=Symbol.iterator,_Symbol$toStringTag=Symbol.toStringTag;var _Symbol$iterator$1,_Symbol$toStringTag$1,ObservableMap=function(){function e(e,t,n){void 0===t&&(t=deepEnhancer),void 0===n&&(n="ObservableMap@"+getNextId()),this.enhancer_=void 0,this.name_=void 0,this[$mobx]=ObservableMapMarker,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,isFunction(Map)||die(18),this.keysAtom_=createAtom(this.name_+".keys()"),this.data_=new Map,this.hasMap_=new Map,this.merge(e)}var t=e.prototype;return t.has_=function(e){return this.data_.has(e)},t.has=function(e){var t=this;if(!globalState.trackingDerivation)return this.has_(e);var n=this.hasMap_.get(e);if(!n){var r=n=new ObservableValue(this.has_(e),referenceEnhancer,this.name_+"."+stringifyKey(e)+"?",!1);this.hasMap_.set(e,r),onBecomeUnobserved(r,function(){return t.hasMap_.delete(e)})}return n.get()},t.set=function(e,t){var n=this.has_(e);if(hasInterceptors(this)){var r=interceptChange(this,{type:n?UPDATE:ADD,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.updateValue_(e,t):this.addValue_(e,t),this},t.delete=function(e){var t=this;if((checkIfStateModificationsAreAllowed(this.keysAtom_),hasInterceptors(this))&&!interceptChange(this,{type:DELETE,object:this,name:e}))return!1;if(this.has_(e)){var n=isSpyEnabled(),r=hasListeners(this),a=r||n?{observableKind:"map",debugObjectName:this.name_,type:DELETE,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return n&&spyReportStart(a),transaction(function(){t.keysAtom_.reportChanged(),t.updateHasMapEntry_(e,!1),t.data_.get(e).setNewValue_(void 0),t.data_.delete(e)}),r&¬ifyListeners(this,a),n&&spyReportEnd(),!0}return!1},t.updateHasMapEntry_=function(e,t){var n=this.hasMap_.get(e);n&&n.setNewValue_(t)},t.updateValue_=function(e,t){var n=this.data_.get(e);if((t=n.prepareNewValue_(t))!==globalState.UNCHANGED){var r=isSpyEnabled(),a=hasListeners(this),o=a||r?{observableKind:"map",debugObjectName:this.name_,type:UPDATE,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&spyReportStart(o),n.setNewValue_(t),a&¬ifyListeners(this,o),r&&spyReportEnd()}},t.addValue_=function(e,t){var n=this;checkIfStateModificationsAreAllowed(this.keysAtom_),transaction(function(){var r=new ObservableValue(t,n.enhancer_,n.name_+"."+stringifyKey(e),!1);n.data_.set(e,r),t=r.value_,n.updateHasMapEntry_(e,!0),n.keysAtom_.reportChanged()});var r=isSpyEnabled(),a=hasListeners(this),o=a||r?{observableKind:"map",debugObjectName:this.name_,type:ADD,object:this,name:e,newValue:t}:null;r&&spyReportStart(o),a&¬ifyListeners(this,o),r&&spyReportEnd()},t.get=function(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)},t.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},t.keys=function(){return this.keysAtom_.reportObserved(),this.data_.keys()},t.values=function(){var e=this,t=this.keys();return makeIterable({next:function(){var n=t.next(),r=n.done,a=n.value;return{done:r,value:r?void 0:e.get(a)}}})},t.entries=function(){var e=this,t=this.keys();return makeIterable({next:function(){var n=t.next(),r=n.done,a=n.value;return{done:r,value:r?void 0:[a,e.get(a)]}}})},t[_Symbol$iterator]=function(){return this.entries()},t.forEach=function(e,t){for(var n,r=_createForOfIteratorHelperLoose(this);!(n=r()).done;){var a=n.value,o=a[0],i=a[1];e.call(t,i,o,this)}},t.merge=function(e){var t=this;return isObservableMap(e)&&(e=new Map(e)),transaction(function(){isPlainObject(e)?getPlainObjectKeys(e).forEach(function(n){return t.set(n,e[n])}):Array.isArray(e)?e.forEach(function(e){var n=e[0],r=e[1];return t.set(n,r)}):isES6Map(e)?(e.constructor!==Map&&die(19,e),e.forEach(function(e,n){return t.set(n,e)})):null!=e&&die(20,e)}),this},t.clear=function(){var e=this;transaction(function(){untracked(function(){for(var t,n=_createForOfIteratorHelperLoose(e.keys());!(t=n()).done;){var r=t.value;e.delete(r)}})})},t.replace=function(e){var t=this;return transaction(function(){for(var n,r=convertToMap(e),a=new Map,o=!1,i=_createForOfIteratorHelperLoose(t.data_.keys());!(n=i()).done;){var s=n.value;if(!r.has(s))if(t.delete(s))o=!0;else{var c=t.data_.get(s);a.set(s,c)}}for(var l,u=_createForOfIteratorHelperLoose(r.entries());!(l=u()).done;){var d=l.value,b=d[0],h=d[1],p=t.data_.has(b);if(t.set(b,h),t.data_.has(b)){var v=t.data_.get(b);a.set(b,v),p||(o=!0)}}if(!o)if(t.data_.size!==a.size)t.keysAtom_.reportChanged();else for(var f=t.data_.keys(),_=a.keys(),g=f.next(),m=_.next();!g.done;){if(g.value!==m.value){t.keysAtom_.reportChanged();break}g=f.next(),m=_.next()}t.data_=a}),this},t.toString=function(){return"[object ObservableMap]"},t.toJSON=function(){return Array.from(this)},t.observe_=function(e,t){return!0===t&&die("`observe` doesn't support fireImmediately=true in combination with maps."),registerListener(this,e)},t.intercept_=function(e){return registerInterceptor(this,e)},_createClass(e,[{key:"size",get:function(){return this.keysAtom_.reportObserved(),this.data_.size}},{key:_Symbol$toStringTag,get:function(){return"Map"}}]),e}(),isObservableMap=createInstanceofPredicate("ObservableMap",ObservableMap);function convertToMap(e){if(isES6Map(e)||isObservableMap(e))return e;if(Array.isArray(e))return new Map(e);if(isPlainObject(e)){var t=new Map;for(var n in e)t.set(n,e[n]);return t}return die(21,e)}var ObservableSetMarker={};_Symbol$iterator$1=Symbol.iterator,_Symbol$toStringTag$1=Symbol.toStringTag;var ObservableSet=function(){function e(e,t,n){void 0===t&&(t=deepEnhancer),void 0===n&&(n="ObservableSet@"+getNextId()),this.name_=void 0,this[$mobx]=ObservableSetMarker,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,isFunction(Set)||die(22),this.atom_=createAtom(this.name_),this.enhancer_=function(e,r){return t(e,r,n)},e&&this.replace(e)}var t=e.prototype;return t.dehanceValue_=function(e){return void 0!==this.dehancer?this.dehancer(e):e},t.clear=function(){var e=this;transaction(function(){untracked(function(){for(var t,n=_createForOfIteratorHelperLoose(e.data_.values());!(t=n()).done;){var r=t.value;e.delete(r)}})})},t.forEach=function(e,t){for(var n,r=_createForOfIteratorHelperLoose(this);!(n=r()).done;){var a=n.value;e.call(t,a,a,this)}},t.add=function(e){var t=this;if((checkIfStateModificationsAreAllowed(this.atom_),hasInterceptors(this))&&!interceptChange(this,{type:ADD,object:this,newValue:e}))return this;if(!this.has(e)){transaction(function(){t.data_.add(t.enhancer_(e,void 0)),t.atom_.reportChanged()});var n=isSpyEnabled(),r=hasListeners(this),a=r||n?{observableKind:"set",debugObjectName:this.name_,type:ADD,object:this,newValue:e}:null;n&&spyReportStart(a),r&¬ifyListeners(this,a),n&&spyReportEnd()}return this},t.delete=function(e){var t=this;if(hasInterceptors(this)&&!interceptChange(this,{type:DELETE,object:this,oldValue:e}))return!1;if(this.has(e)){var n=isSpyEnabled(),r=hasListeners(this),a=r||n?{observableKind:"set",debugObjectName:this.name_,type:DELETE,object:this,oldValue:e}:null;return n&&spyReportStart(a),transaction(function(){t.atom_.reportChanged(),t.data_.delete(e)}),r&¬ifyListeners(this,a),n&&spyReportEnd(),!0}return!1},t.has=function(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))},t.entries=function(){var e=0,t=Array.from(this.keys()),n=Array.from(this.values());return makeIterable({next:function(){var r=e;return e+=1,r<n.length?{value:[t[r],n[r]],done:!1}:{done:!0}}})},t.keys=function(){return this.values()},t.values=function(){this.atom_.reportObserved();var e=this,t=0,n=Array.from(this.data_.values());return makeIterable({next:function(){return t<n.length?{value:e.dehanceValue_(n[t++]),done:!1}:{done:!0}}})},t.replace=function(e){var t=this;return isObservableSet(e)&&(e=new Set(e)),transaction(function(){Array.isArray(e)?(t.clear(),e.forEach(function(e){return t.add(e)})):isES6Set(e)?(t.clear(),e.forEach(function(e){return t.add(e)})):null!=e&&die("Cannot initialize set from "+e)}),this},t.observe_=function(e,t){return!0===t&&die("`observe` doesn't support fireImmediately=true in combination with sets."),registerListener(this,e)},t.intercept_=function(e){return registerInterceptor(this,e)},t.toJSON=function(){return Array.from(this)},t.toString=function(){return"[object ObservableSet]"},t[_Symbol$iterator$1]=function(){return this.values()},_createClass(e,[{key:"size",get:function(){return this.atom_.reportObserved(),this.data_.size}},{key:_Symbol$toStringTag$1,get:function(){return"Set"}}]),e}(),isObservableSet=createInstanceofPredicate("ObservableSet",ObservableSet),inferredAnnotationsSymbol=Symbol("mobx-inferred-annotations"),descriptorCache=Object.create(null),REMOVE="remove",ObservableObjectAdministration=function(){function e(e,t,n,r,a){void 0===t&&(t=new Map),void 0===r&&(r=observable),void 0===a&&(a=!1),this.target_=void 0,this.values_=void 0,this.name_=void 0,this.defaultAnnotation_=void 0,this.autoBind_=void 0,this.keysAtom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.proxy_=void 0,this.isPlainObject_=void 0,this.appliedAnnotations_=void 0,this.pendingKeys_=void 0,this.target_=e,this.values_=t,this.name_=n,this.defaultAnnotation_=r,this.autoBind_=a,this.keysAtom_=new Atom(n+".keys"),this.isPlainObject_=isPlainObject(this.target_),isAnnotation(this.defaultAnnotation_)||die("defaultAnnotation must be valid annotation"),"boolean"!=typeof this.autoBind_&&die("autoBind must be boolean"),this.appliedAnnotations_={}}var t=e.prototype;return t.getObservablePropValue_=function(e){return this.values_.get(e).get()},t.setObservablePropValue_=function(e,t){var n=this.values_.get(e);if(n instanceof ComputedValue)return n.set(t),!0;if(hasInterceptors(this)){var r=interceptChange(this,{type:UPDATE,object:this.proxy_||this.target_,name:e,newValue:t});if(!r)return null;t=r.newValue}if((t=n.prepareNewValue_(t))!==globalState.UNCHANGED){var a=hasListeners(this),o=isSpyEnabled(),i=a||o?{type:UPDATE,observableKind:"object",debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;o&&spyReportStart(i),n.setNewValue_(t),a&¬ifyListeners(this,i),o&&spyReportEnd()}return!0},t.get_=function(e){return globalState.trackingDerivation&&!hasProp(this.target_,e)&&this.has_(e),this.target_[e]},t.set_=function(e,t,n){return void 0===n&&(n=!1),hasProp(this.target_,e)?this.values_.has(e)?this.setObservablePropValue_(e,t):n?Reflect.set(this.target_,e,t):(this.target_[e]=t,!0):this.extend_(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.defaultAnnotation_,n)},t.has_=function(e){if(!globalState.trackingDerivation)return e in this.target_;this.pendingKeys_||(this.pendingKeys_=new Map);var t=this.pendingKeys_.get(e);return t||(t=new ObservableValue(e in this.target_,referenceEnhancer,this.name_+"."+stringifyKey(e)+"?",!1),this.pendingKeys_.set(e,t)),t.get()},t.make_=function(e,t){!0===t&&(t=this.inferAnnotation_(e)),!1!==t&&(assertAnnotable(this,t,e),t.make_(this,e))},t.extend_=function(e,t,n,r){if(void 0===r&&(r=!1),!0===n&&(n=inferAnnotationFromDescriptor(t,this.defaultAnnotation_,this.autoBind_)),!1===n)return this.defineProperty_(e,t,r);assertAnnotable(this,n,e);var a=n.extend_(this,e,t,r);return a&&recordAnnotationApplied(this,n,e),a},t.inferAnnotation_=function(e){var t,n=null==(t=this.target_[inferredAnnotationsSymbol])?void 0:t[e];if(n)return n;for(var r=this.target_;r&&r!==objectPrototype;){var a=getDescriptor(r,e);if(a){n=inferAnnotationFromDescriptor(a,this.defaultAnnotation_,this.autoBind_);break}r=Object.getPrototypeOf(r)}if(void 0===n&&die(1,"true",e),!this.isPlainObject_){var o=Object.getPrototypeOf(this.target_);hasProp(o,inferredAnnotationsSymbol)||addHiddenProp(o,inferredAnnotationsSymbol,{}),o[inferredAnnotationsSymbol][e]=n}return n},t.defineProperty_=function(e,t,n){void 0===n&&(n=!1);try{startBatch();var r=this.delete_(e);if(!r)return r;if(hasInterceptors(this)){var a=interceptChange(this,{object:this.proxy_||this.target_,name:e,type:ADD,newValue:t.value});if(!a)return null;var o=a.newValue;t.value!==o&&(t=_extends({},t,{value:o}))}if(n){if(!Reflect.defineProperty(this.target_,e,t))return!1}else defineProperty(this.target_,e,t);this.notifyPropertyAddition_(e,t.value)}finally{endBatch()}return!0},t.defineObservableProperty_=function(e,t,n,r){void 0===r&&(r=!1);try{startBatch();var a=this.delete_(e);if(!a)return a;if(hasInterceptors(this)){var o=interceptChange(this,{object:this.proxy_||this.target_,name:e,type:ADD,newValue:t});if(!o)return null;t=o.newValue}var i=getCachedObservablePropDescriptor(e),s={configurable:!globalState.safeDescriptors||this.isPlainObject_,enumerable:!0,get:i.get,set:i.set};if(r){if(!Reflect.defineProperty(this.target_,e,s))return!1}else defineProperty(this.target_,e,s);var c=new ObservableValue(t,n,this.name_+"."+stringifyKey(e),!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{endBatch()}return!0},t.defineComputedProperty_=function(e,t,n){void 0===n&&(n=!1);try{startBatch();var r=this.delete_(e);if(!r)return r;if(hasInterceptors(this))if(!interceptChange(this,{object:this.proxy_||this.target_,name:e,type:ADD,newValue:void 0}))return null;t.name||(t.name=this.name_+"."+stringifyKey(e)),t.context=this.proxy_||this.target_;var a=getCachedObservablePropDescriptor(e),o={configurable:!globalState.safeDescriptors||this.isPlainObject_,enumerable:!1,get:a.get,set:a.set};if(n){if(!Reflect.defineProperty(this.target_,e,o))return!1}else defineProperty(this.target_,e,o);this.values_.set(e,new ComputedValue(t)),this.notifyPropertyAddition_(e,void 0)}finally{endBatch()}return!0},t.delete_=function(e,t){if(void 0===t&&(t=!1),!hasProp(this.target_,e))return!0;if(hasInterceptors(this)&&!interceptChange(this,{object:this.proxy_||this.target_,name:e,type:REMOVE}))return null;try{var n,r;startBatch();var a,o=hasListeners(this),i=isSpyEnabled(),s=this.values_.get(e),c=void 0;if(!s&&(o||i))c=null==(a=getDescriptor(this.target_,e))?void 0:a.value;if(t){if(!Reflect.deleteProperty(this.target_,e))return!1}else delete this.target_[e];if(delete this.appliedAnnotations_[e],s&&(this.values_.delete(e),s instanceof ObservableValue&&(c=s.value_),propagateChanged(s)),this.keysAtom_.reportChanged(),null==(n=this.pendingKeys_)||null==(r=n.get(e))||r.set(e in this.target_),o||i){var l={type:REMOVE,observableKind:"object",object:this.proxy_||this.target_,debugObjectName:this.name_,oldValue:c,name:e};i&&spyReportStart(l),o&¬ifyListeners(this,l),i&&spyReportEnd()}}finally{endBatch()}return!0},t.observe_=function(e,t){return!0===t&&die("`observe` doesn't support the fire immediately property for observable objects."),registerListener(this,e)},t.intercept_=function(e){return registerInterceptor(this,e)},t.notifyPropertyAddition_=function(e,t){var n,r,a=hasListeners(this),o=isSpyEnabled();if(a||o){var i=a||o?{type:ADD,observableKind:"object",debugObjectName:this.name_,object:this.proxy_||this.target_,name:e,newValue:t}:null;o&&spyReportStart(i),a&¬ifyListeners(this,i),o&&spyReportEnd()}null==(n=this.pendingKeys_)||null==(r=n.get(e))||r.set(!0),this.keysAtom_.reportChanged()},t.ownKeys_=function(){return this.keysAtom_.reportObserved(),ownKeys(this.target_)},t.keys_=function(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)},e}();function asObservableObject(e,t){var n;if(t&&isObservableObject(e)&&die("Options can't be provided for already observable objects."),hasProp(e,$mobx))return e;Object.isExtensible(e)||die("Cannot make the designated object observable; it is not extensible");var r=null!=(n=null==t?void 0:t.name)?n:(isPlainObject(e)?"ObservableObject":e.constructor.name)+"@"+getNextId(),a=new ObservableObjectAdministration(e,new Map,stringifyKey(r),getAnnotationFromOptions(t),null==t?void 0:t.autoBind);return addHiddenProp(e,$mobx,a),e}var isObservableObjectAdministration=createInstanceofPredicate("ObservableObjectAdministration",ObservableObjectAdministration);function getCachedObservablePropDescriptor(e){return descriptorCache[e]||(descriptorCache[e]={get:function(){return this[$mobx].getObservablePropValue_(e)},set:function(t){return this[$mobx].setObservablePropValue_(e,t)}})}function isObservableObject(e){return!!isObject(e)&&isObservableObjectAdministration(e[$mobx])}function recordAnnotationApplied(e,t,n){e.appliedAnnotations_[n]=t,t.isDecorator_&&delete e.target_[storedAnnotationsSymbol][n]}function assertAnnotable(e,t,n){if(isAnnotation(t)||die("Cannot annotate '"+e.name_+"."+n.toString()+"': Invalid annotation."),!isOverride(t)&&hasProp(e.appliedAnnotations_,n)){var r=e.name_+"."+n.toString(),a=e.appliedAnnotations_[n].annotationType_;die("Cannot apply '"+t.annotationType_+"' to '"+r+"':\nThe field is already annotated with '"+a+"'.\nRe-annotating fields is not allowed.\nUse 'override' annotation for methods overriden by subclass.")}}var OBSERVABLE_ARRAY_BUFFER_SIZE=0,StubArray=function(){};function inherit(e,t){Object.setPrototypeOf?Object.setPrototypeOf(e.prototype,t):void 0!==e.prototype.__proto__?e.prototype.__proto__=t:e.prototype=t}inherit(StubArray,Array.prototype);var LegacyObservableArray=function(e){function t(t,n,r,a){var o;void 0===r&&(r="ObservableArray@"+getNextId()),void 0===a&&(a=!1),o=e.call(this)||this;var i=new ObservableArrayAdministration(r,n,a,!0);if(i.proxy_=_assertThisInitialized(o),addHiddenFinalProp(_assertThisInitialized(o),$mobx,i),t&&t.length){var s=allowStateChangesStart(!0);o.spliceWithArray(0,0,t),allowStateChangesEnd(s)}return o}_inheritsLoose(t,e);var n=t.prototype;return n.concat=function(){this[$mobx].atom_.reportObserved();for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Array.prototype.concat.apply(this.slice(),t.map(function(e){return isObservableArray(e)?e.slice():e}))},n[Symbol.iterator]=function(){var e=this,t=0;return makeIterable({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})},_createClass(t,[{key:"length",get:function(){return this[$mobx].getArrayLength_()},set:function(e){this[$mobx].setArrayLength_(e)}},{key:Symbol.toStringTag,get:function(){return"Array"}}]),t}(StubArray);function createArrayEntryDescriptor(e){return{enumerable:!1,configurable:!0,get:function(){return this[$mobx].get_(e)},set:function(t){this[$mobx].set_(e,t)}}}function createArrayBufferItem(e){defineProperty(LegacyObservableArray.prototype,""+e,createArrayEntryDescriptor(e))}function reserveArrayBuffer(e){if(e>OBSERVABLE_ARRAY_BUFFER_SIZE){for(var t=OBSERVABLE_ARRAY_BUFFER_SIZE;t<e+100;t++)createArrayBufferItem(t);OBSERVABLE_ARRAY_BUFFER_SIZE=e}}function createLegacyArray(e,t,n){return new LegacyObservableArray(e,t,n)}function getAtom(e,t){if("object"==typeof e&&null!==e){if(isObservableArray(e))return void 0!==t&&die(23),e[$mobx].atom_;if(isObservableSet(e))return e[$mobx];if(isObservableMap(e)){if(void 0===t)return e.keysAtom_;var n=e.data_.get(t)||e.hasMap_.get(t);return n||die(25,t,getDebugName(e)),n}if(isObservableObject(e)){if(!t)return die(26);var r=e[$mobx].values_.get(t);return r||die(27,t,getDebugName(e)),r}if(isAtom(e)||isComputedValue(e)||isReaction(e))return e}else if(isFunction(e)&&isReaction(e[$mobx]))return e[$mobx];die(28)}function getAdministration(e,t){return e||die(29),void 0!==t?getAdministration(getAtom(e,t)):isAtom(e)||isComputedValue(e)||isReaction(e)?e:isObservableMap(e)||isObservableSet(e)?e:e[$mobx]?e[$mobx]:void die(24,e)}function getDebugName(e,t){return(void 0!==t?getAtom(e,t):isObservableObject(e)||isObservableMap(e)||isObservableSet(e)?getAdministration(e):getAtom(e)).name_}Object.entries(arrayExtensions).forEach(function(e){var t=e[0],n=e[1];"concat"!==t&&addHiddenProp(LegacyObservableArray.prototype,t,n)}),reserveArrayBuffer(1e3);var toString=objectPrototype.toString;function deepEqual(e,t,n){return void 0===n&&(n=-1),eq(e,t,n)}function eq(e,t,n,r,a){if(e===t)return 0!==e||1/e==1/t;if(null==e||null==t)return!1;if(e!=e)return t!=t;var o=typeof e;if(!isFunction(o)&&"object"!==o&&"object"!=typeof t)return!1;var i=toString.call(e);if(i!==toString.call(t))return!1;switch(i){case"[object RegExp]":case"[object String]":return""+e==""+t;case"[object Number]":return+e!=+e?+t!=+t:0==+e?1/+e==1/t:+e==+t;case"[object Date]":case"[object Boolean]":return+e==+t;case"[object Symbol]":return"undefined"!=typeof Symbol&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case"[object Map]":case"[object Set]":n>=0&&n++}e=unwrap(e),t=unwrap(t);var s="[object Array]"===i;if(!s){if("object"!=typeof e||"object"!=typeof t)return!1;var c=e.constructor,l=t.constructor;if(c!==l&&!(isFunction(c)&&c instanceof c&&isFunction(l)&&l instanceof l)&&"constructor"in e&&"constructor"in t)return!1}if(0===n)return!1;n<0&&(n=-1),a=a||[];for(var u=(r=r||[]).length;u--;)if(r[u]===e)return a[u]===t;if(r.push(e),a.push(t),s){if((u=e.length)!==t.length)return!1;for(;u--;)if(!eq(e[u],t[u],n-1,r,a))return!1}else{var d,b=Object.keys(e);if(u=b.length,Object.keys(t).length!==u)return!1;for(;u--;)if(!hasProp(t,d=b[u])||!eq(e[d],t[d],n-1,r,a))return!1}return r.pop(),a.pop(),!0}function unwrap(e){return isObservableArray(e)?e.slice():isES6Map(e)||isObservableMap(e)?Array.from(e.entries()):isES6Set(e)||isObservableSet(e)?Array.from(e.entries()):e}function makeIterable(e){return e[Symbol.iterator]=getSelf,e}function getSelf(){return this}function inferAnnotationFromDescriptor(e,t,n){return e.get?computed:!e.set&&(isFunction(e.value)?isGenerator(e.value)?!isFlow(e.value)&&flow:!isAction(e.value)&&(n?autoAction.bound:autoAction):t)}function isAnnotation(e){return e instanceof Object&&"string"==typeof e.annotationType_&&isFunction(e.make_)&&isFunction(e.extend_)}["Symbol","Map","Set","Symbol"].forEach(function(e){void 0===getGlobal()[e]&&die("MobX requires global '"+e+"' to be available or polyfilled")}),"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:spy,extras:{getDebugName:getDebugName},$mobx:$mobx});export{$mobx,FlowCancellationError,ObservableMap,ObservableSet,Reaction,allowStateChanges as _allowStateChanges,runInAction as _allowStateChangesInsideComputed,allowStateReadsEnd as _allowStateReadsEnd,allowStateReadsStart as _allowStateReadsStart,autoAction as _autoAction,_endAction,getAdministration as _getAdministration,getGlobalState as _getGlobalState,interceptReads as _interceptReads,isComputingDerivation as _isComputingDerivation,resetGlobalState as _resetGlobalState,_startAction,action,autorun,comparer,computed,configure,createAtom,entries,extendObservable,flow,flowResult,get,getAtom,getDebugName,getDependencyTree,getObserverTree,has,intercept,isAction,isObservableValue as isBoxedObservable,isComputed,isComputedProp,isFlowCancellationError,isObservable,isObservableArray,isObservableMap,isObservableObject,isObservableProp,isObservableSet,keys,makeAutoObservable,makeObservable,observable,observe,onBecomeObserved,onBecomeUnobserved,onReactionError,override,reaction,remove,runInAction,set,spy,toJS,trace,transaction,untracked,values,when}; |
files/backbonejs/1.0.0/backbone.js | gswalden/jsdelivr | // Backbone.js 1.0.0
// (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc.
// Backbone may be freely distributed under the MIT license.
// For all details and documentation:
// http://backbonejs.org
(function(){
// Initial Setup
// -------------
// Save a reference to the global object (`window` in the browser, `exports`
// on the server).
var root = this;
// Save the previous value of the `Backbone` variable, so that it can be
// restored later on, if `noConflict` is used.
var previousBackbone = root.Backbone;
// Create local references to array methods we'll want to use later.
var array = [];
var push = array.push;
var slice = array.slice;
var splice = array.splice;
// The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both the browser and the server.
var Backbone;
if (typeof exports !== 'undefined') {
Backbone = exports;
} else {
Backbone = root.Backbone = {};
}
// Current version of the library. Keep in sync with `package.json`.
Backbone.VERSION = '1.0.0';
// Require Underscore, if we're on the server, and it's not already present.
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
// For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
// the `$` variable.
Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$;
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
// to its previous owner. Returns a reference to this Backbone object.
Backbone.noConflict = function() {
root.Backbone = previousBackbone;
return this;
};
// Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
// will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
// set a `X-Http-Method-Override` header.
Backbone.emulateHTTP = false;
// Turn on `emulateJSON` to support legacy servers that can't deal with direct
// `application/json` requests ... will encode the body as
// `application/x-www-form-urlencoded` instead and will send the model in a
// form param named `model`.
Backbone.emulateJSON = false;
// Backbone.Events
// ---------------
// A module that can be mixed in to *any object* in order to provide it with
// custom events. You may bind with `on` or remove with `off` callback
// functions to an event; `trigger`-ing an event fires all callbacks in
// succession.
//
// var object = {};
// _.extend(object, Backbone.Events);
// object.on('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
var Events = Backbone.Events = {
// Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({callback: callback, context: context, ctx: context || this});
return this;
},
// Bind an event to only be triggered a single time. After the first time
// the callback is invoked, it will be removed.
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
// Remove one or many callbacks. If `context` is null, removes all
// callbacks with that function. If `callback` is null, removes all
// callbacks for the event. If `name` is null, removes all bound
// callbacks for all events.
off: function(name, callback, context) {
var retain, ev, events, names, i, l, j, k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
if (!name && !callback && !context) {
this._events = {};
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
if (events = this._events[name]) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
(context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length) delete this._events[name];
}
}
return this;
},
// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
},
// Tell this object to stop listening to either specific events ... or
// to every object it's currently listening to.
stopListening: function(obj, name, callback) {
var listeners = this._listeners;
if (!listeners) return this;
var deleteListener = !name && !callback;
if (typeof name === 'object') callback = this;
if (obj) (listeners = {})[obj._listenerId] = obj;
for (var id in listeners) {
listeners[id].off(name, callback, this);
if (deleteListener) delete this._listeners[id];
}
return this;
}
};
// Regular expression used to split event strings.
var eventSplitter = /\s+/;
// Implement fancy features of the Events API such as multiple event
// names `"change blur"` and jQuery-style event maps `{change: action}`
// in terms of the existing API.
var eventsApi = function(obj, action, name, rest) {
if (!name) return true;
// Handle event maps.
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
// Handle space separated event names.
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0, l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
// A difficult-to-believe, but optimized internal dispatch function for
// triggering events. Tries to keep the usual cases speedy (most internal
// Backbone events have 3 arguments).
var triggerEvents = function(events, args) {
var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
switch (args.length) {
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
}
};
var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
// Inversion-of-control versions of `on` and `once`. Tell *this* object to
// listen to an event in another object ... keeping track of what it's
// listening to.
_.each(listenMethods, function(implementation, method) {
Events[method] = function(obj, name, callback) {
var listeners = this._listeners || (this._listeners = {});
var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
listeners[id] = obj;
if (typeof name === 'object') callback = this;
obj[implementation](name, callback, this);
return this;
};
});
// Aliases for backwards compatibility.
Events.bind = Events.on;
Events.unbind = Events.off;
// Allow the `Backbone` object to serve as a global event bus, for folks who
// want global "pubsub" in a convenient place.
_.extend(Backbone, Events);
// Backbone.Model
// --------------
// Backbone **Models** are the basic data object in the framework --
// frequently representing a row in a table in a database on your server.
// A discrete chunk of data and a bunch of useful, related methods for
// performing computations and transformations on that data.
// Create a new model with the specified attributes. A client id (`cid`)
// is automatically generated and assigned for you.
var Model = Backbone.Model = function(attributes, options) {
var defaults;
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = {};
_.extend(this, _.pick(options, modelOptions));
if (options.parse) attrs = this.parse(attrs, options) || {};
if (defaults = _.result(this, 'defaults')) {
attrs = _.defaults({}, attrs, defaults);
}
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};
// A list of options to be attached directly to the model, if provided.
var modelOptions = ['url', 'urlRoot', 'collection'];
// Attach all inheritable methods to the Model prototype.
_.extend(Model.prototype, Events, {
// A hash of attributes whose current and previous value differ.
changed: null,
// The value returned during the last failed validation.
validationError: null,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute: 'id',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Return a copy of the model's `attributes` object.
toJSON: function(options) {
return _.clone(this.attributes);
},
// Proxy `Backbone.sync` by default -- but override this if you need
// custom syncing semantics for *this* particular model.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Get the value of an attribute.
get: function(attr) {
return this.attributes[attr];
},
// Get the HTML-escaped value of an attribute.
escape: function(attr) {
return _.escape(this.get(attr));
},
// Returns `true` if the attribute contains a value that is not null
// or undefined.
has: function(attr) {
return this.get(attr) != null;
},
// Set a hash of model attributes on the object, firing `"change"`. This is
// the core primitive operation of a model, updating the data and notifying
// anyone who needs to know about the change in state. The heart of the beast.
set: function(key, val, options) {
var attr, attrs, unset, changes, silent, changing, prev, current;
if (key == null) return this;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options || (options = {});
// Run validation.
if (!this._validate(attrs, options)) return false;
// Extract attributes and options.
unset = options.unset;
silent = options.silent;
changes = [];
changing = this._changing;
this._changing = true;
if (!changing) {
this._previousAttributes = _.clone(this.attributes);
this.changed = {};
}
current = this.attributes, prev = this._previousAttributes;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
// For each `set` attribute, update or delete the current value.
for (attr in attrs) {
val = attrs[attr];
if (!_.isEqual(current[attr], val)) changes.push(attr);
if (!_.isEqual(prev[attr], val)) {
this.changed[attr] = val;
} else {
delete this.changed[attr];
}
unset ? delete current[attr] : current[attr] = val;
}
// Trigger all relevant attribute changes.
if (!silent) {
if (changes.length) this._pending = true;
for (var i = 0, l = changes.length; i < l; i++) {
this.trigger('change:' + changes[i], this, current[changes[i]], options);
}
}
// You might be wondering why there's a `while` loop here. Changes can
// be recursively nested within `"change"` events.
if (changing) return this;
if (!silent) {
while (this._pending) {
this._pending = false;
this.trigger('change', this, options);
}
}
this._pending = false;
this._changing = false;
return this;
},
// Remove an attribute from the model, firing `"change"`. `unset` is a noop
// if the attribute doesn't exist.
unset: function(attr, options) {
return this.set(attr, void 0, _.extend({}, options, {unset: true}));
},
// Clear all attributes on the model, firing `"change"`.
clear: function(options) {
var attrs = {};
for (var key in this.attributes) attrs[key] = void 0;
return this.set(attrs, _.extend({}, options, {unset: true}));
},
// Determine if the model has changed since the last `"change"` event.
// If you specify an attribute name, determine if that attribute has changed.
hasChanged: function(attr) {
if (attr == null) return !_.isEmpty(this.changed);
return _.has(this.changed, attr);
},
// Return an object containing all the attributes that have changed, or
// false if there are no changed attributes. Useful for determining what
// parts of a view need to be updated and/or what attributes need to be
// persisted to the server. Unset attributes will be set to undefined.
// You can also pass an attributes object to diff against the model,
// determining if there *would be* a change.
changedAttributes: function(diff) {
if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
var val, changed = false;
var old = this._changing ? this._previousAttributes : this.attributes;
for (var attr in diff) {
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
(changed || (changed = {}))[attr] = val;
}
return changed;
},
// Get the previous value of an attribute, recorded at the time the last
// `"change"` event was fired.
previous: function(attr) {
if (attr == null || !this._previousAttributes) return null;
return this._previousAttributes[attr];
},
// Get all of the attributes of the model at the time of the previous
// `"change"` event.
previousAttributes: function() {
return _.clone(this._previousAttributes);
},
// Fetch the model from the server. If the server's representation of the
// model differs from its current attributes, they will be overridden,
// triggering a `"change"` event.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
if (!model.set(model.parse(resp, options), options)) return false;
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save: function(key, val, options) {
var attrs, method, xhr, attributes = this.attributes;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (key == null || typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
// If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
options = _.extend({validate: true}, options);
// Do not persist invalid models.
if (!this._validate(attrs, options)) return false;
// Set temporary attributes if `{wait: true}`.
if (attrs && options.wait) {
this.attributes = _.extend({}, attributes, attrs);
}
// After a successful server-side save, the client is (optionally)
// updated with the server-side state.
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
// Ensure attributes are restored during synchronous saves.
model.attributes = attributes;
var serverAttrs = model.parse(resp, options);
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
return false;
}
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
if (method === 'patch') options.attrs = attrs;
xhr = this.sync(method, this, options);
// Restore attributes.
if (attrs && options.wait) this.attributes = attributes;
return xhr;
},
// Destroy this model on the server if it was already persisted.
// Optimistically removes the model from its collection, if it has one.
// If `wait: true` is passed, waits for the server to respond before removal.
destroy: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
var destroy = function() {
model.trigger('destroy', model, model.collection, options);
};
options.success = function(resp) {
if (options.wait || model.isNew()) destroy();
if (success) success(model, resp, options);
if (!model.isNew()) model.trigger('sync', model, resp, options);
};
if (this.isNew()) {
options.success();
return false;
}
wrapError(this, options);
var xhr = this.sync('delete', this, options);
if (!options.wait) destroy();
return xhr;
},
// Default URL for the model's representation on the server -- if you're
// using Backbone's restful methods, override this to change the endpoint
// that will be called.
url: function() {
var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
},
// **parse** converts a response into the hash of attributes to be `set` on
// the model. The default implementation is just to pass the response along.
parse: function(resp, options) {
return resp;
},
// Create a new model with identical attributes to this one.
clone: function() {
return new this.constructor(this.attributes);
},
// A model is new if it has never been saved to the server, and lacks an id.
isNew: function() {
return this.id == null;
},
// Check if the model is currently in a valid state.
isValid: function(options) {
return this._validate({}, _.extend(options || {}, { validate: true }));
},
// Run validation against the next complete set of model attributes,
// returning `true` if all is well. Otherwise, fire an `"invalid"` event.
_validate: function(attrs, options) {
if (!options.validate || !this.validate) return true;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validationError = this.validate(attrs, options) || null;
if (!error) return true;
this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error}));
return false;
}
});
// Underscore methods that we want to implement on the Model.
var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
// Mix in each Underscore method as a proxy to `Model#attributes`.
_.each(modelMethods, function(method) {
Model.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.attributes);
return _[method].apply(_, args);
};
});
// Backbone.Collection
// -------------------
// If models tend to represent a single row of data, a Backbone Collection is
// more analagous to a table full of data ... or a small slice or page of that
// table, or a collection of rows that belong together for a particular reason
// -- all of the messages in this particular folder, all of the documents
// belonging to this particular author, and so on. Collections maintain
// indexes of their models, both in order, and for lookup by `id`.
// Create a new **Collection**, perhaps to contain a specific type of `model`.
// If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.
var Collection = Backbone.Collection = function(models, options) {
options || (options = {});
if (options.url) this.url = options.url;
if (options.model) this.model = options.model;
if (options.comparator !== void 0) this.comparator = options.comparator;
this._reset();
this.initialize.apply(this, arguments);
if (models) this.reset(models, _.extend({silent: true}, options));
};
// Default options for `Collection#set`.
var setOptions = {add: true, remove: true, merge: true};
var addOptions = {add: true, merge: false, remove: false};
// Define the Collection's inheritable methods.
_.extend(Collection.prototype, Events, {
// The default model for a collection is just a **Backbone.Model**.
// This should be overridden in most cases.
model: Model,
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// The JSON representation of a Collection is an array of the
// models' attributes.
toJSON: function(options) {
return this.map(function(model){ return model.toJSON(options); });
},
// Proxy `Backbone.sync` by default.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Add a model, or list of models to the set.
add: function(models, options) {
return this.set(models, _.defaults(options || {}, addOptions));
},
// Remove a model, or a list of models from the set.
remove: function(models, options) {
models = _.isArray(models) ? models.slice() : [models];
options || (options = {});
var i, l, index, model;
for (i = 0, l = models.length; i < l; i++) {
model = this.get(models[i]);
if (!model) continue;
delete this._byId[model.id];
delete this._byId[model.cid];
index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
this._removeReference(model);
}
return this;
},
// Update a collection by `set`-ing a new list of models, adding new ones,
// removing models that are no longer present, and merging models that
// already exist in the collection, as necessary. Similar to **Model#set**,
// the core operation for updating the data contained by the collection.
set: function(models, options) {
options = _.defaults(options || {}, setOptions);
if (options.parse) models = this.parse(models, options);
if (!_.isArray(models)) models = models ? [models] : [];
var i, l, model, attrs, existing, sort;
var at = options.at;
var sortable = this.comparator && (at == null) && options.sort !== false;
var sortAttr = _.isString(this.comparator) ? this.comparator : null;
var toAdd = [], toRemove = [], modelMap = {};
// Turn bare objects into model references, and prevent invalid models
// from being added.
for (i = 0, l = models.length; i < l; i++) {
if (!(model = this._prepareModel(models[i], options))) continue;
// If a duplicate is found, prevent it from being added and
// optionally merge it into the existing model.
if (existing = this.get(model)) {
if (options.remove) modelMap[existing.cid] = true;
if (options.merge) {
existing.set(model.attributes, options);
if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
}
// This is a new model, push it to the `toAdd` list.
} else if (options.add) {
toAdd.push(model);
// Listen to added models' events, and index models for lookup by
// `id` and by `cid`.
model.on('all', this._onModelEvent, this);
this._byId[model.cid] = model;
if (model.id != null) this._byId[model.id] = model;
}
}
// Remove nonexistent models if appropriate.
if (options.remove) {
for (i = 0, l = this.length; i < l; ++i) {
if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
}
if (toRemove.length) this.remove(toRemove, options);
}
// See if sorting is needed, update `length` and splice in new models.
if (toAdd.length) {
if (sortable) sort = true;
this.length += toAdd.length;
if (at != null) {
splice.apply(this.models, [at, 0].concat(toAdd));
} else {
push.apply(this.models, toAdd);
}
}
// Silently sort the collection if appropriate.
if (sort) this.sort({silent: true});
if (options.silent) return this;
// Trigger `add` events.
for (i = 0, l = toAdd.length; i < l; i++) {
(model = toAdd[i]).trigger('add', model, this, options);
}
// Trigger `sort` if the collection was sorted.
if (sort) this.trigger('sort', this, options);
return this;
},
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any granular `add` or `remove` events. Fires `reset` when finished.
// Useful for bulk operations and optimizations.
reset: function(models, options) {
options || (options = {});
for (var i = 0, l = this.models.length; i < l; i++) {
this._removeReference(this.models[i]);
}
options.previousModels = this.models;
this._reset();
this.add(models, _.extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return this;
},
// Add a model to the end of the collection.
push: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, _.extend({at: this.length}, options));
return model;
},
// Remove a model from the end of the collection.
pop: function(options) {
var model = this.at(this.length - 1);
this.remove(model, options);
return model;
},
// Add a model to the beginning of the collection.
unshift: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, _.extend({at: 0}, options));
return model;
},
// Remove a model from the beginning of the collection.
shift: function(options) {
var model = this.at(0);
this.remove(model, options);
return model;
},
// Slice out a sub-array of models from the collection.
slice: function(begin, end) {
return this.models.slice(begin, end);
},
// Get a model from the set by id.
get: function(obj) {
if (obj == null) return void 0;
return this._byId[obj.id != null ? obj.id : obj.cid || obj];
},
// Get the model at the given index.
at: function(index) {
return this.models[index];
},
// Return models with matching attributes. Useful for simple cases of
// `filter`.
where: function(attrs, first) {
if (_.isEmpty(attrs)) return first ? void 0 : [];
return this[first ? 'find' : 'filter'](function(model) {
for (var key in attrs) {
if (attrs[key] !== model.get(key)) return false;
}
return true;
});
},
// Return the first model with matching attributes. Useful for simple cases
// of `find`.
findWhere: function(attrs) {
return this.where(attrs, true);
},
// Force the collection to re-sort itself. You don't need to call this under
// normal circumstances, as the set will maintain sort order as each item
// is added.
sort: function(options) {
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
options || (options = {});
// Run sort based on type of `comparator`.
if (_.isString(this.comparator) || this.comparator.length === 1) {
this.models = this.sortBy(this.comparator, this);
} else {
this.models.sort(_.bind(this.comparator, this));
}
if (!options.silent) this.trigger('sort', this, options);
return this;
},
// Figure out the smallest index at which a model should be inserted so as
// to maintain order.
sortedIndex: function(model, value, context) {
value || (value = this.comparator);
var iterator = _.isFunction(value) ? value : function(model) {
return model.get(value);
};
return _.sortedIndex(this.models, model, iterator, context);
},
// Pluck an attribute from each model in the collection.
pluck: function(attr) {
return _.invoke(this.models, 'get', attr);
},
// Fetch the default set of models for this collection, resetting the
// collection when they arrive. If `reset: true` is passed, the response
// data will be passed through the `reset` method instead of `set`.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var success = options.success;
var collection = this;
options.success = function(resp) {
var method = options.reset ? 'reset' : 'set';
collection[method](resp, options);
if (success) success(collection, resp, options);
collection.trigger('sync', collection, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Create a new instance of a model in this collection. Add the model to the
// collection immediately, unless `wait: true` is passed, in which case we
// wait for the server to agree.
create: function(model, options) {
options = options ? _.clone(options) : {};
if (!(model = this._prepareModel(model, options))) return false;
if (!options.wait) this.add(model, options);
var collection = this;
var success = options.success;
options.success = function(resp) {
if (options.wait) collection.add(model, options);
if (success) success(model, resp, options);
};
model.save(null, options);
return model;
},
// **parse** converts a response into a list of models to be added to the
// collection. The default implementation is just to pass it through.
parse: function(resp, options) {
return resp;
},
// Create a new collection with an identical list of models as this one.
clone: function() {
return new this.constructor(this.models);
},
// Private method to reset all internal state. Called when the collection
// is first initialized or reset.
_reset: function() {
this.length = 0;
this.models = [];
this._byId = {};
},
// Prepare a hash of attributes (or other model) to be added to this
// collection.
_prepareModel: function(attrs, options) {
if (attrs instanceof Model) {
if (!attrs.collection) attrs.collection = this;
return attrs;
}
options || (options = {});
options.collection = this;
var model = new this.model(attrs, options);
if (!model._validate(attrs, options)) {
this.trigger('invalid', this, attrs, options);
return false;
}
return model;
},
// Internal method to sever a model's ties to a collection.
_removeReference: function(model) {
if (this === model.collection) delete model.collection;
model.off('all', this._onModelEvent, this);
},
// Internal method called every time a model in the set fires an event.
// Sets need to update their indexes when models change ids. All other
// events simply proxy through. "add" and "remove" events that originate
// in other collections are ignored.
_onModelEvent: function(event, model, collection, options) {
if ((event === 'add' || event === 'remove') && collection !== this) return;
if (event === 'destroy') this.remove(model, options);
if (model && event === 'change:' + model.idAttribute) {
delete this._byId[model.previous(model.idAttribute)];
if (model.id != null) this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
});
// Underscore methods that we want to implement on the Collection.
// 90% of the core usefulness of Backbone Collections is actually implemented
// right here:
var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
'isEmpty', 'chain'];
// Mix in each Underscore method as a proxy to `Collection#models`.
_.each(methods, function(method) {
Collection.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.models);
return _[method].apply(_, args);
};
});
// Underscore methods that take a property name as an argument.
var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
// Use attributes instead of properties.
_.each(attributeMethods, function(method) {
Collection.prototype[method] = function(value, context) {
var iterator = _.isFunction(value) ? value : function(model) {
return model.get(value);
};
return _[method](this.models, iterator, context);
};
});
// Backbone.View
// -------------
// Backbone Views are almost more convention than they are actual code. A View
// is simply a JavaScript object that represents a logical chunk of UI in the
// DOM. This might be a single item, an entire list, a sidebar or panel, or
// even the surrounding frame which wraps your whole app. Defining a chunk of
// UI as a **View** allows you to define your DOM events declaratively, without
// having to worry about render order ... and makes it easy for the view to
// react to specific changes in the state of your models.
// Creating a Backbone.View creates its initial element outside of the DOM,
// if an existing element is not provided...
var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
this._configure(options || {});
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
// Set up all inheritable **Backbone.View** properties and methods.
_.extend(View.prototype, Events, {
// The default `tagName` of a View's element is `"div"`.
tagName: 'div',
// jQuery delegate for element lookup, scoped to DOM elements within the
// current view. This should be prefered to global lookups where possible.
$: function(selector) {
return this.$el.find(selector);
},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// **render** is the core function that your view should override, in order
// to populate its element (`this.el`), with the appropriate HTML. The
// convention is for **render** to always return `this`.
render: function() {
return this;
},
// Remove this view by taking the element out of the DOM, and removing any
// applicable Backbone.Events listeners.
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
// Change the view's element (`this.el` property), including event
// re-delegation.
setElement: function(element, delegate) {
if (this.$el) this.undelegateEvents();
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
this.el = this.$el[0];
if (delegate !== false) this.delegateEvents();
return this;
},
// Set callbacks, where `this.events` is a hash of
//
// *{"event selector": "callback"}*
//
// {
// 'mousedown .title': 'edit',
// 'click .button': 'save'
// 'click .open': function(e) { ... }
// }
//
// pairs. Callbacks will be bound to the view, with `this` set properly.
// Uses event delegation for efficiency.
// Omitting the selector binds the event to `this.el`.
// This only works for delegate-able events: not `focus`, `blur`, and
// not `change`, `submit`, and `reset` in Internet Explorer.
delegateEvents: function(events) {
if (!(events || (events = _.result(this, 'events')))) return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
// Clears all callbacks previously bound to the view with `delegateEvents`.
// You usually don't need to use this, but may wish to if you have multiple
// Backbone views attached to the same DOM element.
undelegateEvents: function() {
this.$el.off('.delegateEvents' + this.cid);
return this;
},
// Performs the initial configuration of a View with a set of options.
// Keys with special meaning *(e.g. model, collection, id, className)* are
// attached directly to the view. See `viewOptions` for an exhaustive
// list.
_configure: function(options) {
if (this.options) options = _.extend({}, _.result(this, 'options'), options);
_.extend(this, _.pick(options, viewOptions));
this.options = options;
},
// Ensure that the View has a DOM element to render into.
// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
if (this.className) attrs['class'] = _.result(this, 'className');
var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
});
// Backbone.sync
// -------------
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
//
// Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
// as `POST`, with a `_method` parameter containing the true HTTP method,
// as well as all requests with the body as `application/x-www-form-urlencoded`
// instead of `application/json` with the model in a param named `model`.
// Useful when interfacing with server-side languages like **PHP** that make
// it difficult to read the body of `PUT` requests.
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default options, unless specified.
_.defaults(options || (options = {}), {
emulateHTTP: Backbone.emulateHTTP,
emulateJSON: Backbone.emulateJSON
});
// Default JSON-request options.
var params = {type: type, dataType: 'json'};
// Ensure that we have a URL.
if (!options.url) {
params.url = _.result(model, 'url') || urlError();
}
// Ensure that we have the appropriate request data.
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
params.contentType = 'application/json';
params.data = JSON.stringify(options.attrs || model.toJSON(options));
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (options.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? {model: params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
params.type = 'POST';
if (options.emulateJSON) params.data._method = type;
var beforeSend = options.beforeSend;
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
if (beforeSend) return beforeSend.apply(this, arguments);
};
}
// Don't process data on a non-GET request.
if (params.type !== 'GET' && !options.emulateJSON) {
params.processData = false;
}
// If we're sending a `PATCH` request, and we're in an old Internet Explorer
// that still has ActiveX enabled by default, override jQuery to use that
// for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
if (params.type === 'PATCH' && window.ActiveXObject &&
!(window.external && window.external.msActiveXFilteringEnabled)) {
params.xhr = function() {
return new ActiveXObject("Microsoft.XMLHTTP");
};
}
// Make the request, allowing the user to override any Ajax options.
var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
model.trigger('request', model, xhr, options);
return xhr;
};
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
var methodMap = {
'create': 'POST',
'update': 'PUT',
'patch': 'PATCH',
'delete': 'DELETE',
'read': 'GET'
};
// Set the default implementation of `Backbone.ajax` to proxy through to `$`.
// Override this if you'd like to use a different library.
Backbone.ajax = function() {
return Backbone.$.ajax.apply(Backbone.$, arguments);
};
// Backbone.Router
// ---------------
// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
var Router = Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var optionalParam = /\((.*?)\)/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
// Set up all inheritable **Backbone.Router** properties and methods.
_.extend(Router.prototype, Events, {
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Manually bind a single named route to a callback. For example:
//
// this.route('search/:query/p:num', 'search', function(query, num) {
// ...
// });
//
route: function(route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (_.isFunction(name)) {
callback = name;
name = '';
}
if (!callback) callback = this[name];
var router = this;
Backbone.history.route(route, function(fragment) {
var args = router._extractParameters(route, fragment);
callback && callback.apply(router, args);
router.trigger.apply(router, ['route:' + name].concat(args));
router.trigger('route', name, args);
Backbone.history.trigger('route', router, name, args);
});
return this;
},
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
return this;
},
// Bind all defined routes to `Backbone.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes: function() {
if (!this.routes) return;
this.routes = _.result(this, 'routes');
var route, routes = _.keys(this.routes);
while ((route = routes.pop()) != null) {
this.route(route, this.routes[route]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp: function(route) {
route = route.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function(match, optional){
return optional ? match : '([^\/]+)';
})
.replace(splatParam, '(.*?)');
return new RegExp('^' + route + '$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted decoded parameters. Empty or unmatched parameters will be
// treated as `null` to normalize cross-browser behavior.
_extractParameters: function(route, fragment) {
var params = route.exec(fragment).slice(1);
return _.map(params, function(param) {
return param ? decodeURIComponent(param) : null;
});
}
});
// Backbone.History
// ----------------
// Handles cross-browser history management, based on either
// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
// and URL fragments. If the browser supports neither (old IE, natch),
// falls back to polling.
var History = Backbone.History = function() {
this.handlers = [];
_.bindAll(this, 'checkUrl');
// Ensure that `History` can be used outside of the browser.
if (typeof window !== 'undefined') {
this.location = window.location;
this.history = window.history;
}
};
// Cached regex for stripping a leading hash/slash and trailing space.
var routeStripper = /^[#\/]|\s+$/g;
// Cached regex for stripping leading and trailing slashes.
var rootStripper = /^\/+|\/+$/g;
// Cached regex for detecting MSIE.
var isExplorer = /msie [\w.]+/;
// Cached regex for removing a trailing slash.
var trailingSlash = /\/$/;
// Has the history handling already been started?
History.started = false;
// Set up all inheritable **Backbone.History** properties and methods.
_.extend(History.prototype, Events, {
// The default interval to poll for hash changes, if necessary, is
// twenty times a second.
interval: 50,
// Gets the true hash value. Cannot use location.hash directly due to bug
// in Firefox where location.hash will always be decoded.
getHash: function(window) {
var match = (window || this).location.href.match(/#(.*)$/);
return match ? match[1] : '';
},
// Get the cross-browser normalized URL fragment, either from the URL,
// the hash, or the override.
getFragment: function(fragment, forcePushState) {
if (fragment == null) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = this.location.pathname;
var root = this.root.replace(trailingSlash, '');
if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
} else {
fragment = this.getHash();
}
}
return fragment.replace(routeStripper, '');
},
// Start the hash change handling, returning `true` if the current URL matches
// an existing route, and `false` otherwise.
start: function(options) {
if (History.started) throw new Error("Backbone.history has already been started");
History.started = true;
// Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
this.options = _.extend({}, {root: '/'}, this.options, options);
this.root = this.options.root;
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var fragment = this.getFragment();
var docMode = document.documentMode;
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
// Normalize root to always include a leading and trailing slash.
this.root = ('/' + this.root + '/').replace(rootStripper, '/');
if (oldIE && this._wantsHashChange) {
this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
this.navigate(fragment);
}
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
Backbone.$(window).on('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
Backbone.$(window).on('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
// Determine if we need to change the base url, for a pushState link
// opened by a non-pushState browser.
this.fragment = fragment;
var loc = this.location;
var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
// If we've started off with a route from a `pushState`-enabled browser,
// but we're currently in a browser that doesn't support it...
if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
this.fragment = this.getFragment(null, true);
this.location.replace(this.root + this.location.search + '#' + this.fragment);
// Return immediately as browser will do redirect to new url
return true;
// Or if we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
} else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
this.fragment = this.getHash().replace(routeStripper, '');
this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
}
if (!this.options.silent) return this.loadUrl();
},
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
stop: function() {
Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
clearInterval(this._checkUrlInterval);
History.started = false;
},
// Add a route to be tested when the fragment changes. Routes added later
// may override previous routes.
route: function(route, callback) {
this.handlers.unshift({route: route, callback: callback});
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`, normalizing across the hidden iframe.
checkUrl: function(e) {
var current = this.getFragment();
if (current === this.fragment && this.iframe) {
current = this.getFragment(this.getHash(this.iframe));
}
if (current === this.fragment) return false;
if (this.iframe) this.navigate(current);
this.loadUrl() || this.loadUrl(this.getHash());
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function(fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
var matched = _.any(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
return matched;
},
// Save a fragment into the hash history, or replace the URL state if the
// 'replace' option is passed. You are responsible for properly URL-encoding
// the fragment in advance.
//
// The options object can contain `trigger: true` if you wish to have the
// route callback be fired (not usually desirable), or `replace: true`, if
// you wish to modify the current URL without adding an entry to the history.
navigate: function(fragment, options) {
if (!History.started) return false;
if (!options || options === true) options = {trigger: options};
fragment = this.getFragment(fragment || '');
if (this.fragment === fragment) return;
this.fragment = fragment;
var url = this.root + fragment;
// If pushState is available, we use it to set the fragment as a real URL.
if (this._hasPushState) {
this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
// If hash changes haven't been explicitly disabled, update the hash
// fragment to store history.
} else if (this._wantsHashChange) {
this._updateHash(this.location, fragment, options.replace);
if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
// Opening and closing the iframe tricks IE7 and earlier to push a
// history entry on hash-tag change. When replace is true, we don't
// want this.
if(!options.replace) this.iframe.document.open().close();
this._updateHash(this.iframe.location, fragment, options.replace);
}
// If you've told us that you explicitly don't want fallback hashchange-
// based history, then `navigate` becomes a page refresh.
} else {
return this.location.assign(url);
}
if (options.trigger) this.loadUrl(fragment);
},
// Update the hash location, either replacing the current entry, or adding
// a new one to the browser history.
_updateHash: function(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
// Some browsers require that `hash` contains a leading #.
location.hash = '#' + fragment;
}
}
});
// Create the default Backbone.history.
Backbone.history = new History;
// Helpers
// -------
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
_.extend(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps);
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
};
// Set up inheritance for the model, collection, router, view and history.
Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
// Throw an error when a URL is needed, and none is supplied.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
// Wrap an optional error callback with a fallback error event.
var wrapError = function (model, options) {
var error = options.error;
options.error = function(resp) {
if (error) error(model, resp, options);
model.trigger('error', model, resp, options);
};
};
}).call(this);
|
react/Textarea/textAreaUtils.spec.js | seek-oss/seek-style-guide | /* eslint-disable react/jsx-key */
import React from 'react';
import { formatInvalidText } from './textAreaUtils.js';
import Highlight from '../Highlight/Highlight';
describe('contentEditableUtils', () => {
describe('formatInvalidText', () => {
const style = 'my-class-name';
describe('invalidText is a string', () => {
it('should do nothing if there is no invalid text', () => {
const value = 'my text';
const invalidText = '';
expect(formatInvalidText(value, invalidText, style)).toEqual([
'my text'
]);
});
it('should render text with no required formatting correctly', () => {
const value = 'text';
const invalidText = 'bad text';
expect(formatInvalidText(value, invalidText, style)).toEqual(['text']);
});
it('should render text with formatting correctly', () => {
const value = 'my bad text';
const invalidText = 'bad text';
expect(formatInvalidText(value, invalidText, style)).toEqual([
'my ',
<Highlight className="my-class-name" tone="critical" key="0">
bad text
</Highlight>
]);
});
it('should apply formatting to multiple instances of matched values', () => {
const value = 'very very very bad text';
const invalidText = 'very';
expect(formatInvalidText(value, invalidText, style)).toEqual([
<Highlight className="my-class-name" tone="critical" key="0">
very
</Highlight>,
' ',
<Highlight className="my-class-name" tone="critical" key="1">
very
</Highlight>,
' ',
<Highlight className="my-class-name" tone="critical" key="2">
very
</Highlight>,
' bad text'
]);
});
});
describe('invalidText is an object / range', () => {
it('should return the unformatted text if no highlighting is required', () => {
const value = 'aaaaaaaaa bbbbbbbbbb';
const invalidText = { start: 30 };
expect(formatInvalidText(value, invalidText, style)).toEqual([
'aaaaaaaaa bbbbbbbbbb'
]);
});
it('should highlight from a start point to the end of a string', () => {
const value = 'my string of text';
const invalidText = {
start: 6
};
expect(formatInvalidText(value, invalidText, style)).toEqual([
'my str',
<Highlight className="my-class-name" tone="critical" key="0">
ing of text
</Highlight>
]);
});
it('should highlight a range', () => {
const value = 'my longer text';
const invalidText = {
start: 3,
end: 9
};
expect(formatInvalidText(value, invalidText, style)).toEqual([
'my ',
<Highlight className="my-class-name" tone="critical" key="0">
longer
</Highlight>,
' text'
]);
});
describe('highlighting multiple ranges', () => {
it('can highlight three seperate ranges', () => {
const value = 'my longer text';
const invalidText = [
{
start: 3,
end: 6
},
{
start: 7,
end: 8
},
{
start: 12,
end: 13
}
];
expect(formatInvalidText(value, invalidText, style)).toEqual([
'my ',
<Highlight className="my-class-name" tone="critical" key="0">
lon
</Highlight>,
'g',
<Highlight className="my-class-name" tone="critical" key="1">
e
</Highlight>,
'r te',
<Highlight className="my-class-name" tone="critical" key="2">
x
</Highlight>,
't'
]);
});
it('highlights correctly when only the first range is present', () => {
const value = 'aaaaaaaaaabbb';
const invalidText = [
{
start: 10,
end: 20
},
{
start: 30,
end: 40
}
];
expect(formatInvalidText(value, invalidText, style)).toEqual([
'aaaaaaaaaa',
<Highlight className="my-class-name" tone="critical" key="0">
bbb
</Highlight>
]);
});
});
});
});
});
|
src/components/LuckyList.js | kisnows/luckydraw | import React from 'react'
import Lucky from './Lucky'
import PropTypes from 'prop-types'
import ReactCssTransitionGroup from 'react-addons-css-transition-group'
import './LuckyList.css'
export default function LuckyList({ objList, handleLuckyDelete }, { titles }) {
const luckyList = objList && objList.map((v) => {
return <Lucky key={v[titles[1]]} data={v} handleLuckyDelete={handleLuckyDelete} />
})
return (
<ReactCssTransitionGroup
transitionEnterTimeout={300}
transitionLeaveTimeout={300}
transitionName={'lucky'}
component={'div'}
>
{luckyList}
</ReactCssTransitionGroup>
)
}
LuckyList.contextTypes = {
titles: PropTypes.array
}
|
packages/canvas-media/src/shared/CanvasSelect.js | djbender/canvas-lms | /*
* Copyright (C) 2020 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
---
CanvasSelect is a wrapper on the new (as of instui 5 or 6 or so) controlled-only Select
While CanvasSelect is also controlled-only, it has a simpler api and is almost a drop-in
replacement for the old instui Select used throughout canvas at this time. One big difference
is the need to pass in an options property rather than rendering <Options> children
It does not currently support old-Select's allowCustom property
(see https://instructure.design/#DeprecatedSelect)
It only handles single-select. Multi-select will likely have to be in a separate component
<CanvasSelect
id="your-id"
label="select's label"
value={value} // should match the ID of the selected option
onChange={handleChange} // function(event, selectedOption)
{...otherPropsPassedToTheUnderlyingSelect} // if you need to (width="100%" is a popular one)
>
<CanvasSelect.Option key="1" id="1" value="1">one</CanvasSelect.Option>
<CanvasSelect.Option key="2" id="2" value="2">two</CanvasSelect.Option>
<CanvasSelect.Option key="3" id="3" value="3">three</CanvasSelect.Option>
</CanvasSelect>
---
*/
/*
* this file is a copy of canvas-lms/packages/canvas-planner/src/CanvasSelect.js
* but with strings passed in, rather then formatMessage'd here.
*/
import React from 'react'
import {func, node, string, shape, oneOfType} from 'prop-types'
import {compact, castArray, isEqual} from 'lodash'
import formatMessage from 'format-message'
import {Select} from '@instructure/ui-select'
import {Alert} from '@instructure/ui-alerts'
import {matchComponentTypes} from '@instructure/ui-react-utils'
const noOptionsOptionId = '_noOptionsOption'
// CanvasSelectOption and CanvasSelectGroup are components our client can create thru CanvasSelect
// to pass us our options. They are never rendered themselves, but get transformed into INSTUI's
// Select.Option and Select.Group on rendering CanvasSelect. See renderChildren below.
function CanvasSelectOption() {
return <div />
}
CanvasSelectOption.propTypes = {
id: string.isRequired, // eslint-disable-line react/no-unused-prop-types
value: string.isRequired // eslint-disable-line react/no-unused-prop-types
}
function CanvasSelectGroup() {
return <div />
}
CanvasSelectGroup.propTypes = {
label: string.isRequired // eslint-disable-line react/no-unused-prop-types
}
export default class CanvasSelect extends React.Component {
static Option = CanvasSelectOption
static Group = CanvasSelectGroup
static propTypes = {
id: string,
label: oneOfType([node, func]).isRequired,
liveRegion: func,
value: string,
onChange: func.isRequired,
children: node,
noOptionsLabel: string, // unselectable option to display when there are no options
translatedStrings: shape({
USE_ARROWS: string.isRequired,
LIST_COLLAPSED: string.isRequired,
LIST_EXPANDED: string.isRequired,
OPTION_SELECTED: string.isRequired
}),
onBlur: func
}
static defaultProps = {
noOptionsLabel: '---'
}
constructor(props) {
super(props)
const option = this.getOptionByFieldValue('value', props.value)
this.state = {
inputValue: option ? option.props.children : '',
isShowingOptions: false,
highlightedOptionId: null,
selectedOptionId: option ? option.props.id : null,
announcement: null
}
}
componentDidUpdate(prevProps) {
if (this.props.value !== prevProps.value || !isEqual(this.props.children, prevProps.children)) {
const option = this.getOptionByFieldValue('value', this.props.value)
// eslint-disable-next-line react/no-did-update-set-state
this.setState({
inputValue: option ? option.props.children : '',
selectedOptionId: option ? option.props.id : ''
})
}
}
render() {
const {id, label, value, onChange, children, noOptionsLabel, ...otherProps} = this.props
return (
<>
<Select
id={id}
renderLabel={() => label}
assistiveText={this.props.translatedStrings.USE_ARROWS}
inputValue={this.state.inputValue}
isShowingOptions={this.state.isShowingOptions}
onBlur={this.handleBlur}
onRequestShowOptions={this.handleShowOptions}
onRequestHideOptions={this.handleHideOptions}
onRequestHighlightOption={this.handleHighlightOption}
onRequestSelectOption={this.handleSelectOption}
{...otherProps}
>
{this.renderChildren(children)}
</Select>
<Alert liveRegion={this.props.liveRegion} liveRegionPoliteness="assertive" screenReaderOnly>
{this.state.announcement}
</Alert>
</>
)
}
renderChildren(children) {
if (!Array.isArray(children)) {
// children is 1 child
if (matchComponentTypes(children, [CanvasSelectOption])) {
return this.renderOption(children)
} else if (matchComponentTypes(children, [CanvasSelectGroup])) {
return this.renderGroup(children)
} else {
return this.renderNoOptionsOption()
}
}
const opts = children
.map(child => {
if (Array.isArray(child)) {
return this.renderChildren(child)
} else if (matchComponentTypes(child, [CanvasSelectOption])) {
return this.renderOption(child)
} else if (matchComponentTypes(child, [CanvasSelectGroup])) {
return this.renderGroup(child)
}
return null
})
.filter(child => !!child) // instui Select blows up on undefined options
if (opts.length === 0) {
return this.renderNoOptionsOption()
}
return opts
}
backupKey = 0
renderOption(option) {
const {id, children, ...optionProps} = option.props
return (
<Select.Option
id={id}
key={option.key || id || ++this.backupKey}
isHighlighted={id === this.state.highlightedOptionId}
isSelected={id === this.state.selectedOptionId}
{...optionProps}
>
{children}
</Select.Option>
)
}
renderGroup(group) {
const {id, label, ...otherProps} = group.props
const children = compact(castArray(group.props.children))
return (
<Select.Group
data-testid={`Group:${label}`}
renderLabel={() => label}
key={group.key || id || ++this.backupKey}
{...otherProps}
>
{children.map(c => this.renderOption(c))}
</Select.Group>
)
}
renderNoOptionsOption() {
return (
<Select.Option id={noOptionsOptionId} isHighlighted={false} isSelected={false}>
{this.props.noOptionsLabel}
</Select.Option>
)
}
handleBlur = event => {
this.setState({highlightedOptionId: null, announcement: null})
if (this.props.onBlur) {
this.props.onBlur(event)
}
}
handleShowOptions = () => {
this.setState({
isShowingOptions: true
})
}
handleHideOptions = _event => {
this.setState(state => {
const text = this.getOptionLabelById(state.selectedOptionId)
return {
isShowingOptions: false,
highlightedOptionId: null,
inputValue: text
}
})
}
/* eslint-disable react/no-access-state-in-setstate */
// Because handleShowOptions sets state.isShowingOptions:true
// it's already in the value of state passed to the setState(updater)
// by the time handleHighlightOption is called we miss the transition,
// this.state still has the previous value as of the last render
// which is what we need. This is why we use this version of setState.
handleHighlightOption = (event, {id}) => {
if (id === noOptionsOptionId) return
const text = this.getOptionLabelById(id)
const nowOpen = this.state.isShowingOptions ? '' : this.props.translatedStrings.LIST_EXPANDED
const inputValue = event.type === 'keydown' ? text : this.state.inputValue
this.setState({
highlightedOptionId: id,
inputValue,
announcement: `${text} ${nowOpen}`
})
}
/* eslint-enable react/no-access-state-in-setstate */
handleSelectOption = (event, {id}) => {
if (id === noOptionsOptionId) {
this.setState({
isShowingOptions: false,
announcement: this.props.translatedStrings.LIST_COLLAPSED
})
} else {
const text = this.getOptionLabelById(id)
const prevSelection = this.state.selectedOptionId
this.setState({
selectedOptionId: id,
inputValue: text,
isShowingOptions: false,
announcement: formatMessage(this.props.translatedStrings.OPTION_SELECTED, {option: text})
})
const option = this.getOptionByFieldValue('id', id)
if (prevSelection !== id) {
this.props.onChange(event, option.props.value)
}
}
}
getOptionLabelById(oid) {
const option = this.getOptionByFieldValue('id', oid)
return option ? option.props.children : ''
}
getOptionByFieldValue(field, value, options = castArray(this.props.children)) {
if (!this.props.children) return null
let foundOpt = null
for (let i = 0; i < options.length; ++i) {
const o = options[i]
if (Array.isArray(o)) {
foundOpt = this.getOptionByFieldValue(field, value, o)
} else if (matchComponentTypes(o, [CanvasSelectOption])) {
if (o.props[field] === value) {
foundOpt = o
}
} else if (matchComponentTypes(o, [CanvasSelectGroup])) {
const groupOptions = castArray(o.props.children)
for (let j = 0; j < groupOptions.length; ++j) {
const o2 = groupOptions[j]
if (o2.props[field] === value) {
foundOpt = o2
break
}
}
}
if (foundOpt) {
break
}
}
return foundOpt
}
}
|
app/javascript/mastodon/components/autosuggest_textarea.js | mhffdq/mastodon | import React from 'react';
import AutosuggestAccountContainer from '../features/compose/containers/autosuggest_account_container';
import AutosuggestEmoji from './autosuggest_emoji';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { isRtl } from '../rtl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Textarea from 'react-textarea-autosize';
import classNames from 'classnames';
const textAtCursorMatchesToken = (str, caretPosition) => {
let word;
let left = str.slice(0, caretPosition).search(/\S+$/);
let right = str.slice(caretPosition).search(/\s/);
if (right < 0) {
word = str.slice(left);
} else {
word = str.slice(left, right + caretPosition);
}
if (!word || word.trim().length < 3 || ['@', ':', '#'].indexOf(word[0]) === -1) {
return [null, null];
}
word = word.trim().toLowerCase();
if (word.length > 0) {
return [left + 1, word];
} else {
return [null, null];
}
};
export default class AutosuggestTextarea extends ImmutablePureComponent {
static propTypes = {
value: PropTypes.string,
suggestions: ImmutablePropTypes.list,
disabled: PropTypes.bool,
placeholder: PropTypes.string,
onSuggestionSelected: PropTypes.func.isRequired,
onSuggestionsClearRequested: PropTypes.func.isRequired,
onSuggestionsFetchRequested: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
onKeyUp: PropTypes.func,
onKeyDown: PropTypes.func,
onPaste: PropTypes.func.isRequired,
autoFocus: PropTypes.bool,
};
static defaultProps = {
autoFocus: true,
};
state = {
suggestionsHidden: false,
selectedSuggestion: 0,
lastToken: null,
tokenStart: 0,
};
onChange = (e) => {
const [ tokenStart, token ] = textAtCursorMatchesToken(e.target.value, e.target.selectionStart);
if (token !== null && this.state.lastToken !== token) {
this.setState({ lastToken: token, selectedSuggestion: 0, tokenStart });
this.props.onSuggestionsFetchRequested(token);
} else if (token === null) {
this.setState({ lastToken: null });
this.props.onSuggestionsClearRequested();
}
this.props.onChange(e);
}
onKeyDown = (e) => {
const { suggestions, disabled } = this.props;
const { selectedSuggestion, suggestionsHidden } = this.state;
if (disabled) {
e.preventDefault();
return;
}
switch(e.key) {
case 'Escape':
if (!suggestionsHidden) {
e.preventDefault();
this.setState({ suggestionsHidden: true });
}
break;
case 'ArrowDown':
if (suggestions.size > 0 && !suggestionsHidden) {
e.preventDefault();
this.setState({ selectedSuggestion: Math.min(selectedSuggestion + 1, suggestions.size - 1) });
}
break;
case 'ArrowUp':
if (suggestions.size > 0 && !suggestionsHidden) {
e.preventDefault();
this.setState({ selectedSuggestion: Math.max(selectedSuggestion - 1, 0) });
}
break;
case 'Enter':
case 'Tab':
// Select suggestion
if (this.state.lastToken !== null && suggestions.size > 0 && !suggestionsHidden) {
e.preventDefault();
e.stopPropagation();
this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestions.get(selectedSuggestion));
}
break;
}
if (e.defaultPrevented || !this.props.onKeyDown) {
return;
}
this.props.onKeyDown(e);
}
onKeyUp = e => {
if (e.key === 'Escape' && this.state.suggestionsHidden) {
document.querySelector('.ui').parentElement.focus();
}
if (this.props.onKeyUp) {
this.props.onKeyUp(e);
}
}
onBlur = () => {
this.setState({ suggestionsHidden: true });
}
onSuggestionClick = (e) => {
const suggestion = this.props.suggestions.get(e.currentTarget.getAttribute('data-index'));
e.preventDefault();
this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion);
this.textarea.focus();
}
componentWillReceiveProps (nextProps) {
if (nextProps.suggestions !== this.props.suggestions && nextProps.suggestions.size > 0 && this.state.suggestionsHidden) {
this.setState({ suggestionsHidden: false });
}
}
setTextarea = (c) => {
this.textarea = c;
}
onPaste = (e) => {
if (e.clipboardData && e.clipboardData.files.length === 1) {
this.props.onPaste(e.clipboardData.files);
e.preventDefault();
}
}
renderSuggestion = (suggestion, i) => {
const { selectedSuggestion } = this.state;
let inner, key;
if (typeof suggestion === 'object') {
inner = <AutosuggestEmoji emoji={suggestion} />;
key = suggestion.id;
} else if (suggestion[0] === '#') {
inner = suggestion;
key = suggestion;
} else {
inner = <AutosuggestAccountContainer id={suggestion} />;
key = suggestion;
}
return (
<div role='button' tabIndex='0' key={key} data-index={i} className={classNames('autosuggest-textarea__suggestions__item', { selected: i === selectedSuggestion })} onMouseDown={this.onSuggestionClick}>
{inner}
</div>
);
}
render () {
const { value, suggestions, disabled, placeholder, autoFocus } = this.props;
const { suggestionsHidden } = this.state;
const style = { direction: 'ltr' };
if (isRtl(value)) {
style.direction = 'rtl';
}
return (
<div className='autosuggest-textarea'>
<label>
<span style={{ display: 'none' }}>{placeholder}</span>
<Textarea
inputRef={this.setTextarea}
className='autosuggest-textarea__textarea'
disabled={disabled}
placeholder={placeholder}
autoFocus={autoFocus}
value={value}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
onKeyUp={this.onKeyUp}
onBlur={this.onBlur}
onPaste={this.onPaste}
style={style}
aria-autocomplete='list'
/>
</label>
<div className={`autosuggest-textarea__suggestions ${suggestionsHidden || suggestions.isEmpty() ? '' : 'autosuggest-textarea__suggestions--visible'}`}>
{suggestions.map(this.renderSuggestion)}
</div>
</div>
);
}
}
|
client/modules/core/components/.stories/poll.js | thancock20/voting-app | import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { withKnobs, text, boolean, number, object } from '@kadira/storybook-addon-knobs';
import { setComposerStub } from 'react-komposer';
import Poll from '../poll.jsx';
storiesOf('core.Poll', module)
.addDecorator(withKnobs)
.add('default view', () => {
const poll = object('poll', {
_id: 'abc123',
question: 'Ice Cream Flavors',
isOwner: () => true
});
return (
<Poll
poll={poll}
deletePoll={action('poll-delete-clicked')}
/>
);
})
.add('non-owner', () => {
const poll = object('poll', {
_id: 'abc123',
question: 'Ice Cream Flavors',
isOwner: () => false
});
return (
<Poll
poll={poll}
deletePoll={action('poll-delete-clicked')}
/>
);
});
|
src/packages/@ncigdc/components/Charts/BarChart.js | NCI-GDC/portal-ui | // @flow
// Vender
import React from 'react';
import * as d3 from 'd3';
import ReactFauxDOM from 'react-faux-dom';
import {
compose,
withState,
pure,
} from 'recompose';
// Custom
import { withTheme } from '@ncigdc/theme';
import { withTooltip } from '@ncigdc/uikit/Tooltip';
import withSize from '@ncigdc/utils/withSize';
import './style.css';
export const DEFAULT_X_AXIS_LABEL_LENGTH = 10;
const BarChart = ({
data,
height: h,
mappingLabel = 'label', // name it with the key you want, e.g. if your data structure is {id: 'bla', count: 1234 } put label = 'id' and value = 'count'
mappingValue = 'value',
margin: m,
setTooltip,
showXAxisLabels = true,
size: { width },
styles,
theme,
title,
xAxis = {}, // Must have titleForSVG and title if showXAxisLabels is false.
xAxisLabelLength = DEFAULT_X_AXIS_LABEL_LENGTH,
yAxis = {},
}) => {
if (!showXAxisLabels && (!xAxis.title || !xAxis.titleForSVG)) {
throw new Error('For GDC Developers, when showXAxisLabels is false, value of titleForSVG or title in xAxis should not be blank.');
}
const el = ReactFauxDOM.createElement('div');
el.style.width = '100%';
el.setAttribute('class', 'test-bar-chart');
const innerPadding = 0.3;
const outerPadding = 0.3;
const margin = m || {
top: 20,
right: 50,
bottom: 65,
left: 55,
};
const chartWidth = width - margin.left - margin.right;
const height = (h || 200) - margin.top - margin.bottom;
const yAxisStyle = yAxis.style || {
textFill: theme.greyScale3,
fontSize: '1.3rem',
fontWeight: '500',
stroke: theme.greyScale4,
};
const xAxisStyle = xAxis.style || {
textFill: theme.greyScale3,
fontSize: '1.3rem',
fontWeight: '700',
stroke: theme.greyScale4,
};
const x = d3
.scaleBand()
.domain(data.map(d => d[mappingLabel]))
.rangeRound([0, chartWidth])
.paddingInner(innerPadding)
.paddingOuter(outerPadding);
const maxY = d3.max(data, d => d[mappingValue]);
const y = d3
.scaleLinear()
.range([height, 0])
.domain([0, maxY]);
const svg = d3
.select(el)
.append('svg')
.attr('width', width)
.attr('height', height + margin.top + margin.bottom)
.append('g', 'chart')
.attr('fill', '#fff')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
svg
.append('text')
.attr('y', 0 - margin.top)
.attr('x', width / 2)
.attr('dy', '1em')
.style('text-anchor', 'middle')
.style('fontSize', '1.1rem')
.style('fontWeight', '500')
.attr('fill', yAxisStyle.textFill)
.text(title);
const yG = svg.append('g').call(
d3
.axisLeft(y)
.ticks(Math.min(4, maxY))
.tickSize(-chartWidth)
.tickSizeOuter(0)
);
yG.selectAll('path').style('stroke', 'none');
yG.selectAll('line').style('stroke', yAxisStyle.stroke);
yG.selectAll('text')
.style('fontSize', yAxisStyle.fontSize)
.style('fill', yAxisStyle.textFill);
svg
.append('text')
.attr('transform', 'rotate(-90)')
.attr('y', 0 - margin.left)
.attr('x', 0 - height / 2)
.attr('dy', '1em')
.style('text-anchor', 'middle')
.style('fontSize', yAxisStyle.fontSize)
.style('fontWeight', yAxisStyle.fontWeight)
.attr('fill', yAxisStyle.textFill)
.text(yAxis.title || '');
if (showXAxisLabels) {
// hidden x axis for full length labels in svg download
const hiddenXG = svg
.append('g')
.attr('class', 'svgDownload')
.attr('transform', `translate(0, ${height})`)
.call(d3.axisBottom(x));
hiddenXG.selectAll('text')
.style('text-anchor', 'start')
.style('fontSize', xAxisStyle.fontSize)
.style('fontWeight', xAxisStyle.fontWeight)
.attr('fill', xAxisStyle.textFill)
.attr('dx', '.8em')
.attr('dy', '.5em')
.text(d => d)
.attr('transform', 'rotate(45)');
hiddenXG.selectAll('path').style('stroke', xAxisStyle.stroke);
hiddenXG.selectAll('line').style('stroke', xAxisStyle.stroke);
// display x axis
const xG = svg
.append('g')
.attr('class', 'displayOnly')
.attr('transform', `translate(0, ${height})`)
.call(d3.axisBottom(x));
xG.selectAll('text')
.style('text-anchor', 'start')
.style('fontSize', xAxisStyle.fontSize)
.style('fontWeight', xAxisStyle.fontWeight)
.attr('fill', xAxisStyle.textFill)
.attr('dx', '.8em')
.attr('dy', '.5em')
.text(d => (d.length > xAxisLabelLength ? `${d.substring(0, xAxisLabelLength - 3)}...` : d))
.attr('transform', 'rotate(45)');
xG.selectAll('path').style('stroke', xAxisStyle.stroke);
xG.selectAll('line').style('stroke', xAxisStyle.stroke);
xG.selectAll('.tick')
.data(data)
.on('mouseenter', d => {
setTooltip(d.tooltip);
})
.on('mouseleave', () => {
setTooltip();
});
} else {
svg
.append('text')
.attr('class', 'displayOnly')
.attr('transform', 'rotate(0)')
.attr('y', height + 20)
.attr('x', width / 2 - margin.left)
.attr('dx', '1em')
.style('text-anchor', 'middle')
.style('fontSize', '1.2rem')
.style('fontWeight', '500')
.attr('fill', yAxisStyle.textFill)
.text(xAxis.title);
svg
.append('text')
.attr('class', 'svgDownload')
.attr('transform', 'rotate(0)')
.attr('y', height + 20)
.attr('x', width / 2 - margin.left)
.attr('dx', '1em')
.style('text-anchor', 'middle')
.style('fontSize', '1.2rem')
.style('fontWeight', '500')
.attr('fill', xAxisStyle.textFill)
.text(xAxis.titleForSVG);
}
const barGs = svg
.selectAll('g.chart')
.data(data)
.enter()
.append('g')
.attr('class', 'bar-g');
const drawBar = barG => {
barG
.append('rect')
.attr('class', 'bar')
.attr('fill', (styles.bars || { fill: 'steelblue' }).fill)
.attr('width', x.bandwidth())
.attr('y', d => y(d[mappingValue]))
.attr('x', d => x(d[mappingLabel]))
.attr('height', d => height - y(d[mappingValue]))
.on('click', d => {
if (d.onClick) {
d.onClick();
}
})
.classed('pointer', d => d.onClick)
.on('mouseenter', d => {
setTooltip(d.tooltip);
})
.on('mouseleave', () => {
setTooltip();
});
};
barGs.each(function selectAndDraw() {
drawBar(d3.select(this));
});
return el.toReact();
};
export default compose(
withTheme,
withTooltip,
withState('chart', 'setState', <span />),
withSize({ refreshRate: 16 }),
pure
)(BarChart);
|
src/js/components/icons/base/DocumentText.js | kylebyerly-hp/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-document-text`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'document-text');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M6,16 L16,16 L6,16 L6,16 Z M6,12 L18,12 L6,12 L6,12 Z M6,8 L11,8 L6,8 L6,8 Z M14,1 L14,8 L21,8 M3,23 L3,1 L15,1 L21,7 L21,23 L3,23 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'DocumentText';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
ajax/libs/preact/8.2.2/preact.js | jonobr1/cdnjs | !function() {
'use strict';
function VNode() {}
function h(nodeName, attributes) {
var lastSimple, child, simple, i, children = EMPTY_CHILDREN;
for (i = arguments.length; i-- > 2; ) stack.push(arguments[i]);
if (attributes && null != attributes.children) {
if (!stack.length) stack.push(attributes.children);
delete attributes.children;
}
while (stack.length) if ((child = stack.pop()) && void 0 !== child.pop) for (i = child.length; i--; ) stack.push(child[i]); else {
if ('boolean' == typeof child) child = null;
if (simple = 'function' != typeof nodeName) if (null == child) child = ''; else if ('number' == typeof child) child = String(child); else if ('string' != typeof child) simple = !1;
if (simple && lastSimple) children[children.length - 1] += child; else if (children === EMPTY_CHILDREN) children = [ child ]; else children.push(child);
lastSimple = simple;
}
var p = new VNode();
p.nodeName = nodeName;
p.children = children;
p.attributes = null == attributes ? void 0 : attributes;
p.key = null == attributes ? void 0 : attributes.key;
if (void 0 !== options.vnode) options.vnode(p);
return p;
}
function extend(obj, props) {
for (var i in props) obj[i] = props[i];
return obj;
}
function cloneElement(vnode, props) {
return h(vnode.nodeName, extend(extend({}, vnode.attributes), props), arguments.length > 2 ? [].slice.call(arguments, 2) : vnode.children);
}
function enqueueRender(component) {
if (!component.__d && (component.__d = !0) && 1 == items.push(component)) (options.debounceRendering || defer)(rerender);
}
function rerender() {
var p, list = items;
items = [];
while (p = list.pop()) if (p.__d) renderComponent(p);
}
function isSameNodeType(node, vnode, hydrating) {
if ('string' == typeof vnode || 'number' == typeof vnode) return void 0 !== node.splitText;
if ('string' == typeof vnode.nodeName) return !node._componentConstructor && isNamedNode(node, vnode.nodeName); else return hydrating || node._componentConstructor === vnode.nodeName;
}
function isNamedNode(node, nodeName) {
return node.__n === nodeName || node.nodeName.toLowerCase() === nodeName.toLowerCase();
}
function getNodeProps(vnode) {
var props = extend({}, vnode.attributes);
props.children = vnode.children;
var defaultProps = vnode.nodeName.defaultProps;
if (void 0 !== defaultProps) for (var i in defaultProps) if (void 0 === props[i]) props[i] = defaultProps[i];
return props;
}
function createNode(nodeName, isSvg) {
var node = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName);
node.__n = nodeName;
return node;
}
function removeNode(node) {
var parentNode = node.parentNode;
if (parentNode) parentNode.removeChild(node);
}
function setAccessor(node, name, old, value, isSvg) {
if ('className' === name) name = 'class';
if ('key' === name) ; else if ('ref' === name) {
if (old) old(null);
if (value) value(node);
} else if ('class' === name && !isSvg) node.className = value || ''; else if ('style' === name) {
if (!value || 'string' == typeof value || 'string' == typeof old) node.style.cssText = value || '';
if (value && 'object' == typeof value) {
if ('string' != typeof old) for (var i in old) if (!(i in value)) node.style[i] = '';
for (var i in value) node.style[i] = 'number' == typeof value[i] && !1 === IS_NON_DIMENSIONAL.test(i) ? value[i] + 'px' : value[i];
}
} else if ('dangerouslySetInnerHTML' === name) {
if (value) node.innerHTML = value.__html || '';
} else if ('o' == name[0] && 'n' == name[1]) {
var useCapture = name !== (name = name.replace(/Capture$/, ''));
name = name.toLowerCase().substring(2);
if (value) {
if (!old) node.addEventListener(name, eventProxy, useCapture);
} else node.removeEventListener(name, eventProxy, useCapture);
(node.__l || (node.__l = {}))[name] = value;
} else if ('list' !== name && 'type' !== name && !isSvg && name in node) {
setProperty(node, name, null == value ? '' : value);
if (null == value || !1 === value) node.removeAttribute(name);
} else {
var ns = isSvg && name !== (name = name.replace(/^xlink\:?/, ''));
if (null == value || !1 === value) if (ns) node.removeAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase()); else node.removeAttribute(name); else if ('function' != typeof value) if (ns) node.setAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase(), value); else node.setAttribute(name, value);
}
}
function setProperty(node, name, value) {
try {
node[name] = value;
} catch (e) {}
}
function eventProxy(e) {
return this.__l[e.type](options.event && options.event(e) || e);
}
function flushMounts() {
var c;
while (c = mounts.pop()) {
if (options.afterMount) options.afterMount(c);
if (c.componentDidMount) c.componentDidMount();
}
}
function diff(dom, vnode, context, mountAll, parent, componentRoot) {
if (!diffLevel++) {
isSvgMode = null != parent && void 0 !== parent.ownerSVGElement;
hydrating = null != dom && !('__preactattr_' in dom);
}
var ret = idiff(dom, vnode, context, mountAll, componentRoot);
if (parent && ret.parentNode !== parent) parent.appendChild(ret);
if (!--diffLevel) {
hydrating = !1;
if (!componentRoot) flushMounts();
}
return ret;
}
function idiff(dom, vnode, context, mountAll, componentRoot) {
var out = dom, prevSvgMode = isSvgMode;
if (null == vnode || 'boolean' == typeof vnode) vnode = '';
if ('string' == typeof vnode || 'number' == typeof vnode) {
if (dom && void 0 !== dom.splitText && dom.parentNode && (!dom._component || componentRoot)) {
if (dom.nodeValue != vnode) dom.nodeValue = vnode;
} else {
out = document.createTextNode(vnode);
if (dom) {
if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
recollectNodeTree(dom, !0);
}
}
out.__preactattr_ = !0;
return out;
}
var vnodeName = vnode.nodeName;
if ('function' == typeof vnodeName) return buildComponentFromVNode(dom, vnode, context, mountAll);
isSvgMode = 'svg' === vnodeName ? !0 : 'foreignObject' === vnodeName ? !1 : isSvgMode;
vnodeName = String(vnodeName);
if (!dom || !isNamedNode(dom, vnodeName)) {
out = createNode(vnodeName, isSvgMode);
if (dom) {
while (dom.firstChild) out.appendChild(dom.firstChild);
if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
recollectNodeTree(dom, !0);
}
}
var fc = out.firstChild, props = out.__preactattr_, vchildren = vnode.children;
if (null == props) {
props = out.__preactattr_ = {};
for (var a = out.attributes, i = a.length; i--; ) props[a[i].name] = a[i].value;
}
if (!hydrating && vchildren && 1 === vchildren.length && 'string' == typeof vchildren[0] && null != fc && void 0 !== fc.splitText && null == fc.nextSibling) {
if (fc.nodeValue != vchildren[0]) fc.nodeValue = vchildren[0];
} else if (vchildren && vchildren.length || null != fc) innerDiffNode(out, vchildren, context, mountAll, hydrating || null != props.dangerouslySetInnerHTML);
diffAttributes(out, vnode.attributes, props);
isSvgMode = prevSvgMode;
return out;
}
function innerDiffNode(dom, vchildren, context, mountAll, isHydrating) {
var j, c, f, vchild, child, originalChildren = dom.childNodes, children = [], keyed = {}, keyedLen = 0, min = 0, len = originalChildren.length, childrenLen = 0, vlen = vchildren ? vchildren.length : 0;
if (0 !== len) for (var i = 0; i < len; i++) {
var _child = originalChildren[i], props = _child.__preactattr_, key = vlen && props ? _child._component ? _child._component.__k : props.key : null;
if (null != key) {
keyedLen++;
keyed[key] = _child;
} else if (props || (void 0 !== _child.splitText ? isHydrating ? _child.nodeValue.trim() : !0 : isHydrating)) children[childrenLen++] = _child;
}
if (0 !== vlen) for (var i = 0; i < vlen; i++) {
vchild = vchildren[i];
child = null;
var key = vchild.key;
if (null != key) {
if (keyedLen && void 0 !== keyed[key]) {
child = keyed[key];
keyed[key] = void 0;
keyedLen--;
}
} else if (!child && min < childrenLen) for (j = min; j < childrenLen; j++) if (void 0 !== children[j] && isSameNodeType(c = children[j], vchild, isHydrating)) {
child = c;
children[j] = void 0;
if (j === childrenLen - 1) childrenLen--;
if (j === min) min++;
break;
}
child = idiff(child, vchild, context, mountAll);
f = originalChildren[i];
if (child && child !== dom && child !== f) if (null == f) dom.appendChild(child); else if (child === f.nextSibling) removeNode(f); else dom.insertBefore(child, f);
}
if (keyedLen) for (var i in keyed) if (void 0 !== keyed[i]) recollectNodeTree(keyed[i], !1);
while (min <= childrenLen) if (void 0 !== (child = children[childrenLen--])) recollectNodeTree(child, !1);
}
function recollectNodeTree(node, unmountOnly) {
var component = node._component;
if (component) unmountComponent(component); else {
if (null != node.__preactattr_ && node.__preactattr_.ref) node.__preactattr_.ref(null);
if (!1 === unmountOnly || null == node.__preactattr_) removeNode(node);
removeChildren(node);
}
}
function removeChildren(node) {
node = node.lastChild;
while (node) {
var next = node.previousSibling;
recollectNodeTree(node, !0);
node = next;
}
}
function diffAttributes(dom, attrs, old) {
var name;
for (name in old) if ((!attrs || null == attrs[name]) && null != old[name]) setAccessor(dom, name, old[name], old[name] = void 0, isSvgMode);
for (name in attrs) if (!('children' === name || 'innerHTML' === name || name in old && attrs[name] === ('value' === name || 'checked' === name ? dom[name] : old[name]))) setAccessor(dom, name, old[name], old[name] = attrs[name], isSvgMode);
}
function collectComponent(component) {
var name = component.constructor.name;
(components[name] || (components[name] = [])).push(component);
}
function createComponent(Ctor, props, context) {
var inst, list = components[Ctor.name];
if (Ctor.prototype && Ctor.prototype.render) {
inst = new Ctor(props, context);
Component.call(inst, props, context);
} else {
inst = new Component(props, context);
inst.constructor = Ctor;
inst.render = doRender;
}
if (list) for (var i = list.length; i--; ) if (list[i].constructor === Ctor) {
inst.__b = list[i].__b;
list.splice(i, 1);
break;
}
return inst;
}
function doRender(props, state, context) {
return this.constructor(props, context);
}
function setComponentProps(component, props, opts, context, mountAll) {
if (!component.__x) {
component.__x = !0;
if (component.__r = props.ref) delete props.ref;
if (component.__k = props.key) delete props.key;
if (!component.base || mountAll) {
if (component.componentWillMount) component.componentWillMount();
} else if (component.componentWillReceiveProps) component.componentWillReceiveProps(props, context);
if (context && context !== component.context) {
if (!component.__c) component.__c = component.context;
component.context = context;
}
if (!component.__p) component.__p = component.props;
component.props = props;
component.__x = !1;
if (0 !== opts) if (1 === opts || !1 !== options.syncComponentUpdates || !component.base) renderComponent(component, 1, mountAll); else enqueueRender(component);
if (component.__r) component.__r(component);
}
}
function renderComponent(component, opts, mountAll, isChild) {
if (!component.__x) {
var rendered, inst, cbase, props = component.props, state = component.state, context = component.context, previousProps = component.__p || props, previousState = component.__s || state, previousContext = component.__c || context, isUpdate = component.base, nextBase = component.__b, initialBase = isUpdate || nextBase, initialChildComponent = component._component, skip = !1;
if (isUpdate) {
component.props = previousProps;
component.state = previousState;
component.context = previousContext;
if (2 !== opts && component.shouldComponentUpdate && !1 === component.shouldComponentUpdate(props, state, context)) skip = !0; else if (component.componentWillUpdate) component.componentWillUpdate(props, state, context);
component.props = props;
component.state = state;
component.context = context;
}
component.__p = component.__s = component.__c = component.__b = null;
component.__d = !1;
if (!skip) {
rendered = component.render(props, state, context);
if (component.getChildContext) context = extend(extend({}, context), component.getChildContext());
var toUnmount, base, childComponent = rendered && rendered.nodeName;
if ('function' == typeof childComponent) {
var childProps = getNodeProps(rendered);
inst = initialChildComponent;
if (inst && inst.constructor === childComponent && childProps.key == inst.__k) setComponentProps(inst, childProps, 1, context, !1); else {
toUnmount = inst;
component._component = inst = createComponent(childComponent, childProps, context);
inst.__b = inst.__b || nextBase;
inst.__u = component;
setComponentProps(inst, childProps, 0, context, !1);
renderComponent(inst, 1, mountAll, !0);
}
base = inst.base;
} else {
cbase = initialBase;
toUnmount = initialChildComponent;
if (toUnmount) cbase = component._component = null;
if (initialBase || 1 === opts) {
if (cbase) cbase._component = null;
base = diff(cbase, rendered, context, mountAll || !isUpdate, initialBase && initialBase.parentNode, !0);
}
}
if (initialBase && base !== initialBase && inst !== initialChildComponent) {
var baseParent = initialBase.parentNode;
if (baseParent && base !== baseParent) {
baseParent.replaceChild(base, initialBase);
if (!toUnmount) {
initialBase._component = null;
recollectNodeTree(initialBase, !1);
}
}
}
if (toUnmount) unmountComponent(toUnmount);
component.base = base;
if (base && !isChild) {
var componentRef = component, t = component;
while (t = t.__u) (componentRef = t).base = base;
base._component = componentRef;
base._componentConstructor = componentRef.constructor;
}
}
if (!isUpdate || mountAll) mounts.unshift(component); else if (!skip) {
if (component.componentDidUpdate) component.componentDidUpdate(previousProps, previousState, previousContext);
if (options.afterUpdate) options.afterUpdate(component);
}
if (null != component.__h) while (component.__h.length) component.__h.pop().call(component);
if (!diffLevel && !isChild) flushMounts();
}
}
function buildComponentFromVNode(dom, vnode, context, mountAll) {
var c = dom && dom._component, originalComponent = c, oldDom = dom, isDirectOwner = c && dom._componentConstructor === vnode.nodeName, isOwner = isDirectOwner, props = getNodeProps(vnode);
while (c && !isOwner && (c = c.__u)) isOwner = c.constructor === vnode.nodeName;
if (c && isOwner && (!mountAll || c._component)) {
setComponentProps(c, props, 3, context, mountAll);
dom = c.base;
} else {
if (originalComponent && !isDirectOwner) {
unmountComponent(originalComponent);
dom = oldDom = null;
}
c = createComponent(vnode.nodeName, props, context);
if (dom && !c.__b) {
c.__b = dom;
oldDom = null;
}
setComponentProps(c, props, 1, context, mountAll);
dom = c.base;
if (oldDom && dom !== oldDom) {
oldDom._component = null;
recollectNodeTree(oldDom, !1);
}
}
return dom;
}
function unmountComponent(component) {
if (options.beforeUnmount) options.beforeUnmount(component);
var base = component.base;
component.__x = !0;
if (component.componentWillUnmount) component.componentWillUnmount();
component.base = null;
var inner = component._component;
if (inner) unmountComponent(inner); else if (base) {
if (base.__preactattr_ && base.__preactattr_.ref) base.__preactattr_.ref(null);
component.__b = base;
removeNode(base);
collectComponent(component);
removeChildren(base);
}
if (component.__r) component.__r(null);
}
function Component(props, context) {
this.__d = !0;
this.context = context;
this.props = props;
this.state = this.state || {};
}
function render(vnode, parent, merge) {
return diff(merge, vnode, {}, !1, parent, !1);
}
var options = {};
var stack = [];
var EMPTY_CHILDREN = [];
var defer = 'function' == typeof Promise ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout;
var IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;
var items = [];
var mounts = [];
var diffLevel = 0;
var isSvgMode = !1;
var hydrating = !1;
var components = {};
extend(Component.prototype, {
setState: function(state, callback) {
var s = this.state;
if (!this.__s) this.__s = extend({}, s);
extend(s, 'function' == typeof state ? state(s, this.props) : state);
if (callback) (this.__h = this.__h || []).push(callback);
enqueueRender(this);
},
forceUpdate: function(callback) {
if (callback) (this.__h = this.__h || []).push(callback);
renderComponent(this, 2);
},
render: function() {}
});
var preact = {
h: h,
createElement: h,
cloneElement: cloneElement,
Component: Component,
render: render,
rerender: rerender,
options: options
};
if ('undefined' != typeof module) module.exports = preact; else self.preact = preact;
}();
//# sourceMappingURL=preact.js.map |
wp-content/themes/westgranvilleplate/content/js/_libs/jquery/jquery-1.11.0.min.js | jrhines/westgranville | /*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f
}}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)
},a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n}); |
src/components/Comments/index.js | transitlinks/web-app | import React from 'react';
import { connect } from 'react-redux';
import {
deleteComment,
saveComment,
saveLike,
} from '../../actions/comments';
import { setProperty } from '../../actions/properties';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Comments.css';
import FontIcon from 'material-ui/FontIcon';
import TextField from 'material-ui/TextField';
import Link from '../Link';
import { injectIntl } from 'react-intl';
const getCommentAuthor = (user) => {
const { username, firstName, lastName, email } = user;
if (username) {
return user.username;
} else if (firstName || lastName) {
return [firstName, lastName].filter(name => name).join(' ');
}
return 'Anonymous';
};
const Comments = ({
comments, checkIn, terminal, commentText, frameId, preview, commentReplyTo,
setProperty, saveComment, deleteComment, saveLike,
auth, env, intl
}) => {
const addReplys = (subComments, sortedComments) => {
subComments.forEach(subComment => {
if (subComment.replyToUuid) sortedComments.push(subComment);
const replys = comments.filter(reply => reply.replyToUuid === subComment.uuid);
addReplys(replys, sortedComments);
});
return sortedComments;
};
const sortedComments = [];
(comments || []).forEach(comment => {
if (!comment.replyToUuid) {
sortedComments.push(comment);
sortedComments.push(...addReplys([comment], []));
}
});
const getCommentInput = (comment) => {
const commentInput = (
<div className={s.commentInput}>
{
comment ?
(
!comments.find(c => c.uuid === comment.replyToUuid) ?
<div className={s.replyToIndicator}></div> : null
) :
<div className={s.icon}>
<FontIcon className="material-icons" style={{ fontSize: '24px' }}>
chat
</FontIcon>
</div>
}
<div className={s.input}>
<TextField id={`comment-input-${frameId}`}
value={commentText[frameId]}
fullWidth
hintText={!commentText[frameId] ? (commentReplyTo ? 'Reply...' : 'Comment...') : null}
onChange={(e) => {
setProperty('posts.commentText', { ...commentText, [frameId]: e.target.value });
}}
onKeyDown={(e) => {
if (e.keyCode === 13) {
const newComment = { text: commentText[frameId] };
if (terminal) newComment.terminalUuid = terminal.uuid;
else if (checkIn) newComment.checkInUuid = checkIn.uuid;
if (commentReplyTo) newComment.replyToUuid = commentReplyTo;
saveComment(newComment, frameId);
setProperty('posts.commentText', { ...commentText, [frameId]: '' });
}
}}
/>
</div>
</div>
);
return commentInput;
};
return (
<div className={s.comments}>
{
(auth && auth.loggedIn && !commentReplyTo) &&
(getCommentInput())
}
{
(comments && comments.length > 0) &&
(preview ? sortedComments.slice(0, 1) : sortedComments).map(comment => {
return (
<div className={s.comment}>
{
comment.replyToUuid &&
<div className={s.replyIndent}>
</div>
}
<div className={s.commentBody}>
<p className={s.commentContent}>
<span className={s.commentAuthor}>
{ getCommentAuthor(comment.user) }
</span>
{ comment.text }
</p>
<div className={s.commentControlsBorder}></div>
{
(commentReplyTo === comment.uuid) &&
(getCommentInput(comment))
}
<div className={s.commentControls} style={ comment.replyToUuid ? { marginRight: '6px' } : {} }>
<div className={s.left}>
{
(auth && auth.loggedIn && comment.user.uuid === auth.user.uuid) && (
<div className={s.delete} onClick={() => deleteComment(comment.uuid, frameId, checkIn.uuid)}>
Delete
</div>
)
}
</div>
<div className={s.right}>
{
(auth && auth.loggedIn) && (
(commentReplyTo === comment.uuid) ?
<div className={s.reply} onClick={() => setProperty('posts.commentReplyTo', null)}>
Cancel
</div> :
<div className={s.reply} onClick={() => setProperty('posts.commentReplyTo', comment.uuid)}>
Reply
</div>
)
}
{
comment.likedByUser ?
<div className={s.commentLikes} onClick={() => saveLike(comment.uuid, 'Comment', 'off', frameId, checkIn.uuid)}>
<div className={s.icon}>
<FontIcon className="material-icons" style={{ fontSize: '16px', color: '#FF0000' }}>
favorite
</FontIcon>
</div>
<div className={s.count}>
{ comment.likes || 0 }
</div>
</div> :
<div className={s.commentLikes} onClick={() => saveLike(comment.uuid, 'Comment', 'on', frameId, checkIn.uuid)}>
<div className={s.icon}>
<FontIcon className="material-icons" style={{ fontSize: '16px' }}>
favorite_border
</FontIcon>
</div>
<div className={s.count}>
{ comment.likes || 0 }
</div>
</div>
}
</div>
</div>
</div>
</div>
);
})
}
{
(preview && comments && comments.length > 1) &&
<div className={s.otherComments}>
<Link to={`/check-in/${checkIn.uuid}?view=${terminal ? terminal.type : 'reaction'}`}>{ comments.length } comments</Link>
</div>
}
</div>
);
}
export default injectIntl(
connect(state => ({
auth: state.auth.auth,
env: state.env,
commentText: state.posts.commentText || {},
commentReplyTo: state.posts.commentReplyTo
}), {
saveComment,
deleteComment,
setProperty,
saveLike
})(withStyles(s)(Comments))
);
|
src/pages/message.js | selfcontained/labelr-react-ampersand-demo | import React from 'react';
export default React.createClass({
displayName: 'MessagePage',
propTypes: {
title: React.PropTypes.string.isRequired,
body: React.PropTypes.string
},
render () {
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.props.body}</p>
</div>
);
}
})
|
app/javascript/mastodon/features/compose/components/text_icon_button.js | anon5r/mastonon | import React from 'react';
import PropTypes from 'prop-types';
export default class TextIconButton extends React.PureComponent {
static propTypes = {
label: PropTypes.string.isRequired,
title: PropTypes.string,
active: PropTypes.bool,
onClick: PropTypes.func.isRequired,
ariaControls: PropTypes.string,
};
handleClick = (e) => {
e.preventDefault();
this.props.onClick();
}
render () {
const { label, title, active, ariaControls } = this.props;
return (
<button title={title} aria-label={title} className={`text-icon-button ${active ? 'active' : ''}`} aria-expanded={active} onClick={this.handleClick} aria-controls={ariaControls}>
{label}
</button>
);
}
}
|
docs/src/app/components/pages/components/Dialog/ExampleSimple.js | nathanmarks/material-ui | import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
/**
* Dialog with action buttons. The actions are passed in as an array of React objects,
* in this example [FlatButtons](/#/components/flat-button).
*
* You can also close this dialog by clicking outside the dialog, or with the 'Esc' key.
*/
export default class DialogExampleSimple extends React.Component {
state = {
open: false,
};
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.setState({open: false});
};
render() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Submit"
primary={true}
keyboardFocused={true}
onTouchTap={this.handleClose}
/>,
];
return (
<div>
<RaisedButton label="Dialog" onTouchTap={this.handleOpen} />
<Dialog
title="Dialog With Actions"
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}
>
The actions in this window were passed in as an array of React objects.
</Dialog>
</div>
);
}
}
|
src/utils/childrenValueInputValidation.js | thealjey/react-bootstrap | import React from 'react';
import { singlePropFrom } from './CustomPropTypes';
const propList = ['children', 'value'];
export default function valueValidation(props, propName, componentName) {
let error = singlePropFrom(propList)(props, propName, componentName);
if (!error) {
error = React.PropTypes.node(props, propName, componentName);
}
return error;
}
|
src/components/Gallery.js | rapind/grokphoto | import React from 'react'
import Firebase from 'firebase'
import ReactFireMixin from 'reactfire'
import { Link } from 'react-router'
export default React.createClass({
mixins: [ReactFireMixin],
propTypes: {
params: React.PropTypes.object
},
getInitialState () {
return {
gallery: null
}
},
componentWillMount () {
this.bindGallery(this.props.params.id)
},
componentWillReceiveProps (nextProps) {
if (this.props.params.id !== nextProps.params.id) {
this.bindGallery(nextProps.params.id)
}
},
bindGallery (id) {
const ref = new Firebase(
`https://togproof.firebaseio.com/galleries/${id}`
)
if (this.state.gallery) this.unbind('gallery')
this.bindAsObject(ref, 'gallery')
},
render () {
const { gallery } = this.state
if (gallery === null) {
return <div></div>
}
return (
<div>
<Link to='/galleries'>Back</Link>
<h2>Gallery: {gallery.title}</h2>
<img src={gallery.cover_image_url} />
</div>
)
}
})
|
index.js | Roconda/redux-material-routing-boilerplate | import React from 'react';
import Root from './src/containers/Root';
import injectTapEventPlugin from 'react-tap-event-plugin'
//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();
React.render(
<div>
<Root />
</div>,
document.getElementById('root')
);
|
docs/app/Examples/elements/Icon/Variations/IconExampleFlipped.js | clemensw/stardust | import React from 'react'
import { Icon } from 'semantic-ui-react'
const IconExampleFlipped = () => (
<div>
<Icon flipped='horizontally' name='cloud' />
<Icon flipped='vertically' name='cloud' />
</div>
)
export default IconExampleFlipped
|
api-gateway/src/main/websrc/src/js/systems/index.js | semiotproject/semiot-platform | import React from 'react';
import { render } from 'react-dom';
import { Router, Route, Link, browserHistory } from 'react-router';
import SystemList from './routes/system-list';
import SystemDetail from './routes/system-detail';
render((
<Router history={browserHistory}>
<Route path="/systems" component={SystemList}/>
<Route path="/systems/:systemId" component={SystemDetail}/>
</Router>
), document.getElementById('root')); |
ajax/libs/jquery/1.11.1-rc1/jquery.min.js | iwdmb/cdnjs | /*! jQuery v1.11.1-rc1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1-rc1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t="sizzle"+-new Date,u=a.document,v=0,w=0,x=fb(),y=fb(),z=fb(),A=function(a,b){return a===b&&(k=!0),0},B="undefined",C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=E.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")"+L+"*(?:([*^$|!~]?=)"+L+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+N+")|)|)"+L+"*\\]",P=":("+M+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+O.replace(3,8)+")*)|.*)\\)|)",Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(P),V=new RegExp("^"+N+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,ab=/'|\\/g,bb=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),cb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{H.apply(E=I.call(u.childNodes),u.childNodes),E[u.childNodes.length].nodeType}catch(db){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function eb(a,b,d,e){var f,g,i,j,k,n,q,r,v,w;if((b?b.ownerDocument||b:u)!==m&&l(b),b=b||m,d=d||[],!a||"string"!=typeof a)return d;if(1!==(j=b.nodeType)&&9!==j)return[];if(o&&!e){if(f=$.exec(a))if(i=f[1]){if(9===j){if(g=b.getElementById(i),!g||!g.parentNode)return d;if(g.id===i)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(i))&&s(b,g)&&g.id===i)return d.push(g),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((i=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(i)),d}if(c.qsa&&(!p||!p.test(a))){if(r=q=t,v=b,w=9===j&&a,1===j&&"object"!==b.nodeName.toLowerCase()){n=pb(a),(q=b.getAttribute("id"))?r=q.replace(ab,"\\$&"):b.setAttribute("id",r),r="[id='"+r+"'] ",k=n.length;while(k--)n[k]=r+qb(n[k]);v=_.test(a)&&nb(b.parentNode)||b,w=n.join(",")}if(w)try{return H.apply(d,v.querySelectorAll(w)),d}catch(x){}finally{q||b.removeAttribute("id")}}}return h(a.replace(Q,"$1"),b,d,e)}function fb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function gb(a){return a[t]=!0,a}function hb(a){var b=m.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ib(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function jb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function mb(a){return gb(function(b){return b=+b,gb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function nb(a){return a&&typeof a.getElementsByTagName!==B&&a}c=eb.support={},f=eb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},l=eb.setDocument=function(a){var b,e=a?a.ownerDocument||a:u,g=e.defaultView;return e!==m&&9===e.nodeType&&e.documentElement?(m=e,n=e.documentElement,o=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){l()},!1):g.attachEvent&&g.attachEvent("onunload",function(){l()})),c.attributes=hb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=hb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(e.getElementsByClassName)&&hb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=hb(function(a){return n.appendChild(a).id=t,!e.getElementsByName||!e.getElementsByName(t).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==B&&o){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(bb,cb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(bb,cb);return function(a){var c=typeof a.getAttributeNode!==B&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==B?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==B&&o?b.getElementsByClassName(a):void 0},q=[],p=[],(c.qsa=Z.test(e.querySelectorAll))&&(hb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&p.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||p.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll(":checked").length||p.push(":checked")}),hb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&p.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||p.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),p.push(",.*:")})),(c.matchesSelector=Z.test(r=n.webkitMatchesSelector||n.mozMatchesSelector||n.oMatchesSelector||n.msMatchesSelector))&&hb(function(a){c.disconnectedMatch=r.call(a,"div"),r.call(a,"[s!='']:x"),q.push("!=",P)}),p=p.length&&new RegExp(p.join("|")),q=q.length&&new RegExp(q.join("|")),b=Z.test(n.compareDocumentPosition),s=b||Z.test(n.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},A=b?function(a,b){if(a===b)return k=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===u&&s(u,a)?-1:b===e||b.ownerDocument===u&&s(u,b)?1:j?J.call(j,a)-J.call(j,b):0:4&d?-1:1)}:function(a,b){if(a===b)return k=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:j?J.call(j,a)-J.call(j,b):0;if(f===g)return jb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?jb(h[d],i[d]):h[d]===u?-1:i[d]===u?1:0},e):m},eb.matches=function(a,b){return eb(a,null,null,b)},eb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==m&&l(a),b=b.replace(T,"='$1']"),!(!c.matchesSelector||!o||q&&q.test(b)||p&&p.test(b)))try{var d=r.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return eb(b,m,null,[a]).length>0},eb.contains=function(a,b){return(a.ownerDocument||a)!==m&&l(a),s(a,b)},eb.attr=function(a,b){(a.ownerDocument||a)!==m&&l(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!o):void 0;return void 0!==f?f:c.attributes||!o?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},eb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},eb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(k=!c.detectDuplicates,j=!c.sortStable&&a.slice(0),a.sort(A),k){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return j=null,a},e=eb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=eb.selectors={cacheLength:50,createPseudo:gb,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(bb,cb),a[3]=(a[4]||a[5]||"").replace(bb,cb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||eb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&eb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return W.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&U.test(c)&&(b=pb(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(bb,cb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=x[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&x(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==B&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=eb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[t]||(q[t]={}),j=k[a]||[],n=j[0]===v&&j[1],m=j[0]===v&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[v,n,m];break}}else if(s&&(j=(b[t]||(b[t]={}))[a])&&j[0]===v)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[t]||(l[t]={}))[a]=[v,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||eb.error("unsupported pseudo: "+a);return e[t]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?gb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:gb(function(a){var b=[],c=[],d=g(a.replace(Q,"$1"));return d[t]?gb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:gb(function(a){return function(b){return eb(a,b).length>0}}),contains:gb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:gb(function(a){return V.test(a||"")||eb.error("unsupported lang: "+a),a=a.replace(bb,cb).toLowerCase(),function(b){var c;do if(c=o?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===n},focus:function(a){return a===m.activeElement&&(!m.hasFocus||m.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:mb(function(){return[0]}),last:mb(function(a,b){return[b-1]}),eq:mb(function(a,b,c){return[0>c?c+b:c]}),even:mb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:mb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:mb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:mb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=kb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=lb(b);function ob(){}ob.prototype=d.filters=d.pseudos,d.setFilters=new ob;function pb(a,b){var c,e,f,g,h,i,j,k=y[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=R.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?eb.error(a):y(a,i).slice(0)}function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=w++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[v,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[t]||(b[t]={}),(h=i[d])&&h[0]===v&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)eb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[t]&&(d=vb(d)),e&&!e[t]&&(e=vb(e,f)),gb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],j=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return J.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==i)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[t]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return vb(j>1&&sb(m),j>1&&qb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(Q,"$1"),c,e>j&&wb(a.slice(j,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,j,k){var l,n,o,p=0,q="0",r=f&&[],s=[],t=i,u=f||e&&d.find.TAG("*",k),w=v+=null==t?1:Math.random()||.1,x=u.length;for(k&&(i=g!==m&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){n=0;while(o=a[n++])if(o(l,g,h)){j.push(l);break}k&&(v=w)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(j));s=ub(s)}H.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&eb.uniqueSort(j)}return k&&(v=w,i=t),r};return c?gb(f):f}return g=eb.compile=function(a,b){var c,d=[],e=[],f=z[a+" "];if(!f){b||(b=pb(a)),c=b.length;while(c--)f=wb(b[c]),f[t]?d.push(f):e.push(f);f=z(a,xb(e,d)),f.selector=a}return f},h=eb.select=function(a,b,e,f){var h,i,j,k,l,m="function"==typeof a&&a,n=!f&&pb(a=m.selector||a);if(e=e||[],1===n.length){if(i=n[0]=n[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&o&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(bb,cb),b)||[])[0],!b)return e;m&&(b=b.parentNode),a=a.slice(i.shift().value.length)}h=W.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(bb,cb),_.test(i[0].type)&&nb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&qb(i),!a)return H.apply(e,f),e;break}}}return(m||g(a,n))(f,b,!o,e,_.test(a)&&nb(b.parentNode)||b),e},c.sortStable=t.split("").sort(A).join("")===t,c.detectDuplicates=!!k,l(),c.sortDetached=hb(function(a){return 1&a.compareDocumentPosition(m.createElement("div"))}),hb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ib("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&hb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ib("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),hb(function(a){return null==a.getAttribute("disabled")})||ib(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),eb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;
if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d]));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")
},cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l=this,n={},o=a.style,p=a.nodeType&&U(a),q=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=m.css(a,"display"),"inline"===("none"===j?Fb(a.nodeName):j)&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?o.zoom=1:o.display="inline-block")),c.overflow&&(o.overflow="hidden",k.shrinkWrapBlocks()||l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}n[d]=q&&q[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(n))"inline"===("none"===j?Fb(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=m._data(a,"fxshow",{}),f&&(q.hidden=!p),p?m(a).show():l.done(function(){m(a).hide()}),l.done(function(){var b;m._removeData(a,"fxshow");for(b in n)m.style(a,b,n[b])});for(d in n)g=hc(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
//# sourceMappingURL=jquery.min.map |
ajax/libs/forerunnerdb/1.3.365/fdb-all.min.js | dannyxx001/cdnjs | !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/Grid"),a("../lib/Rest"),a("../lib/Odm");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/CollectionGroup":6,"../lib/Document":10,"../lib/Grid":11,"../lib/Highchart":12,"../lib/Odm":27,"../lib/Overview":30,"../lib/Persist":32,"../lib/Rest":36,"../lib/View":40,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":7,"../lib/Shim.IE8":39}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){var b;this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0;for(b in a)a.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:a[b]})};d.addModule("ActiveBucket",e),d.mixin(e.prototype,"Mixin.Sorting"),d.synthesize(e.prototype,"primaryKey"),e.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},e.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},e.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Shared":38}],4:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a,b,c){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c,d){this._store=[],this._keys=[],void 0!==b&&this.index(b),void 0!==c&&this.compareFunc(c),void 0!==d&&this.hashFunc(d),void 0!==a&&this.data(a)},d.addModule("BinaryTree",f),d.mixin(f.prototype,"Mixin.ChainReactor"),d.mixin(f.prototype,"Mixin.Sorting"),d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"compareFunc"),d.synthesize(f.prototype,"hashFunc"),d.synthesize(f.prototype,"indexDir"),d.synthesize(f.prototype,"keys"),d.synthesize(f.prototype,"index",function(a){return void 0!==a&&this.keys(this.extractKeys(a)),this.$super.call(this,a)}),f.prototype.extractKeys=function(a){var b,c=[];for(b in a)a.hasOwnProperty(b)&&c.push({key:b,val:a[b]});return c},f.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},f.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},f.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),!0}return!1},f.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.val?e=this.sortAsc(a[d.key],b[d.key]):-1===d.val&&(e=this.sortDesc(a[d.key],b[d.key])),0!==e)return e;return e},f.prototype._hashFunc=function(a){return a[this._keys[0].key]},f.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this._data?(b=this._compareFunc(this._data,a),0===b?(this.push(a),this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):-1===b?(this._right?this._right.insert(a):this._right=new f(a,this._index,this._compareFunc,this._hashFunc),!0):1===b?(this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):!1):(this.data(a),!0)},f.prototype.lookup=function(a,b){var c=this._compareFunc(this._data,a);return b=b||[],0===c&&(this._left&&this._left.lookup(a,b),b.push(this._data),this._right&&this._right.lookup(a,b)),-1===c&&this._right&&this._right.lookup(a,b),1===c&&this._left&&this._left.lookup(a,b),b},f.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},f.prototype.findRange=function(a,b,c,d,e){e=e||[],this._left&&this._left.findRange(a,b,c,d,e);var f=this.sortAsc(this._data[b],c),g=this.sortAsc(this._data[b],d);if(!(0!==f&&1!==f||0!==g&&-1!==g))switch(a){case"hash":e.push(this._hash);break;case"data":e.push(this._data);break;default:e.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,e),e},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._index),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},d.finishModule("BinaryTree"),b.exports=f},{"./Path":31,"./Shared":38}],5:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this.subsetOf(this)},d.addModule("Collection",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),d.mixin(n.prototype,"Mixin.Updating"),d.mixin(n.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),d.synthesize(n.prototype,"metaData"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},n.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey!==a&&(this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex()),this):this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},n.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(n.prototype,"mongoEmulation"),n.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},n.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},n.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},n.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},n.prototype.update=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b),this.debug()&&console.log(this.logIdentifier()+" Updating some data");var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:d},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},n.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":var s=!0;b[p]>0?b.$max&&a[p]>=b.$max&&(s=!1):b[p]<0&&b.$min&&a[p]<=b.$min&&(s=!1),s&&(this._updateIncrement(a,p,b[p]),q=!0);break;case"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[p]}break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+p+")";var t,u,v,w,x=a[p],y=x.length,z=!0,A=d&&d.$addToSet;for(b[p].$key?(v=!1,w=new h(b[p].$key),u=w.value(b[p])[0],delete b[p].$key):A&&A.key?(v=!1,w=new h(A.key),u=w.value(b[p])[0]):(u=this.jStringify(b[p]),v=!0),t=0;y>t;t++)if(v){if(this.jStringify(x[t])===u){z=!1;break}}else if(u===w.value(x[t])[0]){z=!1;break}z&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+p+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],d,"",{})){var B=b.$index;if(void 0===B)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[p],j,B),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$clear":this._updateClear(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;case"$toggle":this._updateProperty(a,p,!a[p]),q=!0;break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);this.chainSend("remove",{query:a,dataSet:d},b),(!b||b&&!b.noEmit)&&this._onRemove(d),this._onChange(),this.deferEmit("change",{type:"remove",data:d})}return c&&c(!1,d),d},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){if(g.length)switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c);this.isProcessingQueue()||this.emit("queuesComplete")},n.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},n.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},n.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(a.length>h)return this._deferQueue.insert=g.concat(a),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},n.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this;if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a)},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return!1;e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n).subsetOf(this).primaryKey(this._primaryKey).setData(c)},d.synthesize(n.prototype,"subsetOf"),n.prototype.isSubsetOf=function(a){return this._subsetOf===a},n.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},n.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.apply(this,arguments)},n.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H=this._metrics.create("find"),I=this.primaryKey(),J=this,K=!0,L={},M=[],N=[],O=[],P={},Q={},R=function(c){return J._match(c,a,b,"and",P)};if(H.start(),a){if(H.time("analyseQuery"),c=this._analyseQuery(J.decouple(a),b,H),H.time("analyseQuery"),H.data("analysis",c),c.hasJoin&&c.queriesJoin){for(H.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],L[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];H.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(H.data("index.potential",c.indexMatch),H.data("index.used",c.indexMatch[0].index),H.time("indexLookup"),e=c.indexMatch[0].lookup||[],H.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(K=!1)):H.flag("usedIndex",!1),K&&(e&&e.length?(d=e.length,H.time("tableScan: "+d),e=e.filter(R)):(d=this._data.length,H.time("tableScan: "+d),e=this._data.filter(R)),H.time("tableScan: "+d)),b.$orderBy&&(H.time("sort"),e=this.sort(b.$orderBy,e),H.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(Q.page=b.$page,Q.pages=Math.ceil(e.length/b.$limit),Q.records=e.length,b.$page&&b.$limit>0&&(H.data("cursor",Q),e.splice(0,b.$page*b.$limit))),b.$skip&&(Q.skip=b.$skip,e.splice(0,b.$skip),H.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(Q.limit=b.$limit,e.length=b.$limit,H.data("limit",b.$limit)),b.$decouple&&(H.time("decouple"),e=this.decouple(e),H.time("decouple"),H.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(w=k,l=L[k]?L[k]:this._db.collection(k),m=b.$join[f][k],x=0;x<e.length;x++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$where":m[n].query&&(o=m[n].query),m[n].options&&(p=m[n].options);break;case"$as":w=m[n];break;case"$multi":q=m[n];break;case"$require":r=m[n];break;case"$prefix":v=m[n]}else o[n]=J._resolveDynamicQuery(m[n],e[x]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===w){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!';t=s[0],u=e[x];for(C in t)t.hasOwnProperty(C)&&void 0===u[v+C]&&(u[v+C]=t[C])}else e[x][w]=q===!1?s[0]:s;else M.push(e[x])}H.data("flag.join",!0)}if(M.length){for(H.time("removalQueue"),z=0;z<M.length;z++)y=e.indexOf(M[z]),y>-1&&e.splice(y,1);H.time("removalQueue")}if(b.$transform){for(H.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));H.time("transform"),H.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(H.time("transformOut"),e=this.transformOut(e),H.time("transformOut")),H.data("results",e.length)}else e=[];H.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?N.push(z):0===b[z]&&O.push(z));if(H.time("scanFields"),N.length||O.length){for(H.data("flag.limitFields",!0),H.data("limitFields.on",N),H.data("limitFields.off",O),H.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(N.length&&A!==I&&-1===N.indexOf(A)&&delete G[A],O.length&&O.indexOf(A)>-1&&delete G[A])}H.time("limitFields")}if(b.$elemMatch){H.data("flag.elemMatch",!0),H.time("projection-elemMatch");for(z in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length)for(B=0;B<E.length;B++)if(J._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}H.time("projection-elemMatch")}if(b.$elemsMatch){H.data("flag.elemsMatch",!0),H.time("projection-elemsMatch");for(z in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length){for(F=[],B=0;B<E.length;B++)J._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}H.time("projection-elemsMatch")}return H.stop(),e.__fdbOp=H,e.$cursor=Q,e},n.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g=this;if("string"==typeof a)return"$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b)[0]:new h(a).value(b)[0];c={};for(f in a)if(a.hasOwnProperty(f))switch(d=typeof a[f],e=a[f],d){case"string":"$$."===e.substr(0,3)?c[f]=new h(e.substr(3,e.length-3)).value(b)[0]:c[f]=e;break;case"object":c[f]=g._resolveDynamicQuery(e,b);break;default:c[f]=e}return c},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},n.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},n.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},n.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},n.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},n.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},n.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=String(c),e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},n.prototype._bucketSort=function(a,b){var c,d,e,f,g,h,i=a.shift(),j=[];if(a.length>0){for(b=this._sort(i,b),d=this.bucket(i.___fdbKey,b),e=d.order,g=d.buckets,h=0;h<e.length;h++)f=e[h],c=[].concat(a),j=j.concat(this._bucketSort(c,g[f]));return j}return this._sort(i,b)},n.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},n.prototype.bucket=function(a,b){var c,d,e,f=[],g={};for(c=0;c<b.length;c++)e=String(b[c][a]),d!==e&&(f.push(e),d=e),g[e]=g[e]||[],g[e].push(b[c]);return{buckets:g,order:f}},n.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),"$as"in b.$join[d][e]?r.push(b.$join[d][e].$as):r.push(e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},n.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?m.subDocs.push(g):m.subDocs=m.subDocs.concat(g),
m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.$stats?m:m.subDocs},n.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},n.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),n.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof n?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1&&a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log(this.logIdentifier()+" Creating collection "+b)}return this._collection[b]=this._collection[b]||new n(b,a).db(this),this._collection[b].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),this._collection[b]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=n},{"./Crc":8,"./IndexBinaryTree":13,"./IndexHashMap":14,"./KeyValueStore":15,"./Metrics":16,"./Overload":29,"./Path":31,"./ReactorIO":35,"./Shared":38}],6:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(){if(!this.isDropped()){var a,b,c;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(b=[].concat(this._collections),a=0;a<b.length;a++)this.removeCollection(b[a]);if(this._view&&this._view.length)for(c=[].concat(this._view),a=0;a<c.length;a++)this._removeView(c[a]);this.emit("drop",this)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?a instanceof h?a:(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":5,"./Shared":38}],7:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":9,"./Metrics.js":16,"./Overload":29,"./Shared":38}],8:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],9:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":16,"./Overload":29,"./Shared":38}],10:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared");var g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",g),d.mixin(g.prototype,"Mixin.Common"),d.mixin(g.prototype,"Mixin.Events"),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Constants"),d.mixin(g.prototype,"Mixin.Triggers"),d.mixin(g.prototype,"Mixin.Matching"),d.mixin(g.prototype,"Mixin.Updating"),d.mixin(g.prototype,"Mixin.Tags"),e=a("./Collection"),f=d.modules.Db,d.synthesize(g.prototype,"state"),d.synthesize(g.prototype,"db"),d.synthesize(g.prototype,"name"),g.prototype.setData=function(a,b){var c,d;if(a){if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){d={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(d[c]=1);a.$unset=d,this.updateObject(this._data,a,{})}else this._data=a;this.deferEmit("change",{type:"setData",data:this.decouple(this._data)})}return this},g.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},g.prototype.update=function(a,b,c){var d=this.updateObject(this._data,b,a,c);d&&this.deferEmit("change",{type:"update",data:this.decouple(this._data)})},g.prototype.updateObject=e.prototype.updateObject,g.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},g.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log(this.logIdentifier()+' Setting data-bound document property "'+b+'"')):(a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"'))},g.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},g.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log(this.logIdentifier()+' Moving data-bound document array index from "'+b+'" to "'+c+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"'))},g.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},g.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},g.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},g.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},g.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},g.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},g.prototype.drop=function(){return this.isDropped()?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),!0):!1},f.prototype.document=function(a){if(a){if(a instanceof g){if("droppped"!==a.state())return a;a=a.name()}return this._document=this._document||{},this._document[a]=this._document[a]||new g(a).db(this),this._document[a]}return this._document},f.prototype.documents=function(){var a,b,c=[];for(b in this._document)this._document.hasOwnProperty(b)&&(a=this._document[b],c.push({name:b,linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Document"),b.exports=g},{"./Collection":5,"./Shared":38}],11:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this.refresh()),this},d.synthesize(l.prototype,"db",function(a){return a&&this.debug(a.debug()),this.$super.apply(this,arguments)}),l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(){return this.isDropped()?!0:this._from?(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),delete this._selector,delete this._template,delete this._from,delete this._db,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget),e=c.attr("data-grid-sort")||"",f=-1===parseInt(c.attr("data-grid-dir")||"-1",10)?1:-1,g=e.split(","),h={};for(window.jQuery(this._selector).find("[data-grid-dir]").removeAttr("data-grid-dir"),c.attr("data-grid-dir",f),b=0;b<g.length;b++)h[g]=f;d.mixin(h,this._options.$orderBy),this._from.orderBy(h),this.emit("sort",h)},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._from.query&&b.off("click","[data-grid-filter]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d={};b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j=e.attr("data-grid-filter"),k=e.attr("data-grid-vartype"),l={},m=e.html(),n=a._db.view("tmpGridFilter_"+a._id+"_"+j);l[j]=1,i={$distinct:l},n.query(i).orderBy(l).from(a._from._from),h=['<div class="dropdown" id="'+a._id+"_"+j+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+j+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',m+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+j+'_dropdownMenu"></ul>'),f.append(g),e.html(f),n.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked> All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+j+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox"> {^{:'+j+"}}","</a>","</li>","{{/for}}"].join("")},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+j+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=n.query(),d=b.val();d?c[j]=new RegExp(d,"gi"):delete c[j],n.query(c)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=n.query();delete b[j],n.query(b)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),l=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(l.prop("checked",l.prop("checked")),e=l.is(":checked")):(l.prop("checked",!l.prop("checked")),e=l.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[j],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),k){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[j]=d[j]||{$in:[]},f=d[j].$in,h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[j]}a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(void 0!==a){if(void 0!==b){if(this._db._grid[a])throw this.logIdentifier()+" Cannot create a grid because a grid with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}return this._db._grid[a]}return this._db._grid}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw this.logIdentifier()+" Cannot remove grid because a grid with this name does not exist: "+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log(this.logIdentifier()+' Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b,c=[];for(b in this._grid)this._grid.hasOwnProperty(b)&&(a=this._grid[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Grid"),b.exports=l},{"./Collection":5,"./CollectionGroup":6,"./ReactorIO":35,"./Shared":38,"./View":40}],12:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw this.classIdentifier()+' "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw this.classIdentifier()+' "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d){var e,f,g,h,i,j,k=this._collection.distinct(a),l=[],m={categories:[]};for(i=0;i<k.length;i++){for(e=k[i],f={},f[a]=e,h=[],g=this._collection.find(f,{orderBy:d}),j=0;j<g.length;j++)m.categories.push(g[j][b]),h.push(g[j][c]);l.push({name:e,data:h})}return{xAxis:m,series:l}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a,arguments)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy);for(a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(){return this.isDropped()?!0:(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),!0)},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,
e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":29,"./Shared":38}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=new f,h=function(){};g.inOrder("hash");var i=function(){this.init.apply(this,arguments)};i.prototype.init=function(a,b,c){this._btree=new(h.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexBinaryTree",i),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Sorting"),i.prototype.id=function(){return this._id},i.prototype.state=function(){return this._state},i.prototype.size=function(){return this._size},d.synthesize(i.prototype,"data"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"collection"),d.synthesize(i.prototype,"type"),d.synthesize(i.prototype,"unique"),i.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},i.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree=new(h.create(2,this.sortAsc)),this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},i.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},i.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},i.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},i.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},i.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},i.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},i.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},i.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},i.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=i},{"./BinaryTree":4,"./Path":31,"./Shared":38}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":31,"./Shared":38}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":38}],16:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":28,"./Shared":38}],17:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],19:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state}},b.exports=d},{"./Overload":29,"./Serialiser":37}],20:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],21:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":29}],22:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){for(k in b)if(b.hasOwnProperty(k)){if(f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++){if(i[h]instanceof RegExp&&i[h].test(b))return!0;if(i[h]===b)return!0}return!1}throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(l[k]===b)return!1;return!0}throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0}return-1}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],24:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(c)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d=this.tagLookup(a);if(d.length)for(c=0;c<d.length;c++)d[c].drop(b);return!0}},b.exports=d},{}],25:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":29}],26:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],27:[function(a,b,c){"use strict";var d,e;d=a("./Shared");var f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b){var c=this;c.name(b),c._collectionDroppedWrap=function(){c._collectionDropped.apply(c,arguments)},c.from(a)},d.addModule("Odm",f),d.mixin(f.prototype,"Mixin.Common"),d.mixin(f.prototype,"Mixin.ChainReactor"),d.mixin(f.prototype,"Mixin.Constants"),d.mixin(f.prototype,"Mixin.Events"),e=a("./Collection"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"state"),d.synthesize(f.prototype,"parent"),d.synthesize(f.prototype,"query"),d.synthesize(f.prototype,"from",function(a){return void 0!==a&&(a.chain(this),a.on("drop",this._collectionDroppedWrap)),this.$super(a)}),f.prototype._collectionDropped=function(a){this.drop()},f.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":}},f.prototype.drop=function(){return this.isDropped()||(this.state("dropped"),this.emit("drop",this),this._from&&delete this._from._odm,delete this._name),!0},f.prototype.$=function(a,b){var c,d,g,h;return a===this._from.primaryKey()?(d={},d[a]=b,c=this._from.find(d,{$decouple:!1}),g=new e,g.setData(c,{$decouple:!1}),g._linked=this._from._linked):(g=new e,c=this._from.find({},{$decouple:!1}),c[0]&&c[0][a]&&(g.setData(c[0][a],{$decouple:!1}),b&&(c=g.find(b,{$decouple:!1}),g.setData(c,{$decouple:!1}))),g._linked=this._from._linked),h=new f(g),h.parent(this),h.query(b),h},f.prototype.prop=function(a,b){var c;if(void 0!==a){if(void 0!==b)return c={},c[a]=b,this._from.update({},c);if(this._from._data[0])return this._from._data[0][a]}},e.prototype.odm=function(a){return this._odm||(this._odm=new f(this,a)),this._odm},d.finishModule("Odm"),b.exports=f},{"./Collection":5,"./Shared":38}],28:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":31,"./Shared":38}],29:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],30:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._sources=[],this._sourceDroppedWrap=function(){b._sourceDropped.apply(b,arguments)}},d.addModule("Overview",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Events"),d.mixin(h.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._sources},h.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._sources.length;)this._removeSource(this._sources[0]);return this._addSource(a),this},h.prototype._addSource=function(a){return a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),-1===this._sources.indexOf(a)&&(this._sources.push(a),a.chain(this),a.on("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._removeSource=function(a){a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking'));var b=this._sources.indexOf(a);return b>-1&&(this._sources.splice(a,1),
a.unChain(this),a.off("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._sourceDropped=function(a){a&&this._removeSource(a)},h.prototype._refresh=function(){if(!this.isDropped()){if(this._sources&&this._sources[0]){this._collData.primaryKey(this._sources[0].primaryKey());var a,b=[];for(a=0;a<this._sources.length;a++)b=b.concat(this._sources[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh()}},h.prototype.data=function(){return this._data},h.prototype.drop=function(){if(!this.isDropped()){for(this._state="dropped",delete this._data,delete this._collData;this._sources.length;)this._removeSource(this._sources[0]);delete this._sources,this._db&&this._name&&delete this._db._overview[this._name],delete this._name,this.emit("drop",this)}return!0},e.prototype.overview=function(a){return a?a instanceof h?a:(this._overview=this._overview||{},this._overview[a]=this._overview[a]||new h(a).db(this),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b,c=[];for(b in this._overview)this._overview.hasOwnProperty(b)&&(a=this._overview[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Overview"),b.exports=h},{"./Collection":5,"./Document":10,"./Shared":38}],31:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?this._parseArr(a[e],f,c,d):c.push(f));return c},e.prototype.value=function(a,b){if(void 0!==a&&"object"==typeof a){var c,d,e,f,g,h,i,j=[];for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,h=0;e>h;h++){if(f=f[d[h]],g instanceof Array){for(i=0;i<g.length;i++)j=j.concat(this.value(g,i+"."+d[h]));return j}if(!f||"object"!=typeof f)break;g=f}return[f]}return[]},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":38}],32:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length):b.foundData=!1,c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length):b.foundData=!1,c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"::"+this._name),this._db.persist.drop(this._db._name+"::"+this._name+"::metaData"))}f.apply(this)}},"boolean, function":function(a,b){var c=this;this.isDropped()||(a&&(this._name?this._db?this._db.persist.drop(this._db._name+"::"+this._name,function(){c._db.persist.drop(c._db._name+"::"+c._name+"::metaData",b)}):b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!"):b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")),f.apply(this,b))}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"::"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"::"+c._name+"::metaData",c.metaData(),function(b,c,d){a&&a(b,c,e,d)})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"::"+b._name,function(c,d,e){c?a&&a(c):(d&&b.setData(d),b._db.persist.load(b._db._name+"::"+b._name+"::metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)}))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].load(b)},d.prototype.save=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].save(b)},m.finishModule("Persist"),b.exports=k},{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":33,"./PersistCrypto":34,"./Shared":38,async:41,localforage:83}],33:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":38,pako:85}],34:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":38,"crypto-js":50}],35:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":38}],36:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k=a("./Shared"),l=a("rest"),m=a("rest/interceptor/mime"),n=function(){this.init.apply(this,arguments)};n.prototype.init=function(a){this._endPoint="",this._client=l.wrap(m)},n.prototype._params=function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(encodeURIComponent(c)+"="+encodeURIComponent(a[c]));return b.join("&")},n.prototype.get=function(a,b,c){var d,e=this;a=void 0!==a?a:"",this._client({method:"get",path:this.endPoint()+a,params:b}).then(function(a){a.entity&&a.entity.error?c&&c(a.entity.error,a.entity,a):(d=e.collection(),d&&d.upsert(a.entity),c&&c(!1,a.entity,a))},function(a){c&&c(!0,a.entity,a)})},n.prototype.post=function(a,b,c){this._client({method:"post",path:this.endPoint()+a,entity:b,headers:{"Content-Type":"application/json"}}).then(function(a){a.entity&&a.entity.error?c&&c(a.entity.error,a.entity,a):c&&c(!1,a.entity,a)},function(a){c&&c(!0,a)})},k.synthesize(n.prototype,"sessionData"),k.synthesize(n.prototype,"endPoint"),k.synthesize(n.prototype,"collection"),k.addModule("Rest",n),k.mixin(n.prototype,"Mixin.ChainReactor"),d=k.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=k.overload,e.prototype.init=function(){this.rest=new n,this.rest.collection(this),h.apply(this,arguments)},d.prototype.init=function(){this.rest=new n,i.apply(this,arguments)},k.finishModule("Rest"),b.exports=n},{"./Collection":5,"./CollectionGroup":6,"./Shared":38,rest:102,"rest/interceptor/mime":107}],37:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],38:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.365",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":17,"./Mixin.ChainReactor":18,"./Mixin.Common":19,"./Mixin.Constants":20,"./Mixin.Events":21,"./Mixin.Matching":22,"./Mixin.Sorting":23,"./Mixin.Tags":24,"./Mixin.Triggers":25,"./Mixin.Updating":26,"./Overload":29}],39:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],40:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f(this.name()+"_internalPrivate")},d.addModule("View",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),d.synthesize(l.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.find=function(a,b){return this.publicData().find(a,b)},l.prototype.findById=function(a,b){return this.publicData().findById(a,b)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a){var b=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var c,d,e,f,g,h,i;if(b&&!b.isDropped()&&b._querySettings.query){if("insert"===a.type){if(c=a.data,c instanceof Array)for(f=[],i=0;i<c.length;i++)b._privateData._match(c[i],b._querySettings.query,b._querySettings.options,"and",{})&&(f.push(c[i]),g=!0);else b._privateData._match(c,b._querySettings.query,b._querySettings.options,"and",{})&&(f=c,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=b._privateData.diff(b._from.subset(b._querySettings.query,b._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=b._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=b._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var c=a.find(this._querySettings.query,this._querySettings.options);return this._transformPrimaryKey(a.primaryKey()),this._transformSetData(c),this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(c),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},l.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i,j,k;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data"),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._privateData.name()+'"');var l=this._from.find(this._querySettings.query,this._querySettings.options);this._transformSetData(l),this._privateData.setData(l);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)i=f[d],this._activeBucket.remove(i),j=this._privateData._data.indexOf(i),e=this._activeBucket.insert(i),j!==e&&this._privateData._updateSpliceMove(this._privateData._data,j,e);if(this._transformEnabled&&this._transformIn)for(g=this._publicData.primaryKey(),k=0;k<f.length;k++)h={},i=f[k],h[g]=i[g],this._transformUpdate(h,i);break;case"remove":this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._privateData.name()+'"'),this._transformRemove(a.data.query,a.options),this._privateData.remove(a.data.query,a.options)}},l.prototype.on=function(){return this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){return this._privateData.emit.apply(this._privateData,arguments)},l.prototype.distinct=function(a,b,c){return this._privateData.distinct.apply(this._privateData,arguments)},l.prototype.primaryKey=function(){return this._privateData.primaryKey()},l.prototype.drop=function(){return this.isDropped()?!0:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._publicData&&this._publicData!==this._privateData&&this._publicData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},d.synthesize(l.prototype,"db",function(a){return a&&(this.privateData().db(a),this.publicData().db(a),this.debug(a.debug()),this.privateData().debug(a.debug()),this.publicData().debug(a.debug())),this.$super.apply(this,arguments)}),l.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},l.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},l.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()}},l.prototype.query=function(a,b){return void 0!==a?(this._querySettings.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._querySettings.query},l.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},l.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},l.prototype.pageFirst=function(){return this.page(0)},l.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},l.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},l.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},l.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a,b=this.publicData();this._privateData.remove(),b.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this.publicData()?this.publicData().count.apply(this.publicData(),arguments):0},l.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},l.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this._transformPrimaryKey(this.privateData().primaryKey()),this._transformSetData(this.privateData().find()),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},l.prototype._transformSetData=function(a){this._transformEnabled&&(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._publicData.setData(a))},l.prototype._transformInsert=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.insert(a,b)},l.prototype._transformUpdate=function(a,b,c){this._transformEnabled&&this._publicData&&this._publicData.update(a,b,c)},l.prototype._transformRemove=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.remove(a,b)},l.prototype._transformPrimaryKey=function(a){this._transformEnabled&&this._publicData&&this._publicData.primaryKey(a)},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){return a instanceof l?a:(this._view[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=this._view[a]||new l(a).db(this),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=l},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./ReactorIO":35,"./Shared":38}],41:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null;
})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){if(!j.paused&&g<j.concurrency&&j.tasks.length)for(;g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this;null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null)},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){q.unshift(a)}function f(a){var b=p(q,a);b>=0&&q.splice(b,1)}function g(){j--,k(q.slice(0),function(a){a()})}c||(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(s,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](q,l))}for(var j,k=N(a[d])?a[d]:[a[d]],q=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,c(a,e)}else l[d]=b,K.setImmediate(g)}),s=k.slice(0,k.length-1),t=s.length;t--;){if(!(j=a[s[t]]))throw new Error("Has inexistant dependency");if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](q,l)):e(i)})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c(null)});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={};b=b||e;var f=r(function(e){var f=e.pop(),g=b.apply(null,e);g in c?K.setImmediate(function(){f.apply(null,c[g])}):g in d?d[g].push(f):(d[g]=[f],a.apply(null,e.concat([r(function(a){c[g]=a;var b=d[g];delete d[g];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return f.memo=c,f.unmemoized=a,f},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:76}],42:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":44}],44:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],45:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2;g[h>>>2]|=(j|k)<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":44}],46:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":44}],47:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":44,"./hmac":49,"./sha1":68}],48:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":43,"./core":44}],49:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":44}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],51:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":44}],52:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":44}],53:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);
b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":43,"./core":44}],54:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":43,"./core":44}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":43,"./core":44}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":43,"./core":44}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":43,"./core":44}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":43,"./core":44}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":43,"./core":44}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":43,"./core":44}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":43,"./core":44}],62:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":43,"./core":44}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":44,"./hmac":49,"./sha1":68}],64:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":44}],68:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":44}],69:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":44,"./sha256":70}],70:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":44}],71:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":44,"./x64-core":75}],72:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":44,"./sha512":73,"./x64-core":75}],73:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":44,"./x64-core":75}],74:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,
100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":44}],76:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],77:[function(a,b,c){"use strict";function d(a){function b(a){return null===j?void l.push(a):void g(function(){var b=j?a.onFulfilled:a.onRejected;if(null===b)return void(j?a.resolve:a.reject)(k);var c;try{c=b(k)}catch(d){return void a.reject(d)}a.resolve(c)})}function c(a){try{if(a===m)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var b=a.then;if("function"==typeof b)return void f(b.bind(a),c,h)}j=!0,k=a,i()}catch(d){h(d)}}function h(a){j=!1,k=a,i()}function i(){for(var a=0,c=l.length;c>a;a++)b(l[a]);l=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");var j=null,k=null,l=[],m=this;this.then=function(a,c){return new d(function(d,f){b(new e(a,c,d,f))})},f(a,c,h)}function e(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function f(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var g=a("asap");b.exports=d},{asap:79}],78:[function(a,b,c){"use strict";function d(a){this.then=function(b){return"function"!=typeof b?this:new e(function(c,d){f(function(){try{c(b(a))}catch(e){d(e)}})})}}var e=a("./core.js"),f=a("asap");b.exports=e,d.prototype=Object.create(e.prototype);var g=new d(!0),h=new d(!1),i=new d(null),j=new d(void 0),k=new d(0),l=new d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return i;if(void 0===a)return j;if(a===!0)return g;if(a===!1)return h;if(0===a)return k;if(""===a)return l;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(c){return new e(function(a,b){b(c)})}return new d(a)},e.from=e.cast=function(a){var b=new Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");return b.name="Warning",console.warn(b.stack),e.resolve(a)},e.denodeify=function(a,b){return b=b||1/0,function(){var c=this,d=Array.prototype.slice.call(arguments);return new e(function(e,f){for(;d.length&&d.length>b;)d.pop();d.push(function(a,b){a?f(a):e(b)}),a.apply(c,d)})}},e.nodeify=function(a){return function(){var b=Array.prototype.slice.call(arguments),c="function"==typeof b[b.length-1]?b.pop():null;try{return a.apply(this,arguments).nodeify(c)}catch(d){if(null===c||"undefined"==typeof c)return new e(function(a,b){b(d)});f(function(){c(d)})}}},e.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),b=Array.prototype.slice.call(a?arguments[0]:arguments);if(!a){var c=new Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated");c.name="Warning",console.warn(c.stack)}return new e(function(a,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}b[f]=g,0===--e&&a(b)}catch(i){c(i)}}if(0===b.length)return a([]);for(var e=b.length,f=0;f<b.length;f++)d(f,b[f])})},e.reject=function(a){return new e(function(b,c){c(a)})},e.race=function(a){return new e(function(b,c){a.forEach(function(a){e.resolve(a).then(b,c)})})},e.prototype.done=function(a,b){var c=arguments.length?this.then.apply(this,arguments):this;c.then(null,function(a){f(function(){throw a})})},e.prototype.nodeify=function(a){return"function"!=typeof a?this:void this.then(function(b){f(function(){a(null,b)})},function(b){f(function(){a(b)})})},e.prototype["catch"]=function(a){return this.then(null,a)}},{"./core.js":77,asap:79}],79:[function(a,b,c){(function(a){function c(){for(;e.next;){e=e.next;var a=e.task;e.task=void 0;var b=e.domain;b&&(e.domain=void 0,b.enter());try{a()}catch(d){if(i)throw b&&b.exit(),setTimeout(c,0),b&&b.enter(),d;setTimeout(function(){throw d},0)}b&&b.exit()}g=!1}function d(b){f=f.next={task:b,domain:i&&a.domain,next:null},g||(g=!0,h())}var e={task:void 0,next:null},f=e,g=!1,h=void 0,i=!1;if("undefined"!=typeof a&&a.nextTick)i=!0,h=function(){a.nextTick(c)};else if("function"==typeof setImmediate)h="undefined"!=typeof window?setImmediate.bind(window,c):function(){setImmediate(c)};else if("undefined"!=typeof MessageChannel){var j=new MessageChannel;j.port1.onmessage=c,h=function(){j.port2.postMessage(0)}}else h=function(){setTimeout(c,0)};b.exports=d}).call(this,a("_process"))},{_process:76}],80:[function(a,b,c){(function(){"use strict";function c(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=window.BlobBuilder||window.MSBlobBuilder||window.MozBlobBuilder||window.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function d(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function e(a){return new u(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function f(a){return new u(function(b,d){var f=c([""],{type:"image/png"}),g=a.transaction([x],"readwrite");g.objectStore(x).put(f,"key"),g.oncomplete=function(){var c=a.transaction([x],"readwrite"),f=c.objectStore(x).get("key");f.onerror=d,f.onsuccess=function(a){var c=a.target.result,d=URL.createObjectURL(c);e(d).then(function(a){b(!(!a||"image/png"!==a.type))},function(){b(!1)}).then(function(){URL.revokeObjectURL(d)})}}})["catch"](function(){return!1})}function g(a){return"boolean"==typeof w?u.resolve(w):f(a).then(function(a){return w=a})}function h(a){return new u(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function i(a){var b=d(atob(a.data));return c([b],{type:a.type})}function j(a){return a&&a.__local_forage_encoded_blob}function k(a){var b=this,c={db:null};if(a)for(var d in a)c[d]=a[d];return new u(function(a,d){var e=v.open(c.name,c.version);e.onerror=function(){d(e.error)},e.onupgradeneeded=function(a){e.result.createObjectStore(c.storeName),a.oldVersion<=1&&e.result.createObjectStore(x)},e.onsuccess=function(){c.db=e.result,b._dbInfo=c,a()}})}function l(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),j(a)&&(a=i(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return t(d,b),d}function m(a,b){var c=this,d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;j(d)&&(d=i(d));var e=a(d,c.key,h++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return t(d,b),d}function n(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new u(function(c,e){var f;d.ready().then(function(){return f=d._dbInfo,g(f.db)}).then(function(a){return!a&&b instanceof Blob?h(b):b}).then(function(b){var d=f.db.transaction(f.storeName,"readwrite"),g=d.objectStore(f.storeName);null===b&&(b=void 0);var h=g.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=h.error?h.error:h.transaction.error;e(a)}})["catch"](e)});return t(e,c),e}function o(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return t(d,b),d}function p(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return t(c,a),c}function q(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return t(c,a),c}function r(a,b){var c=this,d=new u(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return t(d,b),d}function s(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return t(c,a),c}function t(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var u="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,v=v||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(v){var w,x="local-forage-detect-blob-support",y={_driver:"asyncStorage",_initStorage:k,iterate:m,getItem:l,setItem:n,removeItem:o,clear:p,length:q,key:r,keys:s};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=y:"function"==typeof define&&define.amd?define("asyncStorage",function(){return y}):this.asyncStorage=y}}).call(window)},{promise:78}],81:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={};if(b)for(var e in b)d[e]=b[e];d.keyPrefix=d.name+"/",c._dbInfo=d;var f=new m(function(b){s===r.DEFINE?a(["localforageSerializer"],b):b(s===r.EXPORT?a("./../utils/serializer"):n.localforageSerializer)});return f.then(function(a){return o=a,m.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=p.length-1;c>=0;c--){var d=p.key(c);0===d.indexOf(a)&&p.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=p.getItem(b.keyPrefix+a);return d&&(d=o.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo.keyPrefix,d=b.length,e=p.length,f=0;e>f;f++){var g=p.key(f),h=p.getItem(g);if(h&&(h=o.deserialize(h)),h=a(h,g.substring(d),f+1),void 0!==h)return h}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=p.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=p.length,d=[],e=0;c>e;e++)0===p.key(e).indexOf(a.keyPrefix)&&d.push(p.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;p.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new m(function(e,f){o.serialize(b,function(b,g){if(g)f(g);else try{var h=d._dbInfo;p.setItem(h.keyPrefix+a,b),e(c)}catch(i){("QuotaExceededError"===i.name||"NS_ERROR_DOM_QUOTA_REACHED"===i.name)&&f(i),f(i)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(q){return}var r={DEFINE:1,EXPORT:2,WINDOW:3},s=r.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?s=r.EXPORT:"function"==typeof define&&define.amd&&(s=r.DEFINE);var t={_driver:"localStorageWrapper",_initStorage:c,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};s===r.EXPORT?b.exports=t:s===r.DEFINE?define("localStorageWrapper",function(){return t}):this.localStorageWrapper=t}).call(window)},{"./../utils/serializer":84,promise:78}],82:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={db:null};if(b)for(var e in b)d[e]="string"!=typeof b[e]?b[e].toString():b[e];var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)}),g=new m(function(a,e){try{d.db=p(d.name,String(d.version),d.description,d.size)}catch(f){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(b)}).then(a)["catch"](e)}d.db.transaction(function(b){b.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=d,a()},function(a,b){e(b)})})});return f.then(function(a){return o=a,g})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=o.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var e=d.rows,f=e.length,g=0;f>g;g++){var h=e.item(g),i=h.value;if(i&&(i=o.deserialize(i)),i=a(i,h.key,g+1),void 0!==i)return void b(i)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b;o.serialize(b,function(b,g){if(g)e(g);else{var h=d._dbInfo;h.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})}})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=this.openDatabase;if(p){var q={DEFINE:1,EXPORT:2,WINDOW:3},r=q.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?r=q.EXPORT:"function"==typeof define&&define.amd&&(r=q.DEFINE);var s={_driver:"webSQLStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};r===q.DEFINE?define("webSQLStorage",function(){return s}):r===q.EXPORT?b.exports=s:this.webSQLStorage=s}}).call(window)},{"./../utils/serializer":84,promise:78}],83:[function(a,b,c){(function(){"use strict";function c(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function d(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(p(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function e(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b]===a)return!0;return!1}function f(a){this._config=d({},m,a),this._driverSet=null,this._ready=!1,this._dbInfo=null;for(var b=0;b<k.length;b++)c(this,k[b]);this.setDriver(this._config.driver)}var g="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,h={},i={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},j=[i.INDEXEDDB,i.WEBSQL,i.LOCALSTORAGE],k=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],l={DEFINE:1,EXPORT:2,WINDOW:3},m={description:"",driver:j.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},n=l.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?n=l.EXPORT:"function"==typeof define&&define.amd&&(n=l.DEFINE);var o=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[i.WEBSQL]=!!a.openDatabase,c[i.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[i.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),p=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},q=this;f.prototype.INDEXEDDB=i.INDEXEDDB,f.prototype.LOCALSTORAGE=i.LOCALSTORAGE,f.prototype.WEBSQL=i.WEBSQL,f.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},f.prototype.defineDriver=function(a,b,c){var d=new g(function(b,c){try{var d=a._driver,f=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),i=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(f);if(e(a._driver))return void c(i);for(var j=k.concat("_initStorage"),l=0;l<j.length;l++){var m=j[l];if(!m||!a[m]||"function"!=typeof a[m])return void c(f)}var n=g.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():g.resolve(!!a._support)),n.then(function(c){o[d]=c,h[d]=a,b()},c)}catch(p){c(p)}});return d.then(b,c),d},f.prototype.driver=function(){return this._driver||null},f.prototype.ready=function(a){var b=this,c=new g(function(a,c){b._driverSet.then(function(){null===b._ready&&(b._ready=b._initStorage(b._config)),b._ready.then(a,c)})["catch"](c)});return c.then(a,a),c},f.prototype.setDriver=function(b,c,d){function f(){i._config.driver=i.driver()}var i=this;return"string"==typeof b&&(b=[b]),this._driverSet=new g(function(c,d){var f=i._getFirstSupportedDriver(b),j=new Error("No available storage method found.");if(!f)return i._driverSet=g.reject(j),void d(j);if(i._dbInfo=null,i._ready=null,e(f)){var k=new g(function(b){if(n===l.DEFINE)a([f],b);else if(n===l.EXPORT)switch(f){case i.INDEXEDDB:b(a("./drivers/indexeddb"));break;case i.LOCALSTORAGE:b(a("./drivers/localstorage"));break;case i.WEBSQL:b(a("./drivers/websql"))}else b(q[f])});k.then(function(a){i._extend(a),c()})}else h[f]?(i._extend(h[f]),c()):(i._driverSet=g.reject(j),d(j))}),this._driverSet.then(f,f),this._driverSet.then(c,d),this._driverSet},f.prototype.supports=function(a){return!!o[a]},f.prototype._extend=function(a){d(this,a)},f.prototype._getFirstSupportedDriver=function(a){if(a&&p(a))for(var b=0;b<a.length;b++){var c=a[b];if(this.supports(c))return c}return null},f.prototype.createInstance=function(a){return new f(a)};var r=new f;n===l.DEFINE?define("localforage",function(){return r}):n===l.EXPORT?b.exports=r:this.localforage=r}).call(window)},{"./drivers/indexeddb":80,"./drivers/localstorage":81,"./drivers/websql":82,promise:78}],84:[function(a,b,c){(function(){"use strict";function c(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=y.BlobBuilder||y.MSBlobBuilder||y.MozBlobBuilder||y.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function d(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=k;a instanceof ArrayBuffer?(d=a,e+=m):(d=a.buffer,"[object Int8Array]"===c?e+=o:"[object Uint8Array]"===c?e+=p:"[object Uint8ClampedArray]"===c?e+=q:"[object Int16Array]"===c?e+=r:"[object Uint16Array]"===c?e+=t:"[object Int32Array]"===c?e+=s:"[object Uint32Array]"===c?e+=u:"[object Float32Array]"===c?e+=v:"[object Float64Array]"===c?e+=w:b(new Error("Failed to get type for BinaryArray"))),b(e+g(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=i+a.type+"~"+g(this.result);b(k+n+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(h){console.error("Couldn't convert value into a JSON string: ",a),b(null,h)}}function e(a){if(a.substring(0,l)!==k)return JSON.parse(a);var b,d=a.substring(x),e=a.substring(l,x);if(e===n&&j.test(d)){var g=d.match(j);b=g[1],d=d.substring(g[0].length)}var h=f(d);switch(e){case m:return h;case n:return c([h],{type:b});case o:return new Int8Array(h);case p:return new Uint8Array(h);case q:return new Uint8ClampedArray(h);case r:return new Int16Array(h);case t:return new Uint16Array(h);case s:return new Int32Array(h);case u:return new Uint32Array(h);case v:return new Float32Array(h);case w:return new Float64Array(h);default:throw new Error("Unkown type: "+e)}}function f(a){var b,c,d,e,f,g=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(g--,"="===a[a.length-2]&&g--);var k=new ArrayBuffer(g),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=h.indexOf(a[b]),d=h.indexOf(a[b+1]),e=h.indexOf(a[b+2]),f=h.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function g(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=h[c[b]>>2],d+=h[(3&c[b])<<4|c[b+1]>>4],d+=h[(15&c[b+1])<<2|c[b+2]>>6],d+=h[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i="~~local_forage_type~",j=/^~~local_forage_type~([^~]+)~/,k="__lfsc__:",l=k.length,m="arbf",n="blob",o="si08",p="ui08",q="uic8",r="si16",s="si32",t="ur16",u="ui32",v="fl32",w="fl64",x=l+m.length,y=this,z={serialize:d,deserialize:e,stringToBuffer:f,bufferToString:g};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=z:"function"==typeof define&&define.amd?define("localforageSerializer",function(){return z}):this.localforageSerializer=z}).call(window)},{}],85:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":86,"./lib/inflate":87,"./lib/utils/common":88,"./lib/zlib/constants":91}],86:[function(a,b,c){"use strict";function d(a,b){var c=new u(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}function f(a,b){return b=b||{},b.gzip=!0,d(a,b)}var g=a("./zlib/deflate.js"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=Object.prototype.toString,m=0,n=4,o=0,p=1,q=2,r=-1,s=0,t=8,u=function(a){this.options=h.assign({level:r,method:t,chunkSize:16384,windowBits:15,memLevel:8,strategy:s,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==o)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header)};u.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?n:m,"string"==typeof a?e.input=i.string2buf(a):"[object ArrayBuffer]"===l.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==p&&c!==o)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&(d===n||d===q))&&("string"===this.options.to?this.onData(i.buf2binstring(h.shrinkBuf(e.output,e.next_out))):this.onData(h.shrinkBuf(e.output,e.next_out)));
}while((e.avail_in>0||0===e.avail_out)&&c!==p);return d===n?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===o):d===q?(this.onEnd(o),e.avail_out=0,!0):!0},u.prototype.onData=function(a){this.chunks.push(a)},u.prototype.onEnd=function(a){a===o&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=u,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":88,"./utils/strings":89,"./zlib/deflate.js":93,"./zlib/messages":98,"./zlib/zstream":100}],87:[function(a,b,c){"use strict";function d(a,b){var c=new n(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=Object.prototype.toString,n=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};n.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,n=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,"string"==typeof a?l.input=h.binstring2buf(a):"[object ArrayBuffer]"===m.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(n),l.next_out=0,l.avail_out=n),c=f.inflate(l,i.Z_NO_FLUSH),c===i.Z_BUF_ERROR&&o===!0&&(c=i.Z_OK,o=!1),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=n-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):d===i.Z_SYNC_FLUSH?(this.onEnd(i.Z_OK),l.avail_out=0,!0):!0},n.prototype.onData=function(a){this.chunks.push(a)},n.prototype.onEnd=function(a){a===i.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=n,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":88,"./utils/strings":89,"./zlib/constants":91,"./zlib/gzheader":94,"./zlib/inflate.js":96,"./zlib/messages":98,"./zlib/zstream":100}],88:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],89:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":88}],90:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],91:[function(a,b,c){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],92:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],93:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ja?a.strstart-(a.w_size-ja):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ia,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ia-(m-f),f=m-ia,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ja)){C.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ha)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ha-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ha)););}while(a.lookahead<ja&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sa;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sa;if(a.strstart-a.block_start>=a.w_size-ja&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sa:sa}function o(a,b){for(var c,d;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c)),a.match_length>=ha)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-ha),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ha){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function p(a,b){for(var c,d,e;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ha-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===S||a.match_length===ha&&a.strstart-a.match_start>4096)&&(a.match_length=ha-1)),a.prev_length>=ha&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ha,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ha),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ha-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return sa}else if(a.match_available){if(d=D._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return sa}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=D._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ia){if(m(a),a.lookahead<=ia&&b===H)return sa;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ha&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ia;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ia-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ha?(c=D._tr_tally(a,1,a.match_length-ha),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sa;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ha-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fa),this.dyn_dtree=new C.Buf16(2*(2*da+1)),this.bl_tree=new C.Buf16(2*(2*ea+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(ga+1),this.heap=new C.Buf16(2*ca+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*ca+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?la:qa,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ha-1)/ha),i.window=new C.Buf8(2*i.w_size),i.head=new C.Buf16(i.hash_size),i.prev=new C.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new C.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ra&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===la)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=ma):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wa),h.status=qa);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ka),m+=31-m%31,h.status=qa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===ma)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=na)}else h.status=na;if(h.status===na)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pa)}else h.status=pa;if(h.status===pa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qa)):h.status=qa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===ra&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==ra){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ua||o===va)&&(h.status=ra),o===sa||o===ua)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===ta&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==la&&b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra?d(a,O):(a.state=null,b===qa?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,aa=29,ba=256,ca=ba+1+aa,da=30,ea=19,fa=2*ca+1,ga=15,ha=3,ia=258,ja=ia+ha+1,ka=32,la=42,ma=69,na=73,oa=91,pa=103,qa=113,ra=666,sa=1,ta=2,ua=3,va=4,wa=3,xa=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xa(0,0,0,0,n),new xa(4,4,8,4,o),new xa(4,5,16,8,o),new xa(4,6,32,32,o),new xa(4,4,16,16,p),new xa(8,16,32,32,p),new xa(8,16,128,128,p),new xa(8,32,128,256,p),new xa(32,128,258,1024,p),new xa(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":88,"./adler32":90,"./crc32":92,"./messages":98,"./trees":99}],94:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],95:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],96:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,
q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":88,"./adler32":90,"./crc32":92,"./inffast":95,"./inftrees":97}],97:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":88}],98:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],99:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?ga[a]:ga[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<<a.bi_valid&65535,f(a,a.bi_buf),a.bi_buf=b>>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function h(a,b,c){g(a,c[2*b],c[2*b+1])}function i(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function k(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ia[d]=c,a=0;a<1<<_[d];a++)ha[c++]=d;for(ha[c-1]=d,e=0,d=0;16>d;d++)for(ja[d]=e,a=0;a<1<<aa[d];a++)ga[e++]=d;for(e>>=7;R>d;d++)for(ja[d]=e<<7,a=0;a<1<<aa[d]-7;a++)ga[256+e++]=d;for(b=0;U>=b;b++)f[b]=0;for(a=0;143>=a;)ea[2*a+1]=8,a++,f[8]++;for(;255>=a;)ea[2*a+1]=9,a++,f[9]++;for(;279>=a;)ea[2*a+1]=7,a++,f[7]++;for(;287>=a;)ea[2*a+1]=8,a++,f[8]++;for(l(ea,Q+1,f),a=0;R>a;a++)fa[2*a+1]=5,fa[2*a]=i(a,5);ka=new na(ea,_,P+1,Q,U),la=new na(fa,aa,0,R,U),ma=new na(new Array(0),ba,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function q(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function r(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&q(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!q(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function s(a,b,c){var d,f,i,j,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],f=a.pending_buf[a.l_buf+k],k++,0===d?h(a,f,b):(i=ha[f],h(a,i+P+1,b),j=_[i],0!==j&&(f-=ia[i],g(a,f,j)),d--,i=e(d),h(a,i,c),j=aa[i],0!==j&&(d-=ja[i],g(a,d,j)));while(k<a.last_lit);h(a,X,b)}function t(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=T,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++j<k&&e===i)){if(l>j){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*ca[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*ca[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pa||(m(),pa=!0),a.l_desc=new oa(a.dyn_ltree,ka),a.d_desc=new oa(a.dyn_dtree,la),a.bl_desc=new oa(a.bl_tree,ma),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,ea),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,ea,fa)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ha[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],aa=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ba=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],da=512,ea=new Array(2*(Q+2));d(ea);var fa=new Array(2*R);d(fa);var ga=new Array(da);d(ga);var ha=new Array(N-M+1);d(ha);var ia=new Array(O);d(ia);var ja=new Array(R);d(ja);var ka,la,ma,na=function(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length},oa=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pa=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":88}],100:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}],101:[function(a,b,c){!function(a,b){"use strict";var c;a(function(a){function d(a,b){var c,d,e,f;if(c=a,e={},b){for(d in b)f=new RegExp("\\{"+d+"\\}"),f.test(c)?c=c.replace(f,encodeURIComponent(b[d]),"g"):e[d]=b[d];for(d in e)c+=-1===c.indexOf("?")?"?":"&",c+=encodeURIComponent(d),null!==e[d]&&void 0!==e[d]&&(c+="=",c+=encodeURIComponent(e[d]))}return c}function e(a,b){return 0===a.indexOf(b)}function f(a,b){return this instanceof f?void(a instanceof f?(this._template=a.template,this._params=g({},this._params,b)):(this._template=(a||"").toString(),this._params=b||{})):new f(a,b)}var g,h,i,j,k;return g=a("./util/mixin"),i=/([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?(\/[^?#]*)?(\?[^#]*)?(#\S*)?/i,j=/^([a-z][a-z0-9\-\+\.]*:\/\/|\/)/i,k=/([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?\//i,f.prototype={append:function(a,b){return new f(this._template+a,g({},this._params,b))},fullyQualify:function(){if(!b)return this;if(this.isFullyQualified())return this;var a=this._template;return e(a,"//")?a=h.protocol+a:e(a,"/")?a=h.origin+a:this.isAbsolute()||(a=h.origin+h.pathname.substring(0,h.pathname.lastIndexOf("/")+1)),-1===a.indexOf("/",8)&&(a+="/"),new f(a,this._params)},isAbsolute:function(){return j.test(this.build())},isFullyQualified:function(){return k.test(this.build())},isCrossOrigin:function(){if(!h)return!0;var a=this.parts();return a.protocol!==h.protocol||a.hostname!==h.hostname||a.port!==h.port},parts:function(){var a,b;return a=this.fullyQualify().build().match(i),b={href:a[0],protocol:a[1],host:a[3]||"",hostname:a[4]||"",port:a[6],pathname:a[7]||"",search:a[8]||"",hash:a[9]||""},b.origin=b.protocol+"//"+b.host,b.port=b.port||("https:"===b.protocol?"443":"http:"===b.protocol?"80":""),b},build:function(a){return d(this._template,g({},this._params,a))},toString:function(){return this.build()}},h=b?new f(b.href).parts():c,f})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)},"undefined"!=typeof window?window.location:void 0)},{"./util/mixin":137}],102:[function(a,b,c){!function(a){"use strict";a(function(a){var b=a("./client/default"),c=a("./client/xhr");return b.setPlatformDefaultClient(c),b})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./client/default":104,"./client/xhr":105}],103:[function(a,b,c){!function(a){"use strict";a(function(){return function(a,b){return b&&(a.skip=function(){return b}),a.wrap=function(b,c){return b(a,c)},a.chain=function(){return"undefined"!=typeof console&&console.log("rest.js: client.chain() is deprecated, use client.wrap() instead"),a.wrap.apply(this,arguments)},a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],104:[function(a,b,c){!function(a){"use strict";var b;a(function(a){function c(){return e.apply(b,arguments)}var d,e,f;return d=a("../client"),c.setDefaultClient=function(a){e=a},c.getDefaultClient=function(){return e},c.resetDefaultClient=function(){e=f},c.setPlatformDefaultClient=function(a){if(f)throw new Error("Unable to redefine platformDefaultClient");e=f=a},d(c)})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../client":103}],105:[function(a,b,c){!function(a,b){"use strict";a(function(a){function c(a){var b={};return a?(a.trim().split(j).forEach(function(a){var c,d,e;c=a.indexOf(":"),d=g(a.substring(0,c).trim()),e=a.substring(c+1).trim(),b[d]?Array.isArray(b[d])?b[d].push(e):b[d]=[b[d],e]:b[d]=e}),b):b}function d(a,b){return Object.keys(b||{}).forEach(function(c){if(b.hasOwnProperty(c)&&c in a)try{a[c]=b[c]}catch(d){}}),a}var e,f,g,h,i,j;return e=a("when"),f=a("../UrlBuilder"),g=a("../util/normalizeHeaderName"),h=a("../util/responsePromise"),i=a("../client"),j=/[\r|\n]+/,i(function(a){return h.promise(function(e,g){var h,i,j,k,l,m,n,o;if(a="string"==typeof a?{path:a}:a||{},n={request:a},a.canceled)return n.error="precanceled",void g(n);if(o=a.engine||b.XMLHttpRequest,!o)return void g({request:a,error:"xhr-not-available"});l=a.entity,a.method=a.method||(l?"POST":"GET"),i=a.method,j=new f(a.path||"",a.params).build();try{h=n.raw=new o,d(h,a.mixin),h.open(i,j,!0),d(h,a.mixin),k=a.headers;for(m in k)("Content-Type"!==m||"multipart/form-data"!==k[m])&&h.setRequestHeader(m,k[m]);a.canceled=!1,a.cancel=function(){a.canceled=!0,h.abort(),g(n)},h.onreadystatechange=function(){a.canceled||h.readyState===(o.DONE||4)&&(n.status={code:h.status,text:h.statusText},n.headers=c(h.getAllResponseHeaders()),n.entity=h.responseText,n.status.code>0?e(n):setTimeout(function(){e(n)},0))};try{h.onerror=function(){n.error="loaderror",g(n)}}catch(p){}h.send(l)}catch(p){n.error="loaderror",g(n)}})})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)},"undefined"!=typeof window?window:void 0)},{"../UrlBuilder":101,"../client":103,"../util/normalizeHeaderName":138,"../util/responsePromise":139,when:134}],106:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a){return a}function c(a){return a}function d(a){return a}function e(a){return l.promise(function(b,c){a.forEach(function(a){l(a,b,c)})})}function f(a){return this instanceof f?void i(this,a):new f(a)}function g(a){var g,i,m,n;return a=a||{},g=a.init||b,i=a.request||c,m=a.success||a.response||d,n=a.error||function(){return l((a.response||d).apply(this,arguments),l.reject,l.reject)},function(b,c){function d(a){var g,h;return g={},h={arguments:Array.prototype.slice.call(arguments),client:d},a="string"==typeof a?{path:a}:a||{},a.originator=a.originator||d,j(i.call(g,a,c,h),function(a){var d,i,j;return j=b,a instanceof f&&(i=a.abort,j=a.client||j,d=a.response,a=a.request),d=d||l(a,function(a){return l(j(a),function(a){return m.call(g,a,c,h)},function(a){return n.call(g,a,c,h)})}),i?e([d,i]):d},function(b){return l.reject({request:a,error:b})})}return"object"==typeof b&&(c=b),"function"!=typeof b&&(b=a.client||h),c=g(c||{}),k(d,b)}}var h,i,j,k,l;return h=a("./client/default"),i=a("./util/mixin"),j=a("./util/responsePromise"),k=a("./client"),l=a("when"),g.ComplexRequest=f,g})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./client":103,"./client/default":104,"./util/mixin":137,"./util/responsePromise":139,when:134}],107:[function(a,b,c){!function(a){"use strict";a(function(a){var b,c,d,e,f;return b=a("../interceptor"),c=a("../mime"),d=a("../mime/registry"),f=a("when"),e={read:function(a){return a},write:function(a){return a}},b({init:function(a){return a.registry=a.registry||d,a},request:function(a,b){var d,g;return g=a.headers||(a.headers={}),d=c.parse(g["Content-Type"]=g["Content-Type"]||b.mime||"text/plain"),g.Accept=g.Accept||b.accept||d.raw+", application/json;q=0.8, text/plain;q=0.5, */*;q=0.2","entity"in a?b.registry.lookup(d).otherwise(function(){if(b.permissive)return e;throw"mime-unknown"}).then(function(c){var e=b.client||a.originator;return f.attempt(c.write,a.entity,{client:e,request:a,mime:d,registry:b.registry}).otherwise(function(){throw"mime-serialization"}).then(function(b){return a.entity=b,a})}):a},response:function(a,b){if(!(a.headers&&a.headers["Content-Type"]&&a.entity))return a;var d=c.parse(a.headers["Content-Type"]);return b.registry.lookup(d).otherwise(function(){return e}).then(function(c){var e=b.client||a.request&&a.request.originator;return f.attempt(c.read,a.entity,{client:e,response:a,mime:d,registry:b.registry}).otherwise(function(b){throw a.error="mime-deserialization",a.cause=b,a}).then(function(b){return a.entity=b,a})})}})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../interceptor":106,"../mime":110,"../mime/registry":111,when:134}],108:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b){return 0===a.indexOf(b)}function c(a,b){return a.lastIndexOf(b)+b.length===a.length}var d,e;return d=a("../interceptor"),e=a("../UrlBuilder"),d({request:function(a,d){var f;return d.prefix&&!new e(a.path).isFullyQualified()&&(f=d.prefix,a.path&&(c(f,"/")||b(a.path,"/")||(f+="/"),f+=a.path),a.path=f),a}})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../UrlBuilder":101,"../interceptor":106}],109:[function(a,b,c){!function(a){"use strict";a(function(a){var b,c,d;return b=a("../interceptor"),c=a("../util/uriTemplate"),d=a("../util/mixin"),b({init:function(a){return a.params=a.params||{},a.template=a.template||"",a},request:function(a,b){var e,f;return e=a.path||b.template,f=d({},a.params,b.params),a.path=c.expand(e,f),delete a.params,a}})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../interceptor":106,"../util/mixin":137,"../util/uriTemplate":141}],110:[function(a,b,c){!function(a){"use strict";var b;a(function(){function a(a){var c,d;return c=a.split(";"),d=c[0].trim().split("+"),{raw:a,type:d[0],suffix:d[1]?"+"+d[1]:"",params:c.slice(1).reduce(function(a,c){return c=c.split("="),a[c[0].trim()]=c[1]?c[1].trim():b,a},{})}}return{parse:a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],111:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a){this.lookup=function(b){var e;return e="string"==typeof b?c.parse(b):b,a[e.raw]?a[e.raw]:a[e.type+e.suffix]?a[e.type+e.suffix]:a[e.type]?a[e.type]:a[e.suffix]?a[e.suffix]:d.reject(new Error('Unable to locate converter for mime "'+e.raw+'"'))},this.delegate=function(a){return{read:function(){var b=arguments;return this.lookup(a).then(function(a){return a.read.apply(this,b)}.bind(this))}.bind(this),write:function(){var b=arguments;return this.lookup(a).then(function(a){return a.write.apply(this,b)}.bind(this))}.bind(this)}},this.register=function(b,c){return a[b]=d(c),a[b]},this.child=function(){return new b(Object.create(a))}}var c,d,e;return c=a("../mime"),d=a("when"),e=new b({}),e.register("application/hal",a("./type/application/hal")),e.register("application/json",a("./type/application/json")),e.register("application/x-www-form-urlencoded",a("./type/application/x-www-form-urlencoded")),e.register("multipart/form-data",a("./type/multipart/form-data")),e.register("text/plain",a("./type/text/plain")),e.register("+json",e.delegate("application/json")),e})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../mime":110,"./type/application/hal":112,"./type/application/json":113,"./type/application/x-www-form-urlencoded":114,"./type/multipart/form-data":115,"./type/text/plain":116,when:134}],112:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b,c){Object.defineProperty(a,b,{value:c,configurable:!0,enumerable:!1,writeable:!0})}var c,d,e,f,g,h;return c=a("../../../interceptor/pathPrefix"),d=a("../../../interceptor/template"),e=a("../../../util/find"),f=a("../../../util/lazyPromise"),g=a("../../../util/responsePromise"),h=a("when"),{read:function(a,i){function j(a,b){(b&&l&&l.warn||l.log)&&(l.warn||l.log).call(l,"Relationship '"+a+"' is deprecated, see "+b)}var k,l;return i=i||{},k=i.client,l=i.console||l,i.registry.lookup(i.mime.suffix).then(function(l){return h(l.read(a,i)).then(function(a){return e.findProperties(a,"_embedded",function(a,c,d){Object.keys(a).forEach(function(d){if(!(d in c)){var e=g({entity:a[d]});b(c,d,e)}}),b(c,d,a)}),e.findProperties(a,"_links",function(a,e,h){Object.keys(a).forEach(function(c){var h=a[c];c in e||b(e,c,g.make(f(function(){return h.deprecation&&j(c,h.deprecation),h.templated===!0?d(k)({path:h.href}):k({path:h.href})})))}),b(e,h,a),b(e,"clientFor",function(b,e){var f=a[b];if(!f)throw new Error("Unknown relationship: "+b);return f.deprecation&&j(b,f.deprecation),f.templated===!0?d(e||k,{template:f.href}):c(e||k,{prefix:f.href})}),b(e,"requestFor",function(a,b,c){var d=this.clientFor(a,c);return d(b)})}),a})})},write:function(a,b){return b.registry.lookup(b.mime.suffix).then(function(c){return c.write(a,b)})}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../../../interceptor/pathPrefix":108,"../../../interceptor/template":109,"../../../util/find":135,"../../../util/lazyPromise":136,"../../../util/responsePromise":139,when:134}],113:[function(a,b,c){!function(a){"use strict";a(function(){function a(b,c){return{read:function(a){return JSON.parse(a,b)},write:function(a){return JSON.stringify(a,c)},extend:a}}return a()})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],114:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){return a=encodeURIComponent(a),a.replace(d,"+")}function b(a){return a=a.replace(e," "),decodeURIComponent(a)}function c(b,d,e){return Array.isArray(e)?e.forEach(function(a){b=c(b,d,a)}):(b.length>0&&(b+="&"),b+=a(d),void 0!==e&&null!==e&&(b+="="+a(e))),b}var d,e;return d=/%20/g,e=/\+/g,{read:function(a){var c={};return a.split("&").forEach(function(a){var d,e,f;d=a.split("="),e=b(d[0]),f=2===d.length?b(d[1]):null,e in c?(Array.isArray(c[e])||(c[e]=[c[e]]),c[e].push(f)):c[e]=f}),c},write:function(a){var b="";return Object.keys(a).forEach(function(d){b=c(b,d,a[d])}),b}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],115:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){return a&&1===a.nodeType&&"FORM"===a.tagName}function b(a){var b,c=new FormData;for(var d in a)a.hasOwnProperty(d)&&(b=a[d],b instanceof File?c.append(d,b,b.name):b instanceof Blob?c.append(d,b):c.append(d,String(b)));return c}return{write:function(c){if("undefined"==typeof FormData)throw new Error("The multipart/form-data mime serializer requires FormData support");if(c instanceof FormData)return c;if(a(c))return new FormData(c);if("object"==typeof c&&null!==c)return b(c);throw new Error("Unable to create FormData from object "+c)}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],116:[function(a,b,c){!function(a){"use strict";a(function(){return{read:function(a){return a},write:function(a){return a.toString()}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],117:[function(a,b,c){!function(a){"use strict";a(function(a){var b=a("./makePromise"),c=a("./Scheduler"),d=a("./env").asap;return b({scheduler:new c(d)})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./Scheduler":118,"./env":130,"./makePromise":132}],118:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){this._async=a,this._running=!1,this._queue=this,this._queueLen=0,this._afterQueue={},this._afterQueueLen=0;var b=this;this.drain=function(){b._drain()}}return a.prototype.enqueue=function(a){this._queue[this._queueLen++]=a,this.run()},a.prototype.afterQueue=function(a){this._afterQueue[this._afterQueueLen++]=a,this.run()},a.prototype.run=function(){this._running||(this._running=!0,this._async(this.drain))},a.prototype._drain=function(){for(var a=0;a<this._queueLen;++a)this._queue[a].run(),this._queue[a]=void 0;for(this._queueLen=0,this._running=!1,a=0;a<this._afterQueueLen;++a)this._afterQueue[a].run(),this._afterQueue[a]=void 0;this._afterQueueLen=0},a})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],119:[function(a,b,c){!function(a){"use strict";a(function(){function a(b){Error.call(this),this.message=b,this.name=a.name,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,a)}return a.prototype=Object.create(Error.prototype),a.prototype.constructor=a,a})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],120:[function(a,b,c){!function(a){"use strict";a(function(){function a(a,c){function d(b,d,f){var g=a._defer(),h=f.length,i=new Array(h);return e({f:b,thisArg:d,args:f,params:i,i:h-1,call:c},g._handler),g}function e(b,d){if(b.i<0)return c(b.f,b.thisArg,b.params,d);var e=a._handler(b.args[b.i]);e.fold(f,b,void 0,d)}function f(a,b,c){a.params[a.i]=b,a.i-=1,e(a,c)}return arguments.length<2&&(c=b),d}function b(a,b,c,d){try{d.resolve(a.apply(b,c))}catch(e){d.reject(e)}}return a.tryCatchResolve=b,a})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],121:[function(a,b,c){!function(a){"use strict";a(function(a){var b=a("../state"),c=a("../apply");return function(a){function d(b){function c(a){k=null,this.resolve(a)}function d(a){this.resolved||(k.push(a),0===--j&&this.reject(k))}for(var e,f,g=a._defer(),h=g._handler,i=b.length>>>0,j=i,k=[],l=0;i>l;++l)if(f=b[l],void 0!==f||l in b){if(e=a._handler(f),e.state()>0){h.become(e),a._visitRemaining(b,l,e);break}e.visit(h,c,d)}else--j;return 0===j&&h.reject(new RangeError("any(): array must not be empty")),g}function e(b,c){function d(a){this.resolved||(k.push(a),0===--n&&(l=null,this.resolve(k)))}function e(a){this.resolved||(l.push(a),0===--f&&(k=null,this.reject(l)))}var f,g,h,i=a._defer(),j=i._handler,k=[],l=[],m=b.length>>>0,n=0;for(h=0;m>h;++h)g=b[h],(void 0!==g||h in b)&&++n;for(c=Math.max(c,0),f=n-c+1,n=Math.min(c,n),c>n?j.reject(new RangeError("some(): array must contain at least "+c+" item(s), but had "+n)):0===n&&j.resolve(k),h=0;m>h;++h)g=b[h],(void 0!==g||h in b)&&a._handler(g).visit(j,d,e,j.notify);return i}function f(b,c){return a._traverse(c,b)}function g(b,c){var d=s.call(b);return a._traverse(c,d).then(function(a){return h(d,a)})}function h(b,c){for(var d=c.length,e=new Array(d),f=0,g=0;d>f;++f)c[f]&&(e[g++]=a._handler(b[f]).value);return e.length=g,e}function i(a){return p(a.map(j))}function j(c){var d=a._handler(c);return 0===d.state()?o(c).then(b.fulfilled,b.rejected):(d._unreport(),b.inspect(d))}function k(a,b){return arguments.length>2?q.call(a,m(b),arguments[2]):q.call(a,m(b))}function l(a,b){return arguments.length>2?r.call(a,m(b),arguments[2]):r.call(a,m(b))}function m(a){return function(b,c,d){return n(a,void 0,[b,c,d])}}var n=c(a),o=a.resolve,p=a.all,q=Array.prototype.reduce,r=Array.prototype.reduceRight,s=Array.prototype.slice;return a.any=d,a.some=e,a.settle=i,a.map=f,a.filter=g,a.reduce=k,a.reduceRight=l,a.prototype.spread=function(a){return this.then(p).then(function(b){return a.apply(this,b)})},a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../apply":120,"../state":133}],122:[function(a,b,c){!function(a){"use strict";a(function(){function a(){throw new TypeError("catch predicate must be a function")}function b(a,b){return c(b)?a instanceof b:b(a)}function c(a){return a===Error||null!=a&&a.prototype instanceof Error}function d(a){return("object"==typeof a||"function"==typeof a)&&null!==a}function e(a){return a}return function(c){function f(a,c){return function(d){return b(d,c)?a.call(this,d):j(d)}}function g(a,b,c,e){var f=a.call(b);return d(f)?h(f,c,e):c(e)}function h(a,b,c){return i(a).then(function(){return b(c)})}var i=c.resolve,j=c.reject,k=c.prototype["catch"];return c.prototype.done=function(a,b){this._handler.visit(this._handler.receiver,a,b)},c.prototype["catch"]=c.prototype.otherwise=function(b){return arguments.length<2?k.call(this,b):"function"!=typeof b?this.ensure(a):k.call(this,f(arguments[1],b))},c.prototype["finally"]=c.prototype.ensure=function(a){return"function"!=typeof a?this:this.then(function(b){return g(a,this,e,b)},function(b){return g(a,this,j,b)})},c.prototype["else"]=c.prototype.orElse=function(a){return this.then(void 0,function(){return a})},c.prototype["yield"]=function(a){return this.then(function(){return a})},c.prototype.tap=function(a){return this.then(a)["yield"](this)},c}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],123:[function(a,b,c){!function(a){"use strict";a(function(){return function(a){return a.prototype.fold=function(b,c){var d=this._beget();return this._handler.fold(function(c,d,e){a._handler(c).fold(function(a,c,d){d.resolve(b.call(this,c,a))},d,this,e)},c,d._handler.receiver,d._handler),d},a}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],124:[function(a,b,c){!function(a){"use strict";a(function(a){var b=a("../state").inspect;return function(a){return a.prototype.inspect=function(){return b(a._handler(this))},a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../state":133}],125:[function(a,b,c){!function(a){"use strict";a(function(){return function(a){function b(a,b,d,e){return c(function(b){return[b,a(b)]},b,d,e)}function c(a,b,e,f){function g(f,g){return d(e(f)).then(function(){return c(a,b,e,g)})}return d(f).then(function(c){return d(b(c)).then(function(b){return b?c:d(a(c)).spread(g)})})}var d=a.resolve;return a.iterate=b,a.unfold=c,a}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],126:[function(a,b,c){!function(a){"use strict";a(function(){return function(a){return a.prototype.progress=function(a){return this.then(void 0,void 0,a)},a}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],127:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b,d,e){return c.setTimer(function(){a(d,e,b)},b)}var c=a("../env"),d=a("../TimeoutError");return function(a){function e(a,c,d){b(f,a,c,d)}function f(a,b){b.resolve(a)}function g(a,b,c){var e="undefined"==typeof a?new d("timed out after "+c+"ms"):a;
b.reject(e)}return a.prototype.delay=function(a){var b=this._beget();return this._handler.fold(e,a,void 0,b._handler),b},a.prototype.timeout=function(a,d){var e=this._beget(),f=e._handler,h=b(g,a,d,e._handler);return this._handler.visit(f,function(a){c.clearTimer(h),this.resolve(a)},function(a){c.clearTimer(h),this.reject(a)},f.notify),e},a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../TimeoutError":119,"../env":130}],128:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a){throw a}function c(){}var d=a("../env").setTimer,e=a("../format");return function(a){function f(a){a.handled||(n.push(a),k("Potentially unhandled rejection ["+a.id+"] "+e.formatError(a.value)))}function g(a){var b=n.indexOf(a);b>=0&&(n.splice(b,1),l("Handled previous rejection ["+a.id+"] "+e.formatObject(a.value)))}function h(a,b){m.push(a,b),null===o&&(o=d(i,0))}function i(){for(o=null;m.length>0;)m.shift()(m.shift())}var j,k=c,l=c;"undefined"!=typeof console&&(j=console,k="undefined"!=typeof j.error?function(a){j.error(a)}:function(a){j.log(a)},l="undefined"!=typeof j.info?function(a){j.info(a)}:function(a){j.log(a)}),a.onPotentiallyUnhandledRejection=function(a){h(f,a)},a.onPotentiallyUnhandledRejectionHandled=function(a){h(g,a)},a.onFatalRejection=function(a){h(b,a.value)};var m=[],n=[],o=null;return a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../env":130,"../format":131}],129:[function(a,b,c){!function(a){"use strict";a(function(){return function(a){return a.prototype["with"]=a.prototype.withThis=function(a){var b=this._beget(),c=b._handler;return c.receiver=a,this._handler.chain(c,a),b},a}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],130:[function(a,b,c){(function(c){!function(a){"use strict";a(function(a){function b(){return"undefined"!=typeof c&&"[object process]"===Object.prototype.toString.call(c)}function d(){return"function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver}function e(a){function b(){var a=c;c=void 0,a()}var c,d=document.createTextNode(""),e=new a(b);e.observe(d,{characterData:!0});var f=0;return function(a){c=a,d.data=f^=1}}var f,g="undefined"!=typeof setTimeout&&setTimeout,h=function(a,b){return setTimeout(a,b)},i=function(a){return clearTimeout(a)},j=function(a){return g(a,0)};if(b())j=function(a){return c.nextTick(a)};else if(f=d())j=e(f);else if(!g){var k=a,l=k("vertx");h=function(a,b){return l.setTimer(b,a)},i=l.cancelTimer,j=l.runOnLoop||l.runOnContext}return{setTimer:h,clearTimer:i,asap:j}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})}).call(this,a("_process"))},{_process:76}],131:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){var c="object"==typeof a&&null!==a&&a.stack?a.stack:b(a);return a instanceof Error?c:c+" (WARNING: non-Error used)"}function b(a){var b=String(a);return"[object Object]"===b&&"undefined"!=typeof JSON&&(b=c(a,b)),b}function c(a,b){try{return JSON.stringify(a)}catch(c){return b}}return{formatError:a,formatObject:b,tryStringify:c}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],132:[function(a,b,c){(function(a){!function(b){"use strict";b(function(){return function(b){function c(a,b){this._handler=a===u?b:d(a)}function d(a){function b(a){e.resolve(a)}function c(a){e.reject(a)}function d(a){e.notify(a)}var e=new w;try{a(b,c,d)}catch(f){c(f)}return e}function e(a){return J(a)?a:new c(u,new x(r(a)))}function f(a){return new c(u,new x(new A(a)))}function g(){return aa}function h(){return new c(u,new w)}function i(a,b){var c=new w(a.receiver,a.join().context);return new b(u,c)}function j(a){return l(T,null,a)}function k(a,b){return l(O,a,b)}function l(a,b,d){function e(c,e,g){g.resolved||m(d,f,c,a(b,e,c),g)}function f(a,b,c){k[a]=b,0===--j&&c.become(new z(k))}for(var g,h="function"==typeof b?e:f,i=new w,j=d.length>>>0,k=new Array(j),l=0;l<d.length&&!i.resolved;++l)g=d[l],void 0!==g||l in d?m(d,h,l,g,i):--j;return 0===j&&i.become(new z(k)),new c(u,i)}function m(a,b,c,d,e){if(K(d)){var f=s(d),g=f.state();0===g?f.fold(b,c,void 0,e):g>0?b(c,f.value,e):(e.become(f),n(a,c+1,f))}else b(c,d,e)}function n(a,b,c){for(var d=b;d<a.length;++d)o(r(a[d]),c)}function o(a,b){if(a!==b){var c=a.state();0===c?a.visit(a,void 0,a._unreport):0>c&&a._unreport()}}function p(a){return"object"!=typeof a||null===a?f(new TypeError("non-iterable passed to race()")):0===a.length?g():1===a.length?e(a[0]):q(a)}function q(a){var b,d,e,f=new w;for(b=0;b<a.length;++b)if(d=a[b],void 0!==d||b in a){if(e=r(d),0!==e.state()){f.become(e),n(a,b+1,e);break}e.visit(f,f.resolve,f.reject)}return new c(u,f)}function r(a){return J(a)?a._handler.join():K(a)?t(a):new z(a)}function s(a){return J(a)?a._handler.join():t(a)}function t(a){try{var b=a.then;return"function"==typeof b?new y(b,a):new z(a)}catch(c){return new A(c)}}function u(){}function v(){}function w(a,b){c.createContext(this,b),this.consumers=void 0,this.receiver=a,this.handler=void 0,this.resolved=!1}function x(a){this.handler=a}function y(a,b){w.call(this),W.enqueue(new G(a,b,this))}function z(a){c.createContext(this),this.value=a}function A(a){c.createContext(this),this.id=++$,this.value=a,this.handled=!1,this.reported=!1,this._report()}function B(a,b){this.rejection=a,this.context=b}function C(a){this.rejection=a}function D(){return new A(new TypeError("Promise cycle"))}function E(a,b){this.continuation=a,this.handler=b}function F(a,b){this.handler=b,this.value=a}function G(a,b,c){this._then=a,this.thenable=b,this.resolver=c}function H(a,b,c,d,e){try{a.call(b,c,d,e)}catch(f){d(f)}}function I(a,b,c,d){this.f=a,this.z=b,this.c=c,this.to=d,this.resolver=Z,this.receiver=this}function J(a){return a instanceof c}function K(a){return("object"==typeof a||"function"==typeof a)&&null!==a}function L(a,b,d,e){return"function"!=typeof a?e.become(b):(c.enterContext(b),P(a,b.value,d,e),void c.exitContext())}function M(a,b,d,e,f){return"function"!=typeof a?f.become(d):(c.enterContext(d),Q(a,b,d.value,e,f),void c.exitContext())}function N(a,b,d,e,f){return"function"!=typeof a?f.notify(b):(c.enterContext(d),R(a,b,e,f),void c.exitContext())}function O(a,b,c){try{return a(b,c)}catch(d){return f(d)}}function P(a,b,c,d){try{d.become(r(a.call(c,b)))}catch(e){d.become(new A(e))}}function Q(a,b,c,d,e){try{a.call(d,b,c,e)}catch(f){e.become(new A(f))}}function R(a,b,c,d){try{d.notify(a.call(c,b))}catch(e){d.notify(e)}}function S(a,b){b.prototype=Y(a.prototype),b.prototype.constructor=b}function T(a,b){return b}function U(){}function V(){return"undefined"!=typeof a&&null!==a&&"function"==typeof a.emit?function(b,c){return"unhandledRejection"===b?a.emit(b,c.value,c):a.emit(b,c)}:"undefined"!=typeof self&&"function"==typeof CustomEvent?function(a,b,c){var d=!1;try{var e=new c("unhandledRejection");d=e instanceof c}catch(f){}return d?function(a,d){var e=new c(a,{detail:{reason:d.value,key:d},bubbles:!1,cancelable:!0});return!b.dispatchEvent(e)}:a}(U,self,CustomEvent):U}var W=b.scheduler,X=V(),Y=Object.create||function(a){function b(){}return b.prototype=a,new b};c.resolve=e,c.reject=f,c.never=g,c._defer=h,c._handler=r,c.prototype.then=function(a,b,c){var d=this._handler,e=d.join().state();if("function"!=typeof a&&e>0||"function"!=typeof b&&0>e)return new this.constructor(u,d);var f=this._beget(),g=f._handler;return d.chain(g,d.receiver,a,b,c),f},c.prototype["catch"]=function(a){return this.then(void 0,a)},c.prototype._beget=function(){return i(this._handler,this.constructor)},c.all=j,c.race=p,c._traverse=k,c._visitRemaining=n,u.prototype.when=u.prototype.become=u.prototype.notify=u.prototype.fail=u.prototype._unreport=u.prototype._report=U,u.prototype._state=0,u.prototype.state=function(){return this._state},u.prototype.join=function(){for(var a=this;void 0!==a.handler;)a=a.handler;return a},u.prototype.chain=function(a,b,c,d,e){this.when({resolver:a,receiver:b,fulfilled:c,rejected:d,progress:e})},u.prototype.visit=function(a,b,c,d){this.chain(Z,a,b,c,d)},u.prototype.fold=function(a,b,c,d){this.when(new I(a,b,c,d))},S(u,v),v.prototype.become=function(a){a.fail()};var Z=new v;S(u,w),w.prototype._state=0,w.prototype.resolve=function(a){this.become(r(a))},w.prototype.reject=function(a){this.resolved||this.become(new A(a))},w.prototype.join=function(){if(!this.resolved)return this;for(var a=this;void 0!==a.handler;)if(a=a.handler,a===this)return this.handler=D();return a},w.prototype.run=function(){var a=this.consumers,b=this.handler;this.handler=this.handler.join(),this.consumers=void 0;for(var c=0;c<a.length;++c)b.when(a[c])},w.prototype.become=function(a){this.resolved||(this.resolved=!0,this.handler=a,void 0!==this.consumers&&W.enqueue(this),void 0!==this.context&&a._report(this.context))},w.prototype.when=function(a){this.resolved?W.enqueue(new E(a,this.handler)):void 0===this.consumers?this.consumers=[a]:this.consumers.push(a)},w.prototype.notify=function(a){this.resolved||W.enqueue(new F(a,this))},w.prototype.fail=function(a){var b="undefined"==typeof a?this.context:a;this.resolved&&this.handler.join().fail(b)},w.prototype._report=function(a){this.resolved&&this.handler.join()._report(a)},w.prototype._unreport=function(){this.resolved&&this.handler.join()._unreport()},S(u,x),x.prototype.when=function(a){W.enqueue(new E(a,this))},x.prototype._report=function(a){this.join()._report(a)},x.prototype._unreport=function(){this.join()._unreport()},S(w,y),S(u,z),z.prototype._state=1,z.prototype.fold=function(a,b,c,d){M(a,b,this,c,d)},z.prototype.when=function(a){L(a.fulfilled,this,a.receiver,a.resolver)};var $=0;S(u,A),A.prototype._state=-1,A.prototype.fold=function(a,b,c,d){d.become(this)},A.prototype.when=function(a){"function"==typeof a.rejected&&this._unreport(),L(a.rejected,this,a.receiver,a.resolver)},A.prototype._report=function(a){W.afterQueue(new B(this,a))},A.prototype._unreport=function(){this.handled||(this.handled=!0,W.afterQueue(new C(this)))},A.prototype.fail=function(a){this.reported=!0,X("unhandledRejection",this),c.onFatalRejection(this,void 0===a?this.context:a)},B.prototype.run=function(){this.rejection.handled||this.rejection.reported||(this.rejection.reported=!0,X("unhandledRejection",this.rejection)||c.onPotentiallyUnhandledRejection(this.rejection,this.context))},C.prototype.run=function(){this.rejection.reported&&(X("rejectionHandled",this.rejection)||c.onPotentiallyUnhandledRejectionHandled(this.rejection))},c.createContext=c.enterContext=c.exitContext=c.onPotentiallyUnhandledRejection=c.onPotentiallyUnhandledRejectionHandled=c.onFatalRejection=U;var _=new u,aa=new c(u,_);return E.prototype.run=function(){this.handler.join().when(this.continuation)},F.prototype.run=function(){var a=this.handler.consumers;if(void 0!==a)for(var b,c=0;c<a.length;++c)b=a[c],N(b.progress,this.value,this.handler,b.receiver,b.resolver)},G.prototype.run=function(){function a(a){d.resolve(a)}function b(a){d.reject(a)}function c(a){d.notify(a)}var d=this.resolver;H(this._then,this.thenable,a,b,c)},I.prototype.fulfilled=function(a){this.f.call(this.c,this.z,a,this.to)},I.prototype.rejected=function(a){this.to.reject(a)},I.prototype.progress=function(a){this.to.notify(a)},c}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})}).call(this,a("_process"))},{_process:76}],133:[function(a,b,c){!function(a){"use strict";a(function(){function a(){return{state:"pending"}}function b(a){return{state:"rejected",reason:a}}function c(a){return{state:"fulfilled",value:a}}function d(d){var e=d.state();return 0===e?a():e>0?c(d.value):b(d.value)}return{pending:a,fulfilled:c,rejected:b,inspect:d}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],134:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b,c,d){var e=x.resolve(a);return arguments.length<2?e:e.then(b,c,d)}function c(a){return new x(a)}function d(a){return function(){for(var b=0,c=arguments.length,d=new Array(c);c>b;++b)d[b]=arguments[b];return y(a,this,d)}}function e(a){for(var b=0,c=arguments.length-1,d=new Array(c);c>b;++b)d[b]=arguments[b+1];return y(a,this,d)}function f(){return new g}function g(){function a(a){d._handler.resolve(a)}function b(a){d._handler.reject(a)}function c(a){d._handler.notify(a)}var d=x._defer();this.promise=d,this.resolve=a,this.reject=b,this.notify=c,this.resolver={resolve:a,reject:b,notify:c}}function h(a){return a&&"function"==typeof a.then}function i(){return x.all(arguments)}function j(a){return b(a,x.all)}function k(a){return b(a,x.settle)}function l(a,c){return b(a,function(a){return x.map(a,c)})}function m(a,c){return b(a,function(a){return x.filter(a,c)})}var n=a("./lib/decorators/timed"),o=a("./lib/decorators/array"),p=a("./lib/decorators/flow"),q=a("./lib/decorators/fold"),r=a("./lib/decorators/inspect"),s=a("./lib/decorators/iterate"),t=a("./lib/decorators/progress"),u=a("./lib/decorators/with"),v=a("./lib/decorators/unhandledRejection"),w=a("./lib/TimeoutError"),x=[o,p,q,s,t,r,u,n,v].reduce(function(a,b){return b(a)},a("./lib/Promise")),y=a("./lib/apply")(x);return b.promise=c,b.resolve=x.resolve,b.reject=x.reject,b.lift=d,b["try"]=e,b.attempt=e,b.iterate=x.iterate,b.unfold=x.unfold,b.join=i,b.all=j,b.settle=k,b.any=d(x.any),b.some=d(x.some),b.race=d(x.race),b.map=l,b.filter=m,b.reduce=d(x.reduce),b.reduceRight=d(x.reduceRight),b.isPromiseLike=h,b.Promise=x,b.defer=f,b.TimeoutError=w,b})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./lib/Promise":117,"./lib/TimeoutError":119,"./lib/apply":120,"./lib/decorators/array":121,"./lib/decorators/flow":122,"./lib/decorators/fold":123,"./lib/decorators/inspect":124,"./lib/decorators/iterate":125,"./lib/decorators/progress":126,"./lib/decorators/timed":127,"./lib/decorators/unhandledRejection":128,"./lib/decorators/with":129}],135:[function(a,b,c){!function(a){"use strict";a(function(){return{findProperties:function a(b,c,d){"object"==typeof b&&null!==b&&(c in b&&d(b[c],b,c),Object.keys(b).forEach(function(e){a(b[e],c,d)}))}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],136:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a){var b,d,e,f,g;return b=c.defer(),d=!1,e=b.resolver,f=b.promise,g=f.then,f.then=function(){return d||(d=!0,c.attempt(a).then(e.resolve,e.reject)),g.apply(f,arguments)},f}var c;return c=a("when"),b})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{when:134}],137:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){var c,d,e,f;for(a||(a={}),c=1,d=arguments.length;d>c;c+=1){e=arguments[c];for(f in e)f in a&&(a[f]===e[f]||f in b&&b[f]===e[f])||(a[f]=e[f])}return a}var b={};return a})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],138:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){return a.toLowerCase().split("-").map(function(a){return a.charAt(0).toUpperCase()+a.slice(1)}).join("-")}return a})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],139:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b){return a.then(function(a){return a&&a[b]},function(a){return j.reject(a&&a[b])})}function c(){return b(this,"entity")}function d(){return b(b(this,"status"),"code")}function e(){return b(this,"headers")}function f(a){return a=k(a),b(this.headers(),a)}function g(a){return a=[].concat(a),h(j.reduce(a,function(a,b){if("string"==typeof b&&(b={rel:b}),"function"!=typeof a.entity.clientFor)throw new Error("Hypermedia response expected");var c=a.entity.clientFor(b.rel);return c({params:b.params})},this))}function h(a){return a.status=d,a.headers=e,a.header=f,a.entity=c,a.follow=g,a}function i(){return h(j.apply(j,arguments))}var j=a("when"),k=a("./normalizeHeaderName");return i.make=h,i.reject=function(a){return h(j.reject(a))},i.promise=function(a){return h(j.promise(a))},i})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./normalizeHeaderName":138,when:134}],140:[function(a,b,c){!function(a){"use strict";a(function(){function a(a,b){if("string"!=typeof a)throw new Error("String required for URL encoding");return a.split("").map(function(a){if(b.hasOwnProperty(a))return a;var c=a.charCodeAt(0);return 127>=c?"%"+c.toString(16).toUpperCase():encodeURIComponent(a).toUpperCase()}).join("")}function b(b){return b=b||d.unreserved,function(c){return a(c,b)}}function c(a){return decodeURIComponent(a)}var d;return d=function(){var a={alpha:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",digit:"0123456789"};return a.genDelims=":/?#[]@",a.subDelims="!$&'()*+,;=",a.reserved=a.genDelims+a.subDelims,a.unreserved=a.alpha+a.digit+"-._~",a.url=a.reserved+a.unreserved,a.scheme=a.alpha+a.digit+"+-.",a.userinfo=a.unreserved+a.subDelims+":",a.host=a.unreserved+a.subDelims,a.port=a.digit,a.pchar=a.unreserved+a.subDelims+":@",a.segment=a.pchar,a.path=a.segment+"/",a.query=a.pchar+"/?",a.fragment=a.pchar+"/?",Object.keys(a).reduce(function(b,c){return b[c]=a[c].split("").reduce(function(a,b){return a[b]=!0,a},{}),b},{})}(),{decode:c,encode:b(),encodeURL:b(d.url),encodeScheme:b(d.scheme),encodeUserInfo:b(d.userinfo),encodeHost:b(d.host),encodePort:b(d.port),encodePathSegment:b(d.segment),encodePath:b(d.path),encodeQuery:b(d.query),encodeFragment:b(d.fragment)}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],141:[function(a,b,c){!function(a){"use strict";var b;a(function(a){function c(a,c,d){return c.split(",").reduce(function(c,e){var g,i;if(g={},"*"===e.slice(-1)&&(e=e.slice(0,-1),g.explode=!0),h.test(e)){var j=h.exec(e);e=j[1],g.maxLength=parseInt(j[2])}return e=f.decode(e),i=d[e],i===b||null===i?c:(Array.isArray(i)?c+=i.reduce(function(b,c){return b.length?(b+=g.explode?a.separator:",",a.named&&g.explode&&(b+=a.encoder(e),b+=c.length?"=":a.empty)):(b+=a.first,a.named&&(b+=a.encoder(e),b+=c.length?"=":a.empty)),b+=a.encoder(c)},""):"object"==typeof i?c+=Object.keys(i).reduce(function(b,c){return b.length?b+=g.explode?a.separator:",":(b+=a.first,a.named&&!g.explode&&(b+=a.encoder(e),b+=i[c].length?"=":a.empty)),b+=a.encoder(c),b+=g.explode?"=":",",b+=a.encoder(i[c])},""):(i=String(i),g.maxLength&&(i=i.slice(0,g.maxLength)),c+=c.length?a.separator:a.first,a.named&&(c+=a.encoder(e),c+=i.length?"=":a.empty),c+=a.encoder(i)),c)},"")}function d(a,b){var d;if(d=g[a.slice(0,1)],d?a=a.slice(1):d=g[""],d.reserved)throw new Error("Reserved expression operations are not supported");return c(d,a,b)}function e(a,b){var c,e,f;for(f="",e=0;;){if(c=a.indexOf("{",e),-1===c){f+=a.slice(e);break}f+=a.slice(e,c),e=a.indexOf("}",c)+1,f+=d(a.slice(c+1,e-1),b)}return f}var f,g,h;return f=a("./uriEncoder"),h=/^([^:]*):([0-9]+)$/,g={"":{first:"",separator:",",named:!1,empty:"",encoder:f.encode},"+":{first:"",separator:",",named:!1,empty:"",encoder:f.encodeURL},"#":{first:"#",separator:",",named:!1,empty:"",encoder:f.encodeURL},".":{first:".",separator:".",named:!1,empty:"",encoder:f.encode},"/":{first:"/",separator:"/",named:!1,empty:"",encoder:f.encode},";":{first:";",separator:";",named:!0,empty:"",encoder:f.encode},"?":{first:"?",separator:"&",named:!0,empty:"=",encoder:f.encode},"&":{first:"&",separator:"&",named:!0,empty:"=",encoder:f.encode},"=":{reserved:!0},",":{reserved:!0},"!":{reserved:!0},"@":{reserved:!0},"|":{reserved:!0}},{expand:e}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./uriEncoder":140}]},{},[1]); |
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | Digio86/artena | import React from 'react';
import { render } from 'react-dom';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
render(<HelloWorld />, document.getElementById('react-root'));
|
react-flux-mui/js/material-ui/src/svg-icons/editor/monetization-on.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorMonetizationOn = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1.41 16.09V20h-2.67v-1.93c-1.71-.36-3.16-1.46-3.27-3.4h1.96c.1 1.05.82 1.87 2.65 1.87 1.96 0 2.4-.98 2.4-1.59 0-.83-.44-1.61-2.67-2.14-2.48-.6-4.18-1.62-4.18-3.67 0-1.72 1.39-2.84 3.11-3.21V4h2.67v1.95c1.86.45 2.79 1.86 2.85 3.39H14.3c-.05-1.11-.64-1.87-2.22-1.87-1.5 0-2.4.68-2.4 1.64 0 .84.65 1.39 2.67 1.91s4.18 1.39 4.18 3.91c-.01 1.83-1.38 2.83-3.12 3.16z"/>
</SvgIcon>
);
EditorMonetizationOn = pure(EditorMonetizationOn);
EditorMonetizationOn.displayName = 'EditorMonetizationOn';
EditorMonetizationOn.muiName = 'SvgIcon';
export default EditorMonetizationOn;
|
RNTester/js/ClipboardExample.js | tszajna0/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @providesModule ClipboardExample
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Clipboard,
View,
Text,
} = ReactNative;
class ClipboardExample extends React.Component {
state = {
content: 'Content will appear here'
};
_setClipboardContent = async () => {
Clipboard.setString('Hello World');
try {
var content = await Clipboard.getString();
this.setState({content});
} catch (e) {
this.setState({content:e.message});
}
};
render() {
return (
<View>
<Text onPress={this._setClipboardContent} style={{color: 'blue'}}>
Tap to put "Hello World" in the clipboard
</Text>
<Text style={{color: 'red', marginTop: 20}}>
{this.state.content}
</Text>
</View>
);
}
}
exports.title = 'Clipboard';
exports.description = 'Show Clipboard contents.';
exports.examples = [
{
title: 'Clipboard.setString() and getString()',
render() {
return <ClipboardExample/>;
}
}
];
|
packages/material-ui-icons/src/LocalAtmRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 13c0 .55-.45 1-1 1H5c-.55 0-1-.45-1-1V7c0-.55.45-1 1-1h14c.55 0 1 .45 1 1v10z" /><path d="M14 10c.55 0 1-.45 1-1s-.45-1-1-1h-1v-.01c0-.55-.45-1-1-1s-1 .45-1 1V8h-1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1h3v1h-3c-.55 0-1 .45-1 1s.45 1 1 1h1c0 .55.45 1 1 1s1-.45 1-1h1c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1h-3v-1h3z" /></React.Fragment>
, 'LocalAtmRounded');
|
docs/app/Examples/views/Card/Types/index.js | shengnian/shengnian-ui-react | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const Types = () => (
<ExampleSection title='Types'>
<ComponentExample
title='Card'
description='A card displays site content in a manner similar to a playing card.'
examplePath='views/Card/Types/CardExampleCard'
/>
<ComponentExample
description='You can also use props to configure the markup.'
examplePath='views/Card/Types/CardExampleCardProps'
/>
<ComponentExample
title='Cards'
description='A group of cards.'
examplePath='views/Card/Types/CardExampleGroups'
/>
<ComponentExample
description='You can also use props to configure the markup.'
examplePath='views/Card/Types/CardExampleGroupProps'
/>
</ExampleSection>
)
export default Types
|
src/gm3/components/catalog/legend.js | geomoose/gm3 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 Dan 'Ducky' Little
*
* 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.
*/
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getLegend } from '../map';
import { isLayerOn } from '../../util';
class CatalogLegend extends Component {
constructor(props) {
super(props);
this.renderLegend = this.renderLegend.bind(this);
}
htmlLegend(html) {
return {__html: html};
}
renderLegend(src) {
const legend = getLegend(
this.props.mapSources[src.mapSourceName],
this.props.mapView,
src.layerName
);
const key = 'legend_' + src.mapSourceName + '_' + src.layerName;
let legend_idx = 0;
switch(legend.type) {
case 'html':
return (
<div
key={key}
className='legend-html'
dangerouslySetInnerHTML={this.htmlLegend(legend.html)}
/>
);
case 'img':
const img_tags = [];
legend_idx = 0;
for(const img_src of legend.images) {
img_tags.push((<img alt='layer legend' key={key + legend_idx} className='legend-image' src={img_src}/>));
legend_idx += 1;
}
return (<div key={key} className='legend-images'> { img_tags } </div>);
case 'nolegend':
default:
// no legend, no DOM'ing.
return false;
}
}
render() {
// check to see if there are any layers on in the
// map-source
const layer = this.props.layer;
// short the rendering a legend if the layer
// is not on.
if(!isLayerOn(this.props.mapSources, layer)) {
return false;
}
// put a legend on it.
return (<div className='catalog-legend'>
{ layer.src.map(this.renderLegend) }
</div>);
}
}
const mapCatalogToProps = function(store) {
return {
mapSources: store.mapSources,
mapView: store.map
}
}
export default connect(mapCatalogToProps)(CatalogLegend);
|
src/components/Menu/__tests__/MenuItem.spec.js | propertybase/react-lds | import React from 'react';
import { mount } from 'enzyme';
import MenuItem from '../MenuItem';
describe('<MenuItem />', () => {
let mounted = null;
beforeEach(() => {
mounted = mount(<MenuItem id="123">foobar</MenuItem>);
});
it('renders children, string or node', () => {
expect(mounted.find('li > a span').text()).toEqual('foobar');
mounted.setProps({ children: <p>1234</p> });
expect(mounted.find('li > a span').children().first().text())
.toBe('1234');
});
it('renders isSelected', () => {
mounted.setProps({ selected: true });
expect(mounted.find('li').hasClass('slds-is-selected')).toBeTruthy();
});
it('renders divider', () => {
mounted.setProps({ divider: true });
expect(mounted.find('li').hasClass('slds-has-divider_top-space')).toBeTruthy();
});
it('renders left and right icons', () => {
const icon = {
icon: 'unicorn',
sprite: 'rainbows',
};
mounted.setProps({
leftIcon: icon,
rightIcon: icon,
});
expect(mounted.find('li > a > span svg').exists()).toBeTruthy();
expect(mounted.find('li > a svg').length).toBe(2);
});
it('applies a title when set', () => {
const getTitle = () => mounted.find('a > span').prop('title');
expect(getTitle()).toEqual('foobar');
mounted.setProps({ children: <span>child</span> });
expect(getTitle()).toBeFalsy();
mounted.setProps({ title: 'foobaz' });
expect(getTitle()).toEqual('foobaz');
});
it('applies className and rest-properties', () => {
mounted.setProps({ className: 'foo', 'data-test': 'bar' });
expect(mounted.find('.slds-dropdown__item').hasClass('foo')).toBeTruthy();
expect(mounted.find('.slds-dropdown__item').prop('data-test')).toEqual('bar');
});
});
|
ajax/libs/react-native-web/0.13.15/cjs/exports/AppRegistry/renderApplication.min.js | cdnjs/cdnjs | "use strict";exports.__esModule=!0,exports.default=renderApplication,exports.getApplication=getApplication;var _AppContainer=_interopRequireDefault(require("./AppContainer")),_invariant=_interopRequireDefault(require("fbjs/lib/invariant")),_render=_interopRequireWildcard(require("../render")),_styleResolver=_interopRequireDefault(require("../StyleSheet/styleResolver")),_react=_interopRequireDefault(require("react"));function _getRequireWildcardCache(){if("function"!=typeof WeakMap)return null;var e=new WeakMap;return _getRequireWildcardCache=function(){return e},e}function _interopRequireWildcard(e){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache();if(t&&t.has(e))return t.get(e);var r,n={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&((r=a?Object.getOwnPropertyDescriptor(e,i):null)&&(r.get||r.set)?Object.defineProperty(n,i,r):n[i]=e[i])}return n.default=e,t&&t.set(e,n),n}function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _extends(){return(_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function renderApplication(e,t,r,n){var a=n.hydrate,i=n.initialProps,o=n.rootTag,l=a?_render.hydrate:_render.default;(0,_invariant.default)(o,"Expect to have a valid rootTag, instead got ",o),l(_react.default.createElement(_AppContainer.default,{rootTag:o,WrapperComponent:t},_react.default.createElement(e,i)),o,r)}function getApplication(e,t,r){return{element:_react.default.createElement(_AppContainer.default,{rootTag:{},WrapperComponent:r},_react.default.createElement(e,t)),getStyleElement:function(e){var t=_styleResolver.default.getStyleSheet();return _react.default.createElement("style",_extends({},e,{dangerouslySetInnerHTML:{__html:t.textContent},id:t.id}))}}} |
ajax/libs/vue/2.0.1/vue.common.js | honestree/cdnjs | 'use strict';
/* */
/**
* Convert a value to a string that is actually rendered.
*/
function _toString (val) {
return val == null
? ''
: typeof val === 'object'
? JSON.stringify(val, null, 2)
: String(val)
}
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
function toNumber (val) {
var n = parseFloat(val, 10)
return (n || n === 0) ? n : val
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
function makeMap (
str,
expectsLowerCase
) {
var map = Object.create(null)
var list = str.split(',')
for (var i = 0; i < list.length; i++) {
map[list[i]] = true
}
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
/**
* Check if a tag is a built-in tag.
*/
var isBuiltInTag = makeMap('slot,component', true)
/**
* Remove an item from an array
*/
function remove$1 (arr, item) {
if (arr.length) {
var index = arr.indexOf(item)
if (index > -1) {
return arr.splice(index, 1)
}
}
}
/**
* Check whether the object has the property.
*/
var hasOwnProperty = Object.prototype.hasOwnProperty
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
/**
* Check if value is primitive
*/
function isPrimitive (value) {
return typeof value === 'string' || typeof value === 'number'
}
/**
* Create a cached version of a pure function.
*/
function cached (fn) {
var cache = Object.create(null)
return function cachedFn (str) {
var hit = cache[str]
return hit || (cache[str] = fn(str))
}
}
/**
* Camelize a hyphen-delmited string.
*/
var camelizeRE = /-(\w)/g
var camelize = cached(function (str) {
return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
})
/**
* Capitalize a string.
*/
var capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
})
/**
* Hyphenate a camelCase string.
*/
var hyphenateRE = /([^-])([A-Z])/g
var hyphenate = cached(function (str) {
return str
.replace(hyphenateRE, '$1-$2')
.replace(hyphenateRE, '$1-$2')
.toLowerCase()
})
/**
* Simple bind, faster than native
*/
function bind$1 (fn, ctx) {
function boundFn (a) {
var l = arguments.length
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
// record original fn length
boundFn._length = fn.length
return boundFn
}
/**
* Convert an Array-like object to a real Array.
*/
function toArray (list, start) {
start = start || 0
var i = list.length - start
var ret = new Array(i)
while (i--) {
ret[i] = list[i + start]
}
return ret
}
/**
* Mix properties into target object.
*/
function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key]
}
return to
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
var toString = Object.prototype.toString
var OBJECT_STRING = '[object Object]'
function isPlainObject (obj) {
return toString.call(obj) === OBJECT_STRING
}
/**
* Merge an Array of Objects into a single Object.
*/
function toObject (arr) {
var res = {}
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i])
}
}
return res
}
/**
* Perform no operation.
*/
function noop () {}
/**
* Always return false.
*/
var no = function () { return false; }
/**
* Generate a static keys string from compiler modules.
*/
function genStaticKeys (modules) {
return modules.reduce(function (keys, m) {
return keys.concat(m.staticKeys || [])
}, []).join(',')
}
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/
function looseEqual (a, b) {
/* eslint-disable eqeqeq */
return a == b || (
isObject(a) && isObject(b)
? JSON.stringify(a) === JSON.stringify(b)
: false
)
/* eslint-enable eqeqeq */
}
function looseIndexOf (arr, val) {
for (var i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) { return i }
}
return -1
}
/* */
var config = {
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Whether to enable devtools
*/
devtools: process.env.NODE_ENV !== 'production',
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: null,
/**
* Custom user key aliases for v-on
*/
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* List of asset types that a component can own.
*/
_assetTypes: [
'component',
'directive',
'filter'
],
/**
* List of lifecycle hooks.
*/
_lifecycleHooks: [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated'
],
/**
* Max circular updates allowed in a scheduler flush cycle.
*/
_maxUpdateCount: 100,
/**
* Server rendering?
*/
_isServer: process.env.VUE_ENV === 'server'
}
/* */
/**
* Check if a string starts with $ or _
*/
function isReserved (str) {
var c = (str + '').charCodeAt(0)
return c === 0x24 || c === 0x5F
}
/**
* Define a property.
*/
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
})
}
/**
* Parse simple path.
*/
var bailRE = /[^\w\.\$]/
function parsePath (path) {
if (bailRE.test(path)) {
return
} else {
var segments = path.split('.')
return function (obj) {
for (var i = 0; i < segments.length; i++) {
if (!obj) { return }
obj = obj[segments[i]]
}
return obj
}
}
}
/* */
/* globals MutationObserver */
// can we use __proto__?
var hasProto = '__proto__' in {}
// Browser environment sniffing
var inBrowser =
typeof window !== 'undefined' &&
Object.prototype.toString.call(window) !== '[object Object]'
var UA = inBrowser && window.navigator.userAgent.toLowerCase()
var isIE = UA && /msie|trident/.test(UA)
var isIE9 = UA && UA.indexOf('msie 9.0') > 0
var isEdge = UA && UA.indexOf('edge/') > 0
var isAndroid = UA && UA.indexOf('android') > 0
var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA)
// detect devtools
var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__
/* istanbul ignore next */
function isNative (Ctor) {
return /native code/.test(Ctor.toString())
}
/**
* Defer a task to execute it asynchronously.
*/
var nextTick = (function () {
var callbacks = []
var pending = false
var timerFunc
function nextTickHandler () {
pending = false
var copies = callbacks.slice(0)
callbacks.length = 0
for (var i = 0; i < copies.length; i++) {
copies[i]()
}
}
// the nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore if */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve()
timerFunc = function () {
p.then(nextTickHandler)
// in problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) { setTimeout(noop) }
}
} else if (typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// use MutationObserver where native Promise is not available,
// e.g. PhantomJS IE11, iOS7, Android 4.4
var counter = 1
var observer = new MutationObserver(nextTickHandler)
var textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = function () {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
} else {
// fallback to setTimeout
/* istanbul ignore next */
timerFunc = setTimeout
}
return function queueNextTick (cb, ctx) {
var func = ctx
? function () { cb.call(ctx) }
: cb
callbacks.push(func)
if (!pending) {
pending = true
timerFunc(nextTickHandler, 0)
}
}
})()
var _Set
/* istanbul ignore if */
if (typeof Set !== 'undefined' && isNative(Set)) {
// use native Set when available.
_Set = Set
} else {
// a non-standard Set polyfill that only works with primitive keys.
_Set = (function () {
function Set () {
this.set = Object.create(null)
}
Set.prototype.has = function has (key) {
return this.set[key] !== undefined
};
Set.prototype.add = function add (key) {
this.set[key] = 1
};
Set.prototype.clear = function clear () {
this.set = Object.create(null)
};
return Set;
}())
}
/* not type checking this file because flow doesn't play well with Proxy */
var hasProxy;
var proxyHandlers;
var initProxy
if (process.env.NODE_ENV !== 'production') {
var allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
)
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/)
proxyHandlers = {
has: function has (target, key) {
var has = key in target
var isAllowed = allowedGlobals(key) || key.charAt(0) === '_'
if (!has && !isAllowed) {
warn(
"Property or method \"" + key + "\" is not defined on the instance but " +
"referenced during render. Make sure to declare reactive data " +
"properties in the data option.",
target
)
}
return has || !isAllowed
}
}
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers)
} else {
vm._renderProxy = vm
}
}
}
/* */
var uid$2 = 0
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
var Dep = function Dep () {
this.id = uid$2++
this.subs = []
};
Dep.prototype.addSub = function addSub (sub) {
this.subs.push(sub)
};
Dep.prototype.removeSub = function removeSub (sub) {
remove$1(this.subs, sub)
};
Dep.prototype.depend = function depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
};
Dep.prototype.notify = function notify () {
// stablize the subscriber list first
var subs = this.subs.slice()
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
};
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null
var targetStack = []
function pushTarget (_target) {
if (Dep.target) { targetStack.push(Dep.target) }
Dep.target = _target
}
function popTarget () {
Dep.target = targetStack.pop()
}
/* */
var queue = []
var has$1 = {}
var circular = {}
var waiting = false
var flushing = false
var index = 0
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
queue.length = 0
has$1 = {}
if (process.env.NODE_ENV !== 'production') {
circular = {}
}
waiting = flushing = false
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
flushing = true
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort(function (a, b) { return a.id - b.id; })
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
var watcher = queue[index]
var id = watcher.id
has$1[id] = null
watcher.run()
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && has$1[id] != null) {
circular[id] = (circular[id] || 0) + 1
if (circular[id] > config._maxUpdateCount) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? ("in watcher with expression \"" + (watcher.expression) + "\"")
: "in a component render function."
),
watcher.vm
)
break
}
}
}
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush')
}
resetSchedulerState()
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
function queueWatcher (watcher) {
var id = watcher.id
if (has$1[id] == null) {
has$1[id] = true
if (!flushing) {
queue.push(watcher)
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
var i = queue.length - 1
while (i >= 0 && queue[i].id > watcher.id) {
i--
}
queue.splice(Math.max(i, index) + 1, 0, watcher)
}
// queue the flush
if (!waiting) {
waiting = true
nextTick(flushSchedulerQueue)
}
}
}
/* */
var uid$1 = 0
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
var Watcher = function Watcher (
vm,
expOrFn,
cb,
options
) {
if ( options === void 0 ) options = {};
this.vm = vm
vm._watchers.push(this)
// options
this.deep = !!options.deep
this.user = !!options.user
this.lazy = !!options.lazy
this.sync = !!options.sync
this.expression = expOrFn.toString()
this.cb = cb
this.id = ++uid$1 // uid for batching
this.active = true
this.dirty = this.lazy // for lazy watchers
this.deps = []
this.newDeps = []
this.depIds = new _Set()
this.newDepIds = new _Set()
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = function () {}
process.env.NODE_ENV !== 'production' && warn(
"Failed watching path: \"" + expOrFn + "\" " +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
)
}
}
this.value = this.lazy
? undefined
: this.get()
};
/**
* Evaluate the getter, and re-collect dependencies.
*/
Watcher.prototype.get = function get () {
pushTarget(this)
var value = this.getter.call(this.vm, this.vm)
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
return value
};
/**
* Add a dependency to this directive.
*/
Watcher.prototype.addDep = function addDep (dep) {
var id = dep.id
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
dep.addSub(this)
}
}
};
/**
* Clean up for dependency collection.
*/
Watcher.prototype.cleanupDeps = function cleanupDeps () {
var this$1 = this;
var i = this.deps.length
while (i--) {
var dep = this$1.deps[i]
if (!this$1.newDepIds.has(dep.id)) {
dep.removeSub(this$1)
}
}
var tmp = this.depIds
this.depIds = this.newDepIds
this.newDepIds = tmp
this.newDepIds.clear()
tmp = this.deps
this.deps = this.newDeps
this.newDeps = tmp
this.newDeps.length = 0
};
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
Watcher.prototype.update = function update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
};
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
Watcher.prototype.run = function run () {
if (this.active) {
var value = this.get()
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
var oldValue = this.value
this.value = value
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue)
} catch (e) {
process.env.NODE_ENV !== 'production' && warn(
("Error in watcher \"" + (this.expression) + "\""),
this.vm
)
/* istanbul ignore else */
if (config.errorHandler) {
config.errorHandler.call(null, e, this.vm)
} else {
throw e
}
}
} else {
this.cb.call(this.vm, value, oldValue)
}
}
}
};
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
Watcher.prototype.evaluate = function evaluate () {
this.value = this.get()
this.dirty = false
};
/**
* Depend on all deps collected by this watcher.
*/
Watcher.prototype.depend = function depend () {
var this$1 = this;
var i = this.deps.length
while (i--) {
this$1.deps[i].depend()
}
};
/**
* Remove self from all dependencies' subcriber list.
*/
Watcher.prototype.teardown = function teardown () {
var this$1 = this;
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed or is performing a v-for
// re-render (the watcher list is then filtered by v-for).
if (!this.vm._isBeingDestroyed && !this.vm._vForRemoving) {
remove$1(this.vm._watchers, this)
}
var i = this.deps.length
while (i--) {
this$1.deps[i].removeSub(this$1)
}
this.active = false
}
};
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
var seenObjects = new _Set()
function traverse (val, seen) {
var i, keys
if (!seen) {
seen = seenObjects
seen.clear()
}
var isA = Array.isArray(val)
var isO = isObject(val)
if ((isA || isO) && Object.isExtensible(val)) {
if (val.__ob__) {
var depId = val.__ob__.dep.id
if (seen.has(depId)) {
return
} else {
seen.add(depId)
}
}
if (isA) {
i = val.length
while (i--) { traverse(val[i], seen) }
} else if (isO) {
keys = Object.keys(val)
i = keys.length
while (i--) { traverse(val[keys[i]], seen) }
}
}
}
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
var arrayProto = Array.prototype
var arrayMethods = Object.create(arrayProto);[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// cache original method
var original = arrayProto[method]
def(arrayMethods, method, function mutator () {
var arguments$1 = arguments;
// avoid leaking arguments:
// http://jsperf.com/closure-with-arguments
var i = arguments.length
var args = new Array(i)
while (i--) {
args[i] = arguments$1[i]
}
var result = original.apply(this, args)
var ob = this.__ob__
var inserted
switch (method) {
case 'push':
inserted = args
break
case 'unshift':
inserted = args
break
case 'splice':
inserted = args.slice(2)
break
}
if (inserted) { ob.observeArray(inserted) }
// notify change
ob.dep.notify()
return result
})
})
/* */
var arrayKeys = Object.getOwnPropertyNames(arrayMethods)
/**
* By default, when a reactive property is set, the new value is
* also converted to become reactive. However when passing down props,
* we don't want to force conversion because the value may be a nested value
* under a frozen data structure. Converting it would defeat the optimization.
*/
var observerState = {
shouldConvert: true,
isSettingProps: false
}
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*/
var Observer = function Observer (value) {
this.value = value
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
if (Array.isArray(value)) {
var augment = hasProto
? protoAugment
: copyAugment
augment(value, arrayMethods, arrayKeys)
this.observeArray(value)
} else {
this.walk(value)
}
};
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
Observer.prototype.walk = function walk (obj) {
var keys = Object.keys(obj)
for (var i = 0; i < keys.length; i++) {
defineReactive$$1(obj, keys[i], obj[keys[i]])
}
};
/**
* Observe a list of Array items.
*/
Observer.prototype.observeArray = function observeArray (items) {
for (var i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
};
// helpers
/**
* Augment an target Object or Array by intercepting
* the prototype chain using __proto__
*/
function protoAugment (target, src) {
/* eslint-disable no-proto */
target.__proto__ = src
/* eslint-enable no-proto */
}
/**
* Augment an target Object or Array by defining
* hidden properties.
*
* istanbul ignore next
*/
function copyAugment (target, src, keys) {
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i]
def(target, key, src[key])
}
}
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
function observe (value) {
if (!isObject(value)) {
return
}
var ob
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__
} else if (
observerState.shouldConvert &&
!config._isServer &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
return ob
}
/**
* Define a reactive property on an Object.
*/
function defineReactive$$1 (
obj,
key,
val,
customSetter
) {
var dep = new Dep()
var property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
var getter = property && property.get
var setter = property && property.set
var childOb = observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
var value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
}
if (Array.isArray(value)) {
for (var e = void 0, i = 0, l = value.length; i < l; i++) {
e = value[i]
e && e.__ob__ && e.__ob__.dep.depend()
}
}
}
return value
},
set: function reactiveSetter (newVal) {
var value = getter ? getter.call(obj) : val
if (newVal === value) {
return
}
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = observe(newVal)
dep.notify()
}
})
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
function set (obj, key, val) {
if (Array.isArray(obj)) {
obj.splice(key, 1, val)
return val
}
if (hasOwn(obj, key)) {
obj[key] = val
return
}
var ob = obj.__ob__
if (obj._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
)
return
}
if (!ob) {
obj[key] = val
return
}
defineReactive$$1(ob.value, key, val)
ob.dep.notify()
return val
}
/**
* Delete a property and trigger change if necessary.
*/
function del (obj, key) {
var ob = obj.__ob__
if (obj._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
)
return
}
if (!hasOwn(obj, key)) {
return
}
delete obj[key]
if (!ob) {
return
}
ob.dep.notify()
}
/* */
function initState (vm) {
vm._watchers = []
initProps(vm)
initData(vm)
initComputed(vm)
initMethods(vm)
initWatch(vm)
}
function initProps (vm) {
var props = vm.$options.props
if (props) {
var propsData = vm.$options.propsData || {}
var keys = vm.$options._propKeys = Object.keys(props)
var isRoot = !vm.$parent
// root instance props should be converted
observerState.shouldConvert = isRoot
var loop = function ( i ) {
var key = keys[i]
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
defineReactive$$1(vm, key, validateProp(key, props, propsData, vm), function () {
if (vm.$parent && !observerState.isSettingProps) {
warn(
"Avoid mutating a prop directly since the value will be " +
"overwritten whenever the parent component re-renders. " +
"Instead, use a data or computed property based on the prop's " +
"value. Prop being mutated: \"" + key + "\"",
vm
)
}
})
} else {
defineReactive$$1(vm, key, validateProp(key, props, propsData, vm))
}
};
for (var i = 0; i < keys.length; i++) loop( i );
observerState.shouldConvert = true
}
}
function initData (vm) {
var data = vm.$options.data
data = vm._data = typeof data === 'function'
? data.call(vm)
: data || {}
if (!isPlainObject(data)) {
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object.',
vm
)
}
// proxy data on instance
var keys = Object.keys(data)
var props = vm.$options.props
var i = keys.length
while (i--) {
if (props && hasOwn(props, keys[i])) {
process.env.NODE_ENV !== 'production' && warn(
"The data property \"" + (keys[i]) + "\" is already declared as a prop. " +
"Use prop default value instead.",
vm
)
} else {
proxy(vm, keys[i])
}
}
// observe data
observe(data)
data.__ob__ && data.__ob__.vmCount++
}
var computedSharedDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
}
function initComputed (vm) {
var computed = vm.$options.computed
if (computed) {
for (var key in computed) {
var userDef = computed[key]
if (typeof userDef === 'function') {
computedSharedDefinition.get = makeComputedGetter(userDef, vm)
computedSharedDefinition.set = noop
} else {
computedSharedDefinition.get = userDef.get
? userDef.cache !== false
? makeComputedGetter(userDef.get, vm)
: bind$1(userDef.get, vm)
: noop
computedSharedDefinition.set = userDef.set
? bind$1(userDef.set, vm)
: noop
}
Object.defineProperty(vm, key, computedSharedDefinition)
}
}
}
function makeComputedGetter (getter, owner) {
var watcher = new Watcher(owner, getter, noop, {
lazy: true
})
return function computedGetter () {
if (watcher.dirty) {
watcher.evaluate()
}
if (Dep.target) {
watcher.depend()
}
return watcher.value
}
}
function initMethods (vm) {
var methods = vm.$options.methods
if (methods) {
for (var key in methods) {
if (methods[key] != null) {
vm[key] = bind$1(methods[key], vm)
} else if (process.env.NODE_ENV !== 'production') {
warn(("Method \"" + key + "\" is undefined in options."), vm)
}
}
}
}
function initWatch (vm) {
var watch = vm.$options.watch
if (watch) {
for (var key in watch) {
var handler = watch[key]
if (Array.isArray(handler)) {
for (var i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i])
}
} else {
createWatcher(vm, key, handler)
}
}
}
}
function createWatcher (vm, key, handler) {
var options
if (isPlainObject(handler)) {
options = handler
handler = handler.handler
}
if (typeof handler === 'string') {
handler = vm[handler]
}
vm.$watch(key, handler, options)
}
function stateMixin (Vue) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
var dataDef = {}
dataDef.get = function () {
return this._data
}
if (process.env.NODE_ENV !== 'production') {
dataDef.set = function (newData) {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
)
}
}
Object.defineProperty(Vue.prototype, '$data', dataDef)
Vue.prototype.$set = set
Vue.prototype.$delete = del
Vue.prototype.$watch = function (
expOrFn,
cb,
options
) {
var vm = this
options = options || {}
options.user = true
var watcher = new Watcher(vm, expOrFn, cb, options)
if (options.immediate) {
cb.call(vm, watcher.value)
}
return function unwatchFn () {
watcher.teardown()
}
}
}
function proxy (vm, key) {
if (!isReserved(key)) {
Object.defineProperty(vm, key, {
configurable: true,
enumerable: true,
get: function proxyGetter () {
return vm._data[key]
},
set: function proxySetter (val) {
vm._data[key] = val
}
})
}
}
/* */
var VNode = function VNode (
tag,
data,
children,
text,
elm,
ns,
context,
componentOptions
) {
this.tag = tag
this.data = data
this.children = children
this.text = text
this.elm = elm
this.ns = ns
this.context = context
this.key = data && data.key
this.componentOptions = componentOptions
this.child = undefined
this.parent = undefined
this.raw = false
this.isStatic = false
this.isRootInsert = true
this.isComment = false
this.isCloned = false
};
var emptyVNode = function () {
var node = new VNode()
node.text = ''
node.isComment = true
return node
}
// optimized shallow clone
// used for static nodes and slot nodes because they may be reused across
// multiple renders, cloning them avoids errors when DOM manipulations rely
// on their elm reference.
function cloneVNode (vnode) {
var cloned = new VNode(
vnode.tag,
vnode.data,
vnode.children,
vnode.text,
vnode.elm,
vnode.ns,
vnode.context,
vnode.componentOptions
)
cloned.isStatic = vnode.isStatic
cloned.key = vnode.key
cloned.isCloned = true
return cloned
}
function cloneVNodes (vnodes) {
var res = new Array(vnodes.length)
for (var i = 0; i < vnodes.length; i++) {
res[i] = cloneVNode(vnodes[i])
}
return res
}
/* */
function normalizeChildren (
children,
ns,
nestedIndex
) {
if (isPrimitive(children)) {
return [createTextVNode(children)]
}
if (Array.isArray(children)) {
var res = []
for (var i = 0, l = children.length; i < l; i++) {
var c = children[i]
var last = res[res.length - 1]
// nested
if (Array.isArray(c)) {
res.push.apply(res, normalizeChildren(c, ns, i))
} else if (isPrimitive(c)) {
if (last && last.text) {
last.text += String(c)
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c))
}
} else if (c instanceof VNode) {
if (c.text && last && last.text) {
last.text += c.text
} else {
// inherit parent namespace
if (ns) {
applyNS(c, ns)
}
// default key for nested array children (likely generated by v-for)
if (c.tag && c.key == null && nestedIndex != null) {
c.key = "__vlist_" + nestedIndex + "_" + i + "__"
}
res.push(c)
}
}
}
return res
}
}
function createTextVNode (val) {
return new VNode(undefined, undefined, undefined, String(val))
}
function applyNS (vnode, ns) {
if (vnode.tag && !vnode.ns) {
vnode.ns = ns
if (vnode.children) {
for (var i = 0, l = vnode.children.length; i < l; i++) {
applyNS(vnode.children[i], ns)
}
}
}
}
function getFirstComponentChild (children) {
return children && children.filter(function (c) { return c && c.componentOptions; })[0]
}
function mergeVNodeHook (def$$1, key, hook) {
var oldHook = def$$1[key]
if (oldHook) {
var injectedHash = def$$1.__injected || (def$$1.__injected = {})
if (!injectedHash[key]) {
injectedHash[key] = true
def$$1[key] = function () {
oldHook.apply(this, arguments)
hook.apply(this, arguments)
}
}
} else {
def$$1[key] = hook
}
}
function updateListeners (
on,
oldOn,
add,
remove$$1
) {
var name, cur, old, fn, event, capture
for (name in on) {
cur = on[name]
old = oldOn[name]
if (!cur) {
process.env.NODE_ENV !== 'production' && warn(
("Handler for event \"" + name + "\" is undefined.")
)
} else if (!old) {
capture = name.charAt(0) === '!'
event = capture ? name.slice(1) : name
if (Array.isArray(cur)) {
add(event, (cur.invoker = arrInvoker(cur)), capture)
} else {
if (!cur.invoker) {
fn = cur
cur = on[name] = {}
cur.fn = fn
cur.invoker = fnInvoker(cur)
}
add(event, cur.invoker, capture)
}
} else if (cur !== old) {
if (Array.isArray(old)) {
old.length = cur.length
for (var i = 0; i < old.length; i++) { old[i] = cur[i] }
on[name] = old
} else {
old.fn = cur
on[name] = old
}
}
}
for (name in oldOn) {
if (!on[name]) {
event = name.charAt(0) === '!' ? name.slice(1) : name
remove$$1(event, oldOn[name].invoker)
}
}
}
function arrInvoker (arr) {
return function (ev) {
var arguments$1 = arguments;
var single = arguments.length === 1
for (var i = 0; i < arr.length; i++) {
single ? arr[i](ev) : arr[i].apply(null, arguments$1)
}
}
}
function fnInvoker (o) {
return function (ev) {
var single = arguments.length === 1
single ? o.fn(ev) : o.fn.apply(null, arguments)
}
}
/* */
var activeInstance = null
function initLifecycle (vm) {
var options = vm.$options
// locate first non-abstract parent
var parent = options.parent
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent
}
parent.$children.push(vm)
}
vm.$parent = parent
vm.$root = parent ? parent.$root : vm
vm.$children = []
vm.$refs = {}
vm._watcher = null
vm._inactive = false
vm._isMounted = false
vm._isDestroyed = false
vm._isBeingDestroyed = false
}
function lifecycleMixin (Vue) {
Vue.prototype._mount = function (
el,
hydrating
) {
var vm = this
vm.$el = el
if (!vm.$options.render) {
vm.$options.render = emptyVNode
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
if (vm.$options.template) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'option is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
)
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
)
}
}
}
callHook(vm, 'beforeMount')
vm._watcher = new Watcher(vm, function () {
vm._update(vm._render(), hydrating)
}, noop)
hydrating = false
// root instance, call mounted on self
// mounted is called for child components in its inserted hook
if (vm.$root === vm) {
vm._isMounted = true
callHook(vm, 'mounted')
}
return vm
}
Vue.prototype._update = function (vnode, hydrating) {
var vm = this
if (vm._isMounted) {
callHook(vm, 'beforeUpdate')
}
var prevEl = vm.$el
var prevActiveInstance = activeInstance
activeInstance = vm
var prevVnode = vm._vnode
vm._vnode = vnode
if (!prevVnode) {
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
vm.$el = vm.__patch__(vm.$el, vnode, hydrating)
} else {
vm.$el = vm.__patch__(prevVnode, vnode)
}
activeInstance = prevActiveInstance
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null
}
if (vm.$el) {
vm.$el.__vue__ = vm
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el
}
if (vm._isMounted) {
callHook(vm, 'updated')
}
}
Vue.prototype._updateFromParent = function (
propsData,
listeners,
parentVnode,
renderChildren
) {
var vm = this
var hasChildren = !!(vm.$options._renderChildren || renderChildren)
vm.$options._parentVnode = parentVnode
vm.$options._renderChildren = renderChildren
// update props
if (propsData && vm.$options.props) {
observerState.shouldConvert = false
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = true
}
var propKeys = vm.$options._propKeys || []
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i]
vm[key] = validateProp(key, vm.$options.props, propsData, vm)
}
observerState.shouldConvert = true
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = false
}
}
// update listeners
if (listeners) {
var oldListeners = vm.$options._parentListeners
vm.$options._parentListeners = listeners
vm._updateListeners(listeners, oldListeners)
}
// resolve slots + force update if has children
if (hasChildren) {
vm.$slots = resolveSlots(renderChildren, vm._renderContext)
vm.$forceUpdate()
}
}
Vue.prototype.$forceUpdate = function () {
var vm = this
if (vm._watcher) {
vm._watcher.update()
}
}
Vue.prototype.$destroy = function () {
var vm = this
if (vm._isBeingDestroyed) {
return
}
callHook(vm, 'beforeDestroy')
vm._isBeingDestroyed = true
// remove self from parent
var parent = vm.$parent
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
remove$1(parent.$children, vm)
}
// teardown watchers
if (vm._watcher) {
vm._watcher.teardown()
}
var i = vm._watchers.length
while (i--) {
vm._watchers[i].teardown()
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
vm._data.__ob__.vmCount--
}
// call the last hook...
vm._isDestroyed = true
callHook(vm, 'destroyed')
// turn off all instance listeners.
vm.$off()
// remove __vue__ reference
if (vm.$el) {
vm.$el.__vue__ = null
}
}
}
function callHook (vm, hook) {
var handlers = vm.$options[hook]
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
handlers[i].call(vm)
}
}
vm.$emit('hook:' + hook)
}
/* */
var hooks = { init: init, prepatch: prepatch, insert: insert, destroy: destroy$1 }
var hooksToMerge = Object.keys(hooks)
function createComponent (
Ctor,
data,
context,
children,
tag
) {
if (!Ctor) {
return
}
if (isObject(Ctor)) {
Ctor = Vue$2.extend(Ctor)
}
if (typeof Ctor !== 'function') {
if (process.env.NODE_ENV !== 'production') {
warn(("Invalid Component definition: " + (String(Ctor))), context)
}
return
}
// async component
if (!Ctor.cid) {
if (Ctor.resolved) {
Ctor = Ctor.resolved
} else {
Ctor = resolveAsyncComponent(Ctor, function () {
// it's ok to queue this on every render because
// $forceUpdate is buffered by the scheduler.
context.$forceUpdate()
})
if (!Ctor) {
// return nothing if this is indeed an async component
// wait for the callback to trigger parent update.
return
}
}
}
data = data || {}
// extract props
var propsData = extractProps(data, Ctor)
// functional component
if (Ctor.options.functional) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
var listeners = data.on
// replace with listeners with .native modifier
data.on = data.nativeOn
if (Ctor.options.abstract) {
// abstract components do not keep anything
// other than props & listeners
data = {}
}
// merge component management hooks onto the placeholder node
mergeHooks(data)
// return a placeholder vnode
var name = Ctor.options.name || tag
var vnode = new VNode(
("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
data, undefined, undefined, undefined, undefined, context,
{ Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }
)
return vnode
}
function createFunctionalComponent (
Ctor,
propsData,
data,
context,
children
) {
var props = {}
var propOptions = Ctor.options.props
if (propOptions) {
for (var key in propOptions) {
props[key] = validateProp(key, propOptions, propsData)
}
}
return Ctor.options.render.call(
null,
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
bind$1(createElement, { _self: Object.create(context) }),
{
props: props,
data: data,
parent: context,
children: normalizeChildren(children),
slots: function () { return resolveSlots(children, context); }
}
)
}
function createComponentInstanceForVnode (
vnode, // we know it's MountedComponentVNode but flow doesn't
parent // activeInstance in lifecycle state
) {
var vnodeComponentOptions = vnode.componentOptions
var options = {
_isComponent: true,
parent: parent,
propsData: vnodeComponentOptions.propsData,
_componentTag: vnodeComponentOptions.tag,
_parentVnode: vnode,
_parentListeners: vnodeComponentOptions.listeners,
_renderChildren: vnodeComponentOptions.children
}
// check inline-template render functions
var inlineTemplate = vnode.data.inlineTemplate
if (inlineTemplate) {
options.render = inlineTemplate.render
options.staticRenderFns = inlineTemplate.staticRenderFns
}
return new vnodeComponentOptions.Ctor(options)
}
function init (vnode, hydrating) {
if (!vnode.child || vnode.child._isDestroyed) {
var child = vnode.child = createComponentInstanceForVnode(vnode, activeInstance)
child.$mount(hydrating ? vnode.elm : undefined, hydrating)
}
}
function prepatch (
oldVnode,
vnode
) {
var options = vnode.componentOptions
var child = vnode.child = oldVnode.child
child._updateFromParent(
options.propsData, // updated props
options.listeners, // updated listeners
vnode, // new parent vnode
options.children // new children
)
}
function insert (vnode) {
if (!vnode.child._isMounted) {
vnode.child._isMounted = true
callHook(vnode.child, 'mounted')
}
if (vnode.data.keepAlive) {
vnode.child._inactive = false
callHook(vnode.child, 'activated')
}
}
function destroy$1 (vnode) {
if (!vnode.child._isDestroyed) {
if (!vnode.data.keepAlive) {
vnode.child.$destroy()
} else {
vnode.child._inactive = true
callHook(vnode.child, 'deactivated')
}
}
}
function resolveAsyncComponent (
factory,
cb
) {
if (factory.requested) {
// pool callbacks
factory.pendingCallbacks.push(cb)
} else {
factory.requested = true
var cbs = factory.pendingCallbacks = [cb]
var sync = true
var resolve = function (res) {
if (isObject(res)) {
res = Vue$2.extend(res)
}
// cache resolved
factory.resolved = res
// invoke callbacks only if this is not a synchronous resolve
// (async resolves are shimmed as synchronous during SSR)
if (!sync) {
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i](res)
}
}
}
var reject = function (reason) {
process.env.NODE_ENV !== 'production' && warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
)
}
var res = factory(resolve, reject)
// handle promise
if (res && typeof res.then === 'function' && !factory.resolved) {
res.then(resolve, reject)
}
sync = false
// return in case resolved synchronously
return factory.resolved
}
}
function extractProps (data, Ctor) {
// we are only extrating raw values here.
// validation and default values are handled in the child
// component itself.
var propOptions = Ctor.options.props
if (!propOptions) {
return
}
var res = {}
var attrs = data.attrs;
var props = data.props;
var domProps = data.domProps;
if (attrs || props || domProps) {
for (var key in propOptions) {
var altKey = hyphenate(key)
checkProp(res, props, key, altKey, true) ||
checkProp(res, attrs, key, altKey) ||
checkProp(res, domProps, key, altKey)
}
}
return res
}
function checkProp (
res,
hash,
key,
altKey,
preserve
) {
if (hash) {
if (hasOwn(hash, key)) {
res[key] = hash[key]
if (!preserve) {
delete hash[key]
}
return true
} else if (hasOwn(hash, altKey)) {
res[key] = hash[altKey]
if (!preserve) {
delete hash[altKey]
}
return true
}
}
return false
}
function mergeHooks (data) {
if (!data.hook) {
data.hook = {}
}
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i]
var fromParent = data.hook[key]
var ours = hooks[key]
data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours
}
}
function mergeHook$1 (a, b) {
// since all hooks have at most two args, use fixed args
// to avoid having to use fn.apply().
return function (_, __) {
a(_, __)
b(_, __)
}
}
/* */
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
function createElement (
tag,
data,
children
) {
if (data && (Array.isArray(data) || typeof data !== 'object')) {
children = data
data = undefined
}
// make sure to use real instance instead of proxy as context
return _createElement(this._self, tag, data, children)
}
function _createElement (
context,
tag,
data,
children
) {
if (data && data.__ob__) {
process.env.NODE_ENV !== 'production' && warn(
"Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" +
'Always create fresh vnode data objects in each render!',
context
)
return
}
if (!tag) {
// in case of component :is set to falsy value
return emptyVNode()
}
if (typeof tag === 'string') {
var Ctor
var ns = config.getTagNamespace(tag)
if (config.isReservedTag(tag)) {
// platform built-in elements
return new VNode(
tag, data, normalizeChildren(children, ns),
undefined, undefined, ns, context
)
} else if ((Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
return createComponent(Ctor, data, context, children, tag)
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
return new VNode(
tag, data, normalizeChildren(children, ns),
undefined, undefined, ns, context
)
}
} else {
// direct component options / constructor
return createComponent(tag, data, context, children)
}
}
/* */
function initRender (vm) {
vm.$vnode = null // the placeholder node in parent tree
vm._vnode = null // the root of the child tree
vm._staticTrees = null
vm._renderContext = vm.$options._parentVnode && vm.$options._parentVnode.context
vm.$slots = resolveSlots(vm.$options._renderChildren, vm._renderContext)
// bind the public createElement fn to this instance
// so that we get proper render context inside it.
vm.$createElement = bind$1(createElement, vm)
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
}
function renderMixin (Vue) {
Vue.prototype.$nextTick = function (fn) {
nextTick(fn, this)
}
Vue.prototype._render = function () {
var vm = this
var ref = vm.$options;
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
var _parentVnode = ref._parentVnode;
if (vm._isMounted) {
// clone slot nodes on re-renders
for (var key in vm.$slots) {
vm.$slots[key] = cloneVNodes(vm.$slots[key])
}
}
if (staticRenderFns && !vm._staticTrees) {
vm._staticTrees = []
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode
// render self
var vnode
try {
vnode = render.call(vm._renderProxy, vm.$createElement)
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
warn(("Error when rendering " + (formatComponentName(vm)) + ":"))
}
/* istanbul ignore else */
if (config.errorHandler) {
config.errorHandler.call(null, e, vm)
} else {
if (config._isServer) {
throw e
} else {
setTimeout(function () { throw e }, 0)
}
}
// return previous vnode to prevent render error causing blank component
vnode = vm._vnode
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
)
}
vnode = emptyVNode()
}
// set parent
vnode.parent = _parentVnode
return vnode
}
// shorthands used in render functions
Vue.prototype._h = createElement
// toString for mustaches
Vue.prototype._s = _toString
// number conversion
Vue.prototype._n = toNumber
// empty vnode
Vue.prototype._e = emptyVNode
// loose equal
Vue.prototype._q = looseEqual
// loose indexOf
Vue.prototype._i = looseIndexOf
// render static tree by index
Vue.prototype._m = function renderStatic (
index,
isInFor
) {
var tree = this._staticTrees[index]
// if has already-rendered static tree and not inside v-for,
// we can reuse the same tree by doing a shallow clone.
if (tree && !isInFor) {
return Array.isArray(tree)
? cloneVNodes(tree)
: cloneVNode(tree)
}
// otherwise, render a fresh tree.
tree = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy)
if (Array.isArray(tree)) {
for (var i = 0; i < tree.length; i++) {
tree[i].isStatic = true
tree[i].key = "__static__" + index + "_" + i
}
} else {
tree.isStatic = true
tree.key = "__static__" + index
}
return tree
}
// filter resolution helper
var identity = function (_) { return _; }
Vue.prototype._f = function resolveFilter (id) {
return resolveAsset(this.$options, 'filters', id, true) || identity
}
// render v-for
Vue.prototype._l = function renderList (
val,
render
) {
var ret, i, l, keys, key
if (Array.isArray(val)) {
ret = new Array(val.length)
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i)
}
} else if (typeof val === 'number') {
ret = new Array(val)
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i)
}
} else if (isObject(val)) {
keys = Object.keys(val)
ret = new Array(keys.length)
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i]
ret[i] = render(val[key], key, i)
}
}
return ret
}
// renderSlot
Vue.prototype._t = function (
name,
fallback
) {
var slotNodes = this.$slots[name]
// warn duplicate slot usage
if (slotNodes && process.env.NODE_ENV !== 'production') {
slotNodes._rendered && warn(
"Duplicate presence of slot \"" + name + "\" found in the same render tree " +
"- this will likely cause render errors.",
this
)
slotNodes._rendered = true
}
return slotNodes || fallback
}
// apply v-bind object
Vue.prototype._b = function bindProps (
data,
value,
asProp
) {
if (value) {
if (!isObject(value)) {
process.env.NODE_ENV !== 'production' && warn(
'v-bind without argument expects an Object or Array value',
this
)
} else {
if (Array.isArray(value)) {
value = toObject(value)
}
for (var key in value) {
if (key === 'class' || key === 'style') {
data[key] = value[key]
} else {
var hash = asProp || config.mustUseProp(key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {})
hash[key] = value[key]
}
}
}
}
return data
}
// expose v-on keyCodes
Vue.prototype._k = function getKeyCodes (key) {
return config.keyCodes[key]
}
}
function resolveSlots (
renderChildren,
context
) {
var slots = {}
if (!renderChildren) {
return slots
}
var children = normalizeChildren(renderChildren) || []
var defaultSlot = []
var name, child
for (var i = 0, l = children.length; i < l; i++) {
child = children[i]
// named slots should only be respected if the vnode was rendered in the
// same context.
if (child.context === context &&
child.data && (name = child.data.slot)) {
var slot = (slots[name] || (slots[name] = []))
if (child.tag === 'template') {
slot.push.apply(slot, child.children)
} else {
slot.push(child)
}
} else {
defaultSlot.push(child)
}
}
// ignore single whitespace
if (defaultSlot.length && !(
defaultSlot.length === 1 &&
(defaultSlot[0].text === ' ' || defaultSlot[0].isComment)
)) {
slots.default = defaultSlot
}
return slots
}
/* */
function initEvents (vm) {
vm._events = Object.create(null)
// init parent attached events
var listeners = vm.$options._parentListeners
var on = bind$1(vm.$on, vm)
var off = bind$1(vm.$off, vm)
vm._updateListeners = function (listeners, oldListeners) {
updateListeners(listeners, oldListeners || {}, on, off)
}
if (listeners) {
vm._updateListeners(listeners)
}
}
function eventsMixin (Vue) {
Vue.prototype.$on = function (event, fn) {
var vm = this;(vm._events[event] || (vm._events[event] = [])).push(fn)
return vm
}
Vue.prototype.$once = function (event, fn) {
var vm = this
function on () {
vm.$off(event, on)
fn.apply(vm, arguments)
}
on.fn = fn
vm.$on(event, on)
return vm
}
Vue.prototype.$off = function (event, fn) {
var vm = this
// all
if (!arguments.length) {
vm._events = Object.create(null)
return vm
}
// specific event
var cbs = vm._events[event]
if (!cbs) {
return vm
}
if (arguments.length === 1) {
vm._events[event] = null
return vm
}
// specific handler
var cb
var i = cbs.length
while (i--) {
cb = cbs[i]
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1)
break
}
}
return vm
}
Vue.prototype.$emit = function (event) {
var vm = this
var cbs = vm._events[event]
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs
var args = toArray(arguments, 1)
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i].apply(vm, args)
}
}
return vm
}
}
/* */
var uid = 0
function initMixin (Vue) {
Vue.prototype._init = function (options) {
var vm = this
// a uid
vm._uid = uid++
// a flag to avoid this being observed
vm._isVue = true
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options)
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm),
options || {},
vm
)
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
initProxy(vm)
} else {
vm._renderProxy = vm
}
// expose real self
vm._self = vm
initLifecycle(vm)
initEvents(vm)
callHook(vm, 'beforeCreate')
initState(vm)
callHook(vm, 'created')
initRender(vm)
}
function initInternalComponent (vm, options) {
var opts = vm.$options = Object.create(resolveConstructorOptions(vm))
// doing this because it's faster than dynamic enumeration.
opts.parent = options.parent
opts.propsData = options.propsData
opts._parentVnode = options._parentVnode
opts._parentListeners = options._parentListeners
opts._renderChildren = options._renderChildren
opts._componentTag = options._componentTag
if (options.render) {
opts.render = options.render
opts.staticRenderFns = options.staticRenderFns
}
}
function resolveConstructorOptions (vm) {
var Ctor = vm.constructor
var options = Ctor.options
if (Ctor.super) {
var superOptions = Ctor.super.options
var cachedSuperOptions = Ctor.superOptions
if (superOptions !== cachedSuperOptions) {
// super option changed
Ctor.superOptions = superOptions
options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions)
if (options.name) {
options.components[options.name] = Ctor
}
}
}
return options
}
}
function Vue$2 (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue$2)) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
initMixin(Vue$2)
stateMixin(Vue$2)
eventsMixin(Vue$2)
lifecycleMixin(Vue$2)
renderMixin(Vue$2)
var warn = noop
var formatComponentName
if (process.env.NODE_ENV !== 'production') {
var hasConsole = typeof console !== 'undefined'
warn = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.error("[Vue warn]: " + msg + " " + (
vm ? formatLocation(formatComponentName(vm)) : ''
))
}
}
formatComponentName = function (vm) {
if (vm.$root === vm) {
return 'root instance'
}
var name = vm._isVue
? vm.$options.name || vm.$options._componentTag
: vm.name
return name ? ("component <" + name + ">") : "anonymous component"
}
var formatLocation = function (str) {
if (str === 'anonymous component') {
str += " - use the \"name\" option for better debugging messages."
}
return ("(found in " + str + ")")
}
}
/* */
/**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/
var strats = config.optionMergeStrategies
/**
* Options with restrictions
*/
if (process.env.NODE_ENV !== 'production') {
strats.el = strats.propsData = function (parent, child, vm, key) {
if (!vm) {
warn(
"option \"" + key + "\" can only be used during instance " +
'creation with the `new` keyword.'
)
}
return defaultStrat(parent, child)
}
strats.name = function (parent, child, vm) {
if (vm && child) {
warn(
'options "name" can only be used as a component definition option, ' +
'not during instance creation.'
)
}
return defaultStrat(parent, child)
}
}
/**
* Helper that recursively merges two data objects together.
*/
function mergeData (to, from) {
var key, toVal, fromVal
for (key in from) {
toVal = to[key]
fromVal = from[key]
if (!hasOwn(to, key)) {
set(to, key, fromVal)
} else if (isObject(toVal) && isObject(fromVal)) {
mergeData(toVal, fromVal)
}
}
return to
}
/**
* Data
*/
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
if (typeof childVal !== 'function') {
process.env.NODE_ENV !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
)
return parentVal
}
if (!parentVal) {
return childVal
}
// when parentVal & childVal are both present,
// we need to return a function that returns the
// merged result of both functions... no need to
// check if parentVal is a function here because
// it has to be a function to pass previous merges.
return function mergedDataFn () {
return mergeData(
childVal.call(this),
parentVal.call(this)
)
}
} else if (parentVal || childVal) {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
? childVal.call(vm)
: childVal
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm)
: undefined
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
}
/**
* Hooks and param attributes are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
config._lifecycleHooks.forEach(function (hook) {
strats[hook] = mergeHook
})
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/
function mergeAssets (parentVal, childVal) {
var res = Object.create(parentVal || null)
return childVal
? extend(res, childVal)
: res
}
config._assetTypes.forEach(function (type) {
strats[type + 's'] = mergeAssets
})
/**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
strats.watch = function (parentVal, childVal) {
/* istanbul ignore if */
if (!childVal) { return parentVal }
if (!parentVal) { return childVal }
var ret = {}
extend(ret, parentVal)
for (var key in childVal) {
var parent = ret[key]
var child = childVal[key]
if (parent && !Array.isArray(parent)) {
parent = [parent]
}
ret[key] = parent
? parent.concat(child)
: [child]
}
return ret
}
/**
* Other object hashes.
*/
strats.props =
strats.methods =
strats.computed = function (parentVal, childVal) {
if (!childVal) { return parentVal }
if (!parentVal) { return childVal }
var ret = Object.create(null)
extend(ret, parentVal)
extend(ret, childVal)
return ret
}
/**
* Default strategy.
*/
var defaultStrat = function (parentVal, childVal) {
return childVal === undefined
? parentVal
: childVal
}
/**
* Make sure component options get converted to actual
* constructors.
*/
function normalizeComponents (options) {
if (options.components) {
var components = options.components
var def
for (var key in components) {
var lower = key.toLowerCase()
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
process.env.NODE_ENV !== 'production' && warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
)
continue
}
def = components[key]
if (isPlainObject(def)) {
components[key] = Vue$2.extend(def)
}
}
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options) {
var props = options.props
if (!props) { return }
var res = {}
var i, val, name
if (Array.isArray(props)) {
i = props.length
while (i--) {
val = props[i]
if (typeof val === 'string') {
name = camelize(val)
res[name] = { type: null }
} else if (process.env.NODE_ENV !== 'production') {
warn('props must be strings when using array syntax.')
}
}
} else if (isPlainObject(props)) {
for (var key in props) {
val = props[key]
name = camelize(key)
res[name] = isPlainObject(val)
? val
: { type: val }
}
}
options.props = res
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options) {
var dirs = options.directives
if (dirs) {
for (var key in dirs) {
var def = dirs[key]
if (typeof def === 'function') {
dirs[key] = { bind: def, update: def }
}
}
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
function mergeOptions (
parent,
child,
vm
) {
normalizeComponents(child)
normalizeProps(child)
normalizeDirectives(child)
var extendsFrom = child.extends
if (extendsFrom) {
parent = typeof extendsFrom === 'function'
? mergeOptions(parent, extendsFrom.options, vm)
: mergeOptions(parent, extendsFrom, vm)
}
if (child.mixins) {
for (var i = 0, l = child.mixins.length; i < l; i++) {
var mixin = child.mixins[i]
if (mixin.prototype instanceof Vue$2) {
mixin = mixin.options
}
parent = mergeOptions(parent, mixin, vm)
}
}
var options = {}
var key
for (key in parent) {
mergeField(key)
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key)
}
}
function mergeField (key) {
var strat = strats[key] || defaultStrat
options[key] = strat(parent[key], child[key], vm, key)
}
return options
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
function resolveAsset (
options,
type,
id,
warnMissing
) {
/* istanbul ignore if */
if (typeof id !== 'string') {
return
}
var assets = options[type]
var res = assets[id] ||
// camelCase ID
assets[camelize(id)] ||
// Pascal Case ID
assets[capitalize(camelize(id))]
if (process.env.NODE_ENV !== 'production' && warnMissing && !res) {
warn(
'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
options
)
}
return res
}
/* */
function validateProp (
key,
propOptions,
propsData,
vm
) {
var prop = propOptions[key]
var absent = !hasOwn(propsData, key)
var value = propsData[key]
// handle boolean props
if (getType(prop.type) === 'Boolean') {
if (absent && !hasOwn(prop, 'default')) {
value = false
} else if (value === '' || value === hyphenate(key)) {
value = true
}
}
// check default value
if (value === undefined) {
value = getPropDefaultValue(vm, prop, key)
// since the default value is a fresh copy,
// make sure to observe it.
var prevShouldConvert = observerState.shouldConvert
observerState.shouldConvert = true
observe(value)
observerState.shouldConvert = prevShouldConvert
}
if (process.env.NODE_ENV !== 'production') {
assertProp(prop, key, value, vm, absent)
}
return value
}
/**
* Get the default value of a prop.
*/
function getPropDefaultValue (vm, prop, name) {
// no default, return undefined
if (!hasOwn(prop, 'default')) {
return undefined
}
var def = prop.default
// warn against non-factory defaults for Object & Array
if (isObject(def)) {
process.env.NODE_ENV !== 'production' && warn(
'Invalid default value for prop "' + name + '": ' +
'Props with type Object/Array must use a factory function ' +
'to return the default value.',
vm
)
}
// call factory function for non-Function types
return typeof def === 'function' && prop.type !== Function
? def.call(vm)
: def
}
/**
* Assert whether a prop is valid.
*/
function assertProp (
prop,
name,
value,
vm,
absent
) {
if (prop.required && absent) {
warn(
'Missing required prop: "' + name + '"',
vm
)
return
}
if (value == null && !prop.required) {
return
}
var type = prop.type
var valid = !type || type === true
var expectedTypes = []
if (type) {
if (!Array.isArray(type)) {
type = [type]
}
for (var i = 0; i < type.length && !valid; i++) {
var assertedType = assertType(value, type[i])
expectedTypes.push(assertedType.expectedType)
valid = assertedType.valid
}
}
if (!valid) {
warn(
'Invalid prop: type check failed for prop "' + name + '".' +
' Expected ' + expectedTypes.map(capitalize).join(', ') +
', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.',
vm
)
return
}
var validator = prop.validator
if (validator) {
if (!validator(value)) {
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
)
}
}
}
/**
* Assert the type of a value
*/
function assertType (value, type) {
var valid
var expectedType = getType(type)
if (expectedType === 'String') {
valid = typeof value === (expectedType = 'string')
} else if (expectedType === 'Number') {
valid = typeof value === (expectedType = 'number')
} else if (expectedType === 'Boolean') {
valid = typeof value === (expectedType = 'boolean')
} else if (expectedType === 'Function') {
valid = typeof value === (expectedType = 'function')
} else if (expectedType === 'Object') {
valid = isPlainObject(value)
} else if (expectedType === 'Array') {
valid = Array.isArray(value)
} else {
valid = value instanceof type
}
return {
valid: valid,
expectedType: expectedType
}
}
/**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.
*/
function getType (fn) {
var match = fn && fn.toString().match(/^\s*function (\w+)/)
return match && match[1]
}
var util = Object.freeze({
defineReactive: defineReactive$$1,
_toString: _toString,
toNumber: toNumber,
makeMap: makeMap,
isBuiltInTag: isBuiltInTag,
remove: remove$1,
hasOwn: hasOwn,
isPrimitive: isPrimitive,
cached: cached,
camelize: camelize,
capitalize: capitalize,
hyphenate: hyphenate,
bind: bind$1,
toArray: toArray,
extend: extend,
isObject: isObject,
isPlainObject: isPlainObject,
toObject: toObject,
noop: noop,
no: no,
genStaticKeys: genStaticKeys,
looseEqual: looseEqual,
looseIndexOf: looseIndexOf,
isReserved: isReserved,
def: def,
parsePath: parsePath,
hasProto: hasProto,
inBrowser: inBrowser,
UA: UA,
isIE: isIE,
isIE9: isIE9,
isEdge: isEdge,
isAndroid: isAndroid,
isIOS: isIOS,
devtools: devtools,
nextTick: nextTick,
get _Set () { return _Set; },
mergeOptions: mergeOptions,
resolveAsset: resolveAsset,
get warn () { return warn; },
get formatComponentName () { return formatComponentName; },
validateProp: validateProp
});
/* */
function initUse (Vue) {
Vue.use = function (plugin) {
/* istanbul ignore if */
if (plugin.installed) {
return
}
// additional parameters
var args = toArray(arguments, 1)
args.unshift(this)
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
} else {
plugin.apply(null, args)
}
plugin.installed = true
return this
}
}
/* */
function initMixin$1 (Vue) {
Vue.mixin = function (mixin) {
Vue.options = mergeOptions(Vue.options, mixin)
}
}
/* */
function initExtend (Vue) {
/**
* Each instance constructor, including Vue, has a unique
* cid. This enables us to create wrapped "child
* constructors" for prototypal inheritance and cache them.
*/
Vue.cid = 0
var cid = 1
/**
* Class inheritance
*/
Vue.extend = function (extendOptions) {
extendOptions = extendOptions || {}
var Super = this
var isFirstExtend = Super.cid === 0
if (isFirstExtend && extendOptions._Ctor) {
return extendOptions._Ctor
}
var name = extendOptions.name || Super.options.name
if (process.env.NODE_ENV !== 'production') {
if (!/^[a-zA-Z][\w-]*$/.test(name)) {
warn(
'Invalid component name: "' + name + '". Component names ' +
'can only contain alphanumeric characaters and the hyphen.'
)
name = null
}
}
var Sub = function VueComponent (options) {
this._init(options)
}
Sub.prototype = Object.create(Super.prototype)
Sub.prototype.constructor = Sub
Sub.cid = cid++
Sub.options = mergeOptions(
Super.options,
extendOptions
)
Sub['super'] = Super
// allow further extension
Sub.extend = Super.extend
// create asset registers, so extended classes
// can have their private assets too.
config._assetTypes.forEach(function (type) {
Sub[type] = Super[type]
})
// enable recursive self-lookup
if (name) {
Sub.options.components[name] = Sub
}
// keep a reference to the super options at extension time.
// later at instantiation we can check if Super's options have
// been updated.
Sub.superOptions = Super.options
Sub.extendOptions = extendOptions
// cache constructor
if (isFirstExtend) {
extendOptions._Ctor = Sub
}
return Sub
}
}
/* */
function initAssetRegisters (Vue) {
/**
* Create asset registration methods.
*/
config._assetTypes.forEach(function (type) {
Vue[type] = function (
id,
definition
) {
if (!definition) {
return this.options[type + 's'][id]
} else {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
if (type === 'component' && config.isReservedTag(id)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + id
)
}
}
if (type === 'component' && isPlainObject(definition)) {
definition.name = definition.name || id
definition = Vue.extend(definition)
}
if (type === 'directive' && typeof definition === 'function') {
definition = { bind: definition, update: definition }
}
this.options[type + 's'][id] = definition
return definition
}
}
})
}
var KeepAlive = {
name: 'keep-alive',
abstract: true,
created: function created () {
this.cache = Object.create(null)
},
render: function render () {
var vnode = getFirstComponentChild(this.$slots.default)
if (vnode && vnode.componentOptions) {
var opts = vnode.componentOptions
var key = vnode.key == null
// same constructor may get registered as different local components
// so cid alone is not enough (#3269)
? opts.Ctor.cid + '::' + opts.tag
: vnode.key
if (this.cache[key]) {
vnode.child = this.cache[key].child
} else {
this.cache[key] = vnode
}
vnode.data.keepAlive = true
}
return vnode
},
destroyed: function destroyed () {
var this$1 = this;
for (var key in this.cache) {
var vnode = this$1.cache[key]
callHook(vnode.child, 'deactivated')
vnode.child.$destroy()
}
}
}
var builtInComponents = {
KeepAlive: KeepAlive
}
/* */
function initGlobalAPI (Vue) {
// config
var configDef = {}
configDef.get = function () { return config; }
if (process.env.NODE_ENV !== 'production') {
configDef.set = function () {
warn(
'Do not replace the Vue.config object, set individual fields instead.'
)
}
}
Object.defineProperty(Vue, 'config', configDef)
Vue.util = util
Vue.set = set
Vue.delete = del
Vue.nextTick = nextTick
Vue.options = Object.create(null)
config._assetTypes.forEach(function (type) {
Vue.options[type + 's'] = Object.create(null)
})
extend(Vue.options.components, builtInComponents)
initUse(Vue)
initMixin$1(Vue)
initExtend(Vue)
initAssetRegisters(Vue)
}
initGlobalAPI(Vue$2)
Object.defineProperty(Vue$2.prototype, '$isServer', {
get: function () { return config._isServer; }
})
Vue$2.version = '2.0.1'
/* */
// attributes that should be using props for binding
var mustUseProp = makeMap('value,selected,checked,muted')
var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck')
var isBooleanAttr = makeMap(
'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
'required,reversed,scoped,seamless,selected,sortable,translate,' +
'truespeed,typemustmatch,visible'
)
var isAttr = makeMap(
'accept,accept-charset,accesskey,action,align,alt,async,autocomplete,' +
'autofocus,autoplay,autosave,bgcolor,border,buffered,challenge,charset,' +
'checked,cite,class,code,codebase,color,cols,colspan,content,http-equiv,' +
'name,contenteditable,contextmenu,controls,coords,data,datetime,default,' +
'defer,dir,dirname,disabled,download,draggable,dropzone,enctype,method,for,' +
'form,formaction,headers,<th>,height,hidden,high,href,hreflang,http-equiv,' +
'icon,id,ismap,itemprop,keytype,kind,label,lang,language,list,loop,low,' +
'manifest,max,maxlength,media,method,GET,POST,min,multiple,email,file,' +
'muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,' +
'preload,radiogroup,readonly,rel,required,reversed,rows,rowspan,sandbox,' +
'scope,scoped,seamless,selected,shape,size,type,text,password,sizes,span,' +
'spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,' +
'target,title,type,usemap,value,width,wrap'
)
var xlinkNS = 'http://www.w3.org/1999/xlink'
var isXlink = function (name) {
return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'
}
var getXlinkProp = function (name) {
return isXlink(name) ? name.slice(6, name.length) : ''
}
var isFalsyAttrValue = function (val) {
return val == null || val === false
}
/* */
function genClassForVnode (vnode) {
var data = vnode.data
var parentNode = vnode
var childNode = vnode
while (childNode.child) {
childNode = childNode.child._vnode
if (childNode.data) {
data = mergeClassData(childNode.data, data)
}
}
while ((parentNode = parentNode.parent)) {
if (parentNode.data) {
data = mergeClassData(data, parentNode.data)
}
}
return genClassFromData(data)
}
function mergeClassData (child, parent) {
return {
staticClass: concat(child.staticClass, parent.staticClass),
class: child.class
? [child.class, parent.class]
: parent.class
}
}
function genClassFromData (data) {
var dynamicClass = data.class
var staticClass = data.staticClass
if (staticClass || dynamicClass) {
return concat(staticClass, stringifyClass(dynamicClass))
}
/* istanbul ignore next */
return ''
}
function concat (a, b) {
return a ? b ? (a + ' ' + b) : a : (b || '')
}
function stringifyClass (value) {
var res = ''
if (!value) {
return res
}
if (typeof value === 'string') {
return value
}
if (Array.isArray(value)) {
var stringified
for (var i = 0, l = value.length; i < l; i++) {
if (value[i]) {
if ((stringified = stringifyClass(value[i]))) {
res += stringified + ' '
}
}
}
return res.slice(0, -1)
}
if (isObject(value)) {
for (var key in value) {
if (value[key]) { res += key + ' ' }
}
return res.slice(0, -1)
}
/* istanbul ignore next */
return res
}
/* */
var namespaceMap = {
svg: 'http://www.w3.org/2000/svg',
math: 'http://www.w3.org/1998/Math/MathML'
}
var isHTMLTag = makeMap(
'html,body,base,head,link,meta,style,title,' +
'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' +
'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
'embed,object,param,source,canvas,script,noscript,del,ins,' +
'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
'output,progress,select,textarea,' +
'details,dialog,menu,menuitem,summary,' +
'content,element,shadow,template'
)
var isUnaryTag = makeMap(
'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +
'link,meta,param,source,track,wbr',
true
)
// Elements that you can, intentionally, leave open
// (and which close themselves)
var canBeLeftOpenTag = makeMap(
'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source',
true
)
// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3
// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
var isNonPhrasingTag = makeMap(
'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +
'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +
'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +
'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +
'title,tr,track',
true
)
// this map is intentionally selective, only covering SVG elements that may
// contain child elements.
var isSVG = makeMap(
'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font,' +
'font-face,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
true
)
var isReservedTag = function (tag) {
return isHTMLTag(tag) || isSVG(tag)
}
function getTagNamespace (tag) {
if (isSVG(tag)) {
return 'svg'
}
// basic support for MathML
// note it doesn't support other MathML elements being component roots
if (tag === 'math') {
return 'math'
}
}
var unknownElementCache = Object.create(null)
function isUnknownElement (tag) {
/* istanbul ignore if */
if (!inBrowser) {
return true
}
if (isReservedTag(tag)) {
return false
}
tag = tag.toLowerCase()
/* istanbul ignore if */
if (unknownElementCache[tag] != null) {
return unknownElementCache[tag]
}
var el = document.createElement(tag)
if (tag.indexOf('-') > -1) {
// http://stackoverflow.com/a/28210364/1070244
return (unknownElementCache[tag] = (
el.constructor === window.HTMLUnknownElement ||
el.constructor === window.HTMLElement
))
} else {
return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString()))
}
}
/* */
/**
* Query an element selector if it's not an element already.
*/
function query (el) {
if (typeof el === 'string') {
var selector = el
el = document.querySelector(el)
if (!el) {
process.env.NODE_ENV !== 'production' && warn(
'Cannot find element: ' + selector
)
return document.createElement('div')
}
}
return el
}
/* */
function createElement$1 (tagName) {
return document.createElement(tagName)
}
function createElementNS (namespace, tagName) {
return document.createElementNS(namespaceMap[namespace], tagName)
}
function createTextNode (text) {
return document.createTextNode(text)
}
function createComment (text) {
return document.createComment(text)
}
function insertBefore (parentNode, newNode, referenceNode) {
parentNode.insertBefore(newNode, referenceNode)
}
function removeChild (node, child) {
node.removeChild(child)
}
function appendChild (node, child) {
node.appendChild(child)
}
function parentNode (node) {
return node.parentNode
}
function nextSibling (node) {
return node.nextSibling
}
function tagName (node) {
return node.tagName
}
function setTextContent (node, text) {
node.textContent = text
}
function childNodes (node) {
return node.childNodes
}
function setAttribute (node, key, val) {
node.setAttribute(key, val)
}
var nodeOps = Object.freeze({
createElement: createElement$1,
createElementNS: createElementNS,
createTextNode: createTextNode,
createComment: createComment,
insertBefore: insertBefore,
removeChild: removeChild,
appendChild: appendChild,
parentNode: parentNode,
nextSibling: nextSibling,
tagName: tagName,
setTextContent: setTextContent,
childNodes: childNodes,
setAttribute: setAttribute
});
/* */
var ref = {
create: function create (_, vnode) {
registerRef(vnode)
},
update: function update (oldVnode, vnode) {
if (oldVnode.data.ref !== vnode.data.ref) {
registerRef(oldVnode, true)
registerRef(vnode)
}
},
destroy: function destroy (vnode) {
registerRef(vnode, true)
}
}
function registerRef (vnode, isRemoval) {
var key = vnode.data.ref
if (!key) { return }
var vm = vnode.context
var ref = vnode.child || vnode.elm
var refs = vm.$refs
if (isRemoval) {
if (Array.isArray(refs[key])) {
remove$1(refs[key], ref)
} else if (refs[key] === ref) {
refs[key] = undefined
}
} else {
if (vnode.data.refInFor) {
if (Array.isArray(refs[key])) {
refs[key].push(ref)
} else {
refs[key] = [ref]
}
} else {
refs[key] = ref
}
}
}
/**
* Virtual DOM patching algorithm based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* Licensed under the MIT License
* https://github.com/paldepind/snabbdom/blob/master/LICENSE
*
* modified by Evan You (@yyx990803)
*
/*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
var emptyData = {}
var emptyNode = new VNode('', emptyData, [])
var hooks$1 = ['create', 'update', 'postpatch', 'remove', 'destroy']
function isUndef (s) {
return s == null
}
function isDef (s) {
return s != null
}
function sameVnode (vnode1, vnode2) {
return (
vnode1.key === vnode2.key &&
vnode1.tag === vnode2.tag &&
vnode1.isComment === vnode2.isComment &&
!vnode1.data === !vnode2.data
)
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
var i, key
var map = {}
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key
if (isDef(key)) { map[key] = i }
}
return map
}
function createPatchFunction (backend) {
var i, j
var cbs = {}
var modules = backend.modules;
var nodeOps = backend.nodeOps;
for (i = 0; i < hooks$1.length; ++i) {
cbs[hooks$1[i]] = []
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks$1[i]] !== undefined) { cbs[hooks$1[i]].push(modules[j][hooks$1[i]]) }
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove$$1 () {
if (--remove$$1.listeners === 0) {
removeElement(childElm)
}
}
remove$$1.listeners = listeners
return remove$$1
}
function removeElement (el) {
var parent = nodeOps.parentNode(el)
nodeOps.removeChild(parent, el)
}
function createElm (vnode, insertedVnodeQueue, nested) {
var i
var data = vnode.data
vnode.isRootInsert = !nested
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode) }
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(i = vnode.child)) {
initComponent(vnode, insertedVnodeQueue)
return vnode.elm
}
}
var children = vnode.children
var tag = vnode.tag
if (isDef(tag)) {
if (process.env.NODE_ENV !== 'production') {
if (
!vnode.ns &&
!(config.ignoredElements && config.ignoredElements.indexOf(tag) > -1) &&
config.isUnknownElement(tag)
) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
)
}
}
vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag)
setScope(vnode)
createChildren(vnode, children, insertedVnodeQueue)
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
} else if (vnode.isComment) {
vnode.elm = nodeOps.createComment(vnode.text)
} else {
vnode.elm = nodeOps.createTextNode(vnode.text)
}
return vnode.elm
}
function createChildren (vnode, children, insertedVnodeQueue) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; ++i) {
nodeOps.appendChild(vnode.elm, createElm(children[i], insertedVnodeQueue, true))
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text))
}
}
function isPatchable (vnode) {
while (vnode.child) {
vnode = vnode.child._vnode
}
return isDef(vnode.tag)
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {
cbs.create[i$1](emptyNode, vnode)
}
i = vnode.data.hook // Reuse variable
if (isDef(i)) {
if (i.create) { i.create(emptyNode, vnode) }
if (i.insert) { insertedVnodeQueue.push(vnode) }
}
}
function initComponent (vnode, insertedVnodeQueue) {
if (vnode.data.pendingInsert) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert)
}
vnode.elm = vnode.child.$el
if (isPatchable(vnode)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
setScope(vnode)
} else {
// empty component root.
// skip all element-related modules except for ref (#3455)
registerRef(vnode)
// make sure to invoke the insert hook
insertedVnodeQueue.push(vnode)
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
var i
if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '')
}
if (isDef(i = activeInstance) &&
i !== vnode.context &&
isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '')
}
}
function addVnodes (parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
nodeOps.insertBefore(parentElm, createElm(vnodes[startIdx], insertedVnodeQueue), before)
}
}
function invokeDestroyHook (vnode) {
var i, j
var data = vnode.data
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode) }
for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode) }
}
if (isDef(i = vnode.child) && !data.keepAlive) {
invokeDestroyHook(i._vnode)
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j])
}
}
}
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
var ch = vnodes[startIdx]
if (isDef(ch)) {
if (isDef(ch.tag)) {
removeAndInvokeRemoveHook(ch)
invokeDestroyHook(ch)
} else { // Text node
nodeOps.removeChild(parentElm, ch.elm)
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (rm || isDef(vnode.data)) {
var listeners = cbs.remove.length + 1
if (!rm) {
// directly removing
rm = createRmCb(vnode.elm, listeners)
} else {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.child) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm)
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm)
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm)
} else {
rm()
}
} else {
removeElement(vnode.elm)
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
var oldStartIdx = 0
var newStartIdx = 0
var oldEndIdx = oldCh.length - 1
var oldStartVnode = oldCh[0]
var oldEndVnode = oldCh[oldEndIdx]
var newEndIdx = newCh.length - 1
var newStartVnode = newCh[0]
var newEndVnode = newCh[newEndIdx]
var oldKeyToIdx, idxInOld, elmToMove, before
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
var canMove = !removeOnly
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx]
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue)
oldStartVnode = oldCh[++oldStartIdx]
newStartVnode = newCh[++newStartIdx]
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue)
oldEndVnode = oldCh[--oldEndIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue)
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
oldStartVnode = oldCh[++oldStartIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue)
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
oldEndVnode = oldCh[--oldEndIdx]
newStartVnode = newCh[++newStartIdx]
} else {
if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx) }
idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : null
if (isUndef(idxInOld)) { // New element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
} else {
elmToMove = oldCh[idxInOld]
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !elmToMove) {
warn(
'It seems there are duplicate keys that is causing an update error. ' +
'Make sure each v-for item has a unique key.'
)
}
if (elmToMove.tag !== newStartVnode.tag) {
// same key but different element. treat as new element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
} else {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue)
oldCh[idxInOld] = undefined
canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
}
}
}
}
if (oldStartIdx > oldEndIdx) {
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue)
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx)
}
}
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) {
return
}
// reuse element for static trees.
// note we only do this if the vnode is cloned -
// if the new node is not cloned it means the render functions have been
// reset by the hot-reload-api and we need to do a proper re-render.
if (vnode.isStatic &&
oldVnode.isStatic &&
vnode.key === oldVnode.key &&
vnode.isCloned) {
vnode.elm = oldVnode.elm
return
}
var i, hook
var hasData = isDef(i = vnode.data)
if (hasData && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
i(oldVnode, vnode)
}
var elm = vnode.elm = oldVnode.elm
var oldCh = oldVnode.children
var ch = vnode.children
if (hasData && isPatchable(vnode)) {
for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode) }
if (isDef(hook) && isDef(i = hook.update)) { i(oldVnode, vnode) }
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly) }
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, '') }
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1)
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '')
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text)
}
if (hasData) {
for (i = 0; i < cbs.postpatch.length; ++i) { cbs.postpatch[i](oldVnode, vnode) }
if (isDef(hook) && isDef(i = hook.postpatch)) { i(oldVnode, vnode) }
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (initial && vnode.parent) {
vnode.parent.data.pendingInsert = queue
} else {
for (var i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i])
}
}
}
var bailed = false
function hydrate (elm, vnode, insertedVnodeQueue) {
if (process.env.NODE_ENV !== 'production') {
if (!assertNodeMatch(elm, vnode)) {
return false
}
}
vnode.elm = elm
var tag = vnode.tag;
var data = vnode.data;
var children = vnode.children;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */) }
if (isDef(i = vnode.child)) {
// child component. it should have hydrated its own tree.
initComponent(vnode, insertedVnodeQueue)
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
var childNodes = nodeOps.childNodes(elm)
// empty element, allow client to pick up and populate children
if (!childNodes.length) {
createChildren(vnode, children, insertedVnodeQueue)
} else {
var childrenMatch = true
if (childNodes.length !== children.length) {
childrenMatch = false
} else {
for (var i$1 = 0; i$1 < children.length; i$1++) {
if (!hydrate(childNodes[i$1], children[i$1], insertedVnodeQueue)) {
childrenMatch = false
break
}
}
}
if (!childrenMatch) {
if (process.env.NODE_ENV !== 'production' &&
typeof console !== 'undefined' &&
!bailed) {
bailed = true
console.warn('Parent: ', elm)
console.warn('Mismatching childNodes vs. VNodes: ', childNodes, children)
}
return false
}
}
}
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
}
return true
}
function assertNodeMatch (node, vnode) {
if (vnode.tag) {
return (
vnode.tag.indexOf('vue-component') === 0 ||
vnode.tag === nodeOps.tagName(node).toLowerCase()
)
} else {
return _toString(vnode.text) === node.data
}
}
return function patch (oldVnode, vnode, hydrating, removeOnly) {
var elm, parent
var isInitialPatch = false
var insertedVnodeQueue = []
if (!oldVnode) {
// empty mount, create new root element
isInitialPatch = true
createElm(vnode, insertedVnodeQueue)
} else {
var isRealElement = isDef(oldVnode.nodeType)
if (!isRealElement && sameVnode(oldVnode, vnode)) {
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute('server-rendered')) {
oldVnode.removeAttribute('server-rendered')
hydrating = true
}
if (hydrating) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true)
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
)
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode)
}
elm = oldVnode.elm
parent = nodeOps.parentNode(elm)
createElm(vnode, insertedVnodeQueue)
// component root element replaced.
// update parent placeholder node element.
if (vnode.parent) {
vnode.parent.elm = vnode.elm
if (isPatchable(vnode)) {
for (var i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode.parent)
}
}
}
if (parent !== null) {
nodeOps.insertBefore(parent, vnode.elm, nodeOps.nextSibling(elm))
removeVnodes(parent, [oldVnode], 0, 0)
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode)
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
return vnode.elm
}
}
/* */
var directives = {
create: function bindDirectives (oldVnode, vnode) {
var hasInsert = false
forEachDirective(oldVnode, vnode, function (def, dir) {
callHook$1(def, dir, 'bind', vnode, oldVnode)
if (def.inserted) {
hasInsert = true
}
})
if (hasInsert) {
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () {
applyDirectives(oldVnode, vnode, 'inserted')
})
}
},
update: function updateDirectives (oldVnode, vnode) {
applyDirectives(oldVnode, vnode, 'update')
// if old vnode has directives but new vnode doesn't
// we need to teardown the directives on the old one.
if (oldVnode.data.directives && !vnode.data.directives) {
applyDirectives(oldVnode, oldVnode, 'unbind')
}
},
postpatch: function postupdateDirectives (oldVnode, vnode) {
applyDirectives(oldVnode, vnode, 'componentUpdated')
},
destroy: function unbindDirectives (vnode) {
applyDirectives(vnode, vnode, 'unbind')
}
}
var emptyModifiers = Object.create(null)
function forEachDirective (
oldVnode,
vnode,
fn
) {
var dirs = vnode.data.directives
if (dirs) {
for (var i = 0; i < dirs.length; i++) {
var dir = dirs[i]
var def = resolveAsset(vnode.context.$options, 'directives', dir.name, true)
if (def) {
var oldDirs = oldVnode && oldVnode.data.directives
if (oldDirs) {
dir.oldValue = oldDirs[i].value
}
if (!dir.modifiers) {
dir.modifiers = emptyModifiers
}
fn(def, dir)
}
}
}
}
function applyDirectives (
oldVnode,
vnode,
hook
) {
forEachDirective(oldVnode, vnode, function (def, dir) {
callHook$1(def, dir, hook, vnode, oldVnode)
})
}
function callHook$1 (def, dir, hook, vnode, oldVnode) {
var fn = def && def[hook]
if (fn) {
fn(vnode.elm, dir, vnode, oldVnode)
}
}
var baseModules = [
ref,
directives
]
/* */
function updateAttrs (oldVnode, vnode) {
if (!oldVnode.data.attrs && !vnode.data.attrs) {
return
}
var key, cur, old
var elm = vnode.elm
var oldAttrs = oldVnode.data.attrs || {}
var attrs = vnode.data.attrs || {}
// clone observed objects, as the user probably wants to mutate it
if (attrs.__ob__) {
attrs = vnode.data.attrs = extend({}, attrs)
}
for (key in attrs) {
cur = attrs[key]
old = oldAttrs[key]
if (old !== cur) {
setAttr(elm, key, cur)
}
}
for (key in oldAttrs) {
if (attrs[key] == null) {
if (isXlink(key)) {
elm.removeAttributeNS(xlinkNS, getXlinkProp(key))
} else if (!isEnumeratedAttr(key)) {
elm.removeAttribute(key)
}
}
}
}
function setAttr (el, key, value) {
if (isBooleanAttr(key)) {
// set attribute for blank value
// e.g. <option disabled>Select one</option>
if (isFalsyAttrValue(value)) {
el.removeAttribute(key)
} else {
el.setAttribute(key, key)
}
} else if (isEnumeratedAttr(key)) {
el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true')
} else if (isXlink(key)) {
if (isFalsyAttrValue(value)) {
el.removeAttributeNS(xlinkNS, getXlinkProp(key))
} else {
el.setAttributeNS(xlinkNS, key, value)
}
} else {
if (isFalsyAttrValue(value)) {
el.removeAttribute(key)
} else {
el.setAttribute(key, value)
}
}
}
var attrs = {
create: updateAttrs,
update: updateAttrs
}
/* */
function updateClass (oldVnode, vnode) {
var el = vnode.elm
var data = vnode.data
var oldData = oldVnode.data
if (!data.staticClass && !data.class &&
(!oldData || (!oldData.staticClass && !oldData.class))) {
return
}
var cls = genClassForVnode(vnode)
// handle transition classes
var transitionClass = el._transitionClasses
if (transitionClass) {
cls = concat(cls, stringifyClass(transitionClass))
}
// set the class
if (cls !== el._prevClass) {
el.setAttribute('class', cls)
el._prevClass = cls
}
}
var klass = {
create: updateClass,
update: updateClass
}
// skip type checking this file because we need to attach private properties
// to elements
function updateDOMListeners (oldVnode, vnode) {
if (!oldVnode.data.on && !vnode.data.on) {
return
}
var on = vnode.data.on || {}
var oldOn = oldVnode.data.on || {}
var add = vnode.elm._v_add || (vnode.elm._v_add = function (event, handler, capture) {
vnode.elm.addEventListener(event, handler, capture)
})
var remove = vnode.elm._v_remove || (vnode.elm._v_remove = function (event, handler) {
vnode.elm.removeEventListener(event, handler)
})
updateListeners(on, oldOn, add, remove)
}
var events = {
create: updateDOMListeners,
update: updateDOMListeners
}
/* */
function updateDOMProps (oldVnode, vnode) {
if (!oldVnode.data.domProps && !vnode.data.domProps) {
return
}
var key, cur
var elm = vnode.elm
var oldProps = oldVnode.data.domProps || {}
var props = vnode.data.domProps || {}
// clone observed objects, as the user probably wants to mutate it
if (props.__ob__) {
props = vnode.data.domProps = extend({}, props)
}
for (key in oldProps) {
if (props[key] == null) {
elm[key] = undefined
}
}
for (key in props) {
// ignore children if the node has textContent or innerHTML,
// as these will throw away existing DOM nodes and cause removal errors
// on subsequent patches (#3360)
if ((key === 'textContent' || key === 'innerHTML') && vnode.children) {
vnode.children.length = 0
}
cur = props[key]
if (key === 'value') {
// store value as _value as well since
// non-string values will be stringified
elm._value = cur
// avoid resetting cursor position when value is the same
var strCur = cur == null ? '' : String(cur)
if (elm.value !== strCur) {
elm.value = strCur
}
} else {
elm[key] = cur
}
}
}
var domProps = {
create: updateDOMProps,
update: updateDOMProps
}
/* */
var prefixes = ['Webkit', 'Moz', 'ms']
var testEl
var normalize = cached(function (prop) {
testEl = testEl || document.createElement('div')
prop = camelize(prop)
if (prop !== 'filter' && (prop in testEl.style)) {
return prop
}
var upper = prop.charAt(0).toUpperCase() + prop.slice(1)
for (var i = 0; i < prefixes.length; i++) {
var prefixed = prefixes[i] + upper
if (prefixed in testEl.style) {
return prefixed
}
}
})
function updateStyle (oldVnode, vnode) {
if ((!oldVnode.data || !oldVnode.data.style) && !vnode.data.style) {
return
}
var cur, name
var el = vnode.elm
var oldStyle = oldVnode.data.style || {}
var style = vnode.data.style || {}
// handle string
if (typeof style === 'string') {
el.style.cssText = style
return
}
var needClone = style.__ob__
// handle array syntax
if (Array.isArray(style)) {
style = vnode.data.style = toObject(style)
}
// clone the style for future updates,
// in case the user mutates the style object in-place.
if (needClone) {
style = vnode.data.style = extend({}, style)
}
for (name in oldStyle) {
if (!style[name]) {
el.style[normalize(name)] = ''
}
}
for (name in style) {
cur = style[name]
if (cur !== oldStyle[name]) {
// ie9 setting to null has no effect, must use empty string
el.style[normalize(name)] = cur == null ? '' : cur
}
}
}
var style = {
create: updateStyle,
update: updateStyle
}
/* */
/**
* Add class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function addClass (el, cls) {
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); })
} else {
el.classList.add(cls)
}
} else {
var cur = ' ' + el.getAttribute('class') + ' '
if (cur.indexOf(' ' + cls + ' ') < 0) {
el.setAttribute('class', (cur + cls).trim())
}
}
}
/**
* Remove class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function removeClass (el, cls) {
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); })
} else {
el.classList.remove(cls)
}
} else {
var cur = ' ' + el.getAttribute('class') + ' '
var tar = ' ' + cls + ' '
while (cur.indexOf(tar) >= 0) {
cur = cur.replace(tar, ' ')
}
el.setAttribute('class', cur.trim())
}
}
/* */
var hasTransition = inBrowser && !isIE9
var TRANSITION = 'transition'
var ANIMATION = 'animation'
// Transition property/event sniffing
var transitionProp = 'transition'
var transitionEndEvent = 'transitionend'
var animationProp = 'animation'
var animationEndEvent = 'animationend'
if (hasTransition) {
/* istanbul ignore if */
if (window.ontransitionend === undefined &&
window.onwebkittransitionend !== undefined) {
transitionProp = 'WebkitTransition'
transitionEndEvent = 'webkitTransitionEnd'
}
if (window.onanimationend === undefined &&
window.onwebkitanimationend !== undefined) {
animationProp = 'WebkitAnimation'
animationEndEvent = 'webkitAnimationEnd'
}
}
var raf = (inBrowser && window.requestAnimationFrame) || setTimeout
function nextFrame (fn) {
raf(function () {
raf(fn)
})
}
function addTransitionClass (el, cls) {
(el._transitionClasses || (el._transitionClasses = [])).push(cls)
addClass(el, cls)
}
function removeTransitionClass (el, cls) {
if (el._transitionClasses) {
remove$1(el._transitionClasses, cls)
}
removeClass(el, cls)
}
function whenTransitionEnds (
el,
expectedType,
cb
) {
var ref = getTransitionInfo(el, expectedType);
var type = ref.type;
var timeout = ref.timeout;
var propCount = ref.propCount;
if (!type) { return cb() }
var event = type === TRANSITION ? transitionEndEvent : animationEndEvent
var ended = 0
var end = function () {
el.removeEventListener(event, onEnd)
cb()
}
var onEnd = function (e) {
if (e.target === el) {
if (++ended >= propCount) {
end()
}
}
}
setTimeout(function () {
if (ended < propCount) {
end()
}
}, timeout + 1)
el.addEventListener(event, onEnd)
}
var transformRE = /\b(transform|all)(,|$)/
function getTransitionInfo (el, expectedType) {
var styles = window.getComputedStyle(el)
var transitioneDelays = styles[transitionProp + 'Delay'].split(', ')
var transitionDurations = styles[transitionProp + 'Duration'].split(', ')
var transitionTimeout = getTimeout(transitioneDelays, transitionDurations)
var animationDelays = styles[animationProp + 'Delay'].split(', ')
var animationDurations = styles[animationProp + 'Duration'].split(', ')
var animationTimeout = getTimeout(animationDelays, animationDurations)
var type
var timeout = 0
var propCount = 0
/* istanbul ignore if */
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION
timeout = transitionTimeout
propCount = transitionDurations.length
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION
timeout = animationTimeout
propCount = animationDurations.length
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout)
type = timeout > 0
? transitionTimeout > animationTimeout
? TRANSITION
: ANIMATION
: null
propCount = type
? type === TRANSITION
? transitionDurations.length
: animationDurations.length
: 0
}
var hasTransform =
type === TRANSITION &&
transformRE.test(styles[transitionProp + 'Property'])
return {
type: type,
timeout: timeout,
propCount: propCount,
hasTransform: hasTransform
}
}
function getTimeout (delays, durations) {
return Math.max.apply(null, durations.map(function (d, i) {
return toMs(d) + toMs(delays[i])
}))
}
function toMs (s) {
return Number(s.slice(0, -1)) * 1000
}
/* */
function enter (vnode) {
var el = vnode.elm
// call leave callback now
if (el._leaveCb) {
el._leaveCb.cancelled = true
el._leaveCb()
}
var data = resolveTransition(vnode.data.transition)
if (!data) {
return
}
/* istanbul ignore if */
if (el._enterCb || el.nodeType !== 1) {
return
}
var css = data.css;
var type = data.type;
var enterClass = data.enterClass;
var enterActiveClass = data.enterActiveClass;
var appearClass = data.appearClass;
var appearActiveClass = data.appearActiveClass;
var beforeEnter = data.beforeEnter;
var enter = data.enter;
var afterEnter = data.afterEnter;
var enterCancelled = data.enterCancelled;
var beforeAppear = data.beforeAppear;
var appear = data.appear;
var afterAppear = data.afterAppear;
var appearCancelled = data.appearCancelled;
// activeInstance will always be the <transition> component managing this
// transition. One edge case to check is when the <transition> is placed
// as the root node of a child component. In that case we need to check
// <transition>'s parent for appear check.
var transitionNode = activeInstance.$vnode
var context = transitionNode && transitionNode.parent
? transitionNode.parent.context
: activeInstance
var isAppear = !context._isMounted || !vnode.isRootInsert
if (isAppear && !appear && appear !== '') {
return
}
var startClass = isAppear ? appearClass : enterClass
var activeClass = isAppear ? appearActiveClass : enterActiveClass
var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter
var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter
var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter
var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled
var expectsCSS = css !== false && !isIE9
var userWantsControl =
enterHook &&
// enterHook may be a bound method which exposes
// the length of original fn as _length
(enterHook._length || enterHook.length) > 1
var cb = el._enterCb = once(function () {
if (expectsCSS) {
removeTransitionClass(el, activeClass)
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, startClass)
}
enterCancelledHook && enterCancelledHook(el)
} else {
afterEnterHook && afterEnterHook(el)
}
el._enterCb = null
})
if (!vnode.data.show) {
// remove pending leave element on enter by injecting an insert hook
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () {
var parent = el.parentNode
var pendingNode = parent && parent._pending && parent._pending[vnode.key]
if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb) {
pendingNode.elm._leaveCb()
}
enterHook && enterHook(el, cb)
})
}
// start enter transition
beforeEnterHook && beforeEnterHook(el)
if (expectsCSS) {
addTransitionClass(el, startClass)
addTransitionClass(el, activeClass)
nextFrame(function () {
removeTransitionClass(el, startClass)
if (!cb.cancelled && !userWantsControl) {
whenTransitionEnds(el, type, cb)
}
})
}
if (vnode.data.show) {
enterHook && enterHook(el, cb)
}
if (!expectsCSS && !userWantsControl) {
cb()
}
}
function leave (vnode, rm) {
var el = vnode.elm
// call enter callback now
if (el._enterCb) {
el._enterCb.cancelled = true
el._enterCb()
}
var data = resolveTransition(vnode.data.transition)
if (!data) {
return rm()
}
/* istanbul ignore if */
if (el._leaveCb || el.nodeType !== 1) {
return
}
var css = data.css;
var type = data.type;
var leaveClass = data.leaveClass;
var leaveActiveClass = data.leaveActiveClass;
var beforeLeave = data.beforeLeave;
var leave = data.leave;
var afterLeave = data.afterLeave;
var leaveCancelled = data.leaveCancelled;
var delayLeave = data.delayLeave;
var expectsCSS = css !== false && !isIE9
var userWantsControl =
leave &&
// leave hook may be a bound method which exposes
// the length of original fn as _length
(leave._length || leave.length) > 1
var cb = el._leaveCb = once(function () {
if (el.parentNode && el.parentNode._pending) {
el.parentNode._pending[vnode.key] = null
}
if (expectsCSS) {
removeTransitionClass(el, leaveActiveClass)
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, leaveClass)
}
leaveCancelled && leaveCancelled(el)
} else {
rm()
afterLeave && afterLeave(el)
}
el._leaveCb = null
})
if (delayLeave) {
delayLeave(performLeave)
} else {
performLeave()
}
function performLeave () {
// the delayed leave may have already been cancelled
if (cb.cancelled) {
return
}
// record leaving element
if (!vnode.data.show) {
(el.parentNode._pending || (el.parentNode._pending = {}))[vnode.key] = vnode
}
beforeLeave && beforeLeave(el)
if (expectsCSS) {
addTransitionClass(el, leaveClass)
addTransitionClass(el, leaveActiveClass)
nextFrame(function () {
removeTransitionClass(el, leaveClass)
if (!cb.cancelled && !userWantsControl) {
whenTransitionEnds(el, type, cb)
}
})
}
leave && leave(el, cb)
if (!expectsCSS && !userWantsControl) {
cb()
}
}
}
function resolveTransition (def$$1) {
if (!def$$1) {
return
}
/* istanbul ignore else */
if (typeof def$$1 === 'object') {
var res = {}
if (def$$1.css !== false) {
extend(res, autoCssTransition(def$$1.name || 'v'))
}
extend(res, def$$1)
return res
} else if (typeof def$$1 === 'string') {
return autoCssTransition(def$$1)
}
}
var autoCssTransition = cached(function (name) {
return {
enterClass: (name + "-enter"),
leaveClass: (name + "-leave"),
appearClass: (name + "-enter"),
enterActiveClass: (name + "-enter-active"),
leaveActiveClass: (name + "-leave-active"),
appearActiveClass: (name + "-enter-active")
}
})
function once (fn) {
var called = false
return function () {
if (!called) {
called = true
fn()
}
}
}
var transition = inBrowser ? {
create: function create (_, vnode) {
if (!vnode.data.show) {
enter(vnode)
}
},
remove: function remove (vnode, rm) {
/* istanbul ignore else */
if (!vnode.data.show) {
leave(vnode, rm)
} else {
rm()
}
}
} : {}
var platformModules = [
attrs,
klass,
events,
domProps,
style,
transition
]
/* */
// the directive module should be applied last, after all
// built-in modules have been applied.
var modules = platformModules.concat(baseModules)
var patch$1 = createPatchFunction({ nodeOps: nodeOps, modules: modules })
/**
* Not type checking this file because flow doesn't like attaching
* properties to Elements.
*/
var modelableTagRE = /^input|select|textarea|vue-component-[0-9]+(-[0-9a-zA-Z_\-]*)?$/
/* istanbul ignore if */
if (isIE9) {
// http://www.matts411.com/post/internet-explorer-9-oninput/
document.addEventListener('selectionchange', function () {
var el = document.activeElement
if (el && el.vmodel) {
trigger(el, 'input')
}
})
}
var model = {
bind: function bind (el, binding, vnode) {
if (process.env.NODE_ENV !== 'production') {
if (!modelableTagRE.test(vnode.tag)) {
warn(
"v-model is not supported on element type: <" + (vnode.tag) + ">. " +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.',
vnode.context
)
}
}
if (vnode.tag === 'select') {
setSelected(el, binding, vnode.context)
/* istanbul ignore if */
if (isIE || isEdge) {
var cb = function () {
setSelected(el, binding, vnode.context)
}
nextTick(cb)
setTimeout(cb, 0)
}
} else if (vnode.tag === 'textarea' || el.type === 'text') {
if (!isAndroid) {
el.addEventListener('compositionstart', onCompositionStart)
el.addEventListener('compositionend', onCompositionEnd)
}
/* istanbul ignore if */
if (isIE9) {
el.vmodel = true
}
}
},
componentUpdated: function componentUpdated (el, binding, vnode) {
if (vnode.tag === 'select') {
setSelected(el, binding, vnode.context)
// in case the options rendered by v-for have changed,
// it's possible that the value is out-of-sync with the rendered options.
// detect such cases and filter out values that no longer has a matchig
// option in the DOM.
var needReset = el.multiple
? binding.value.some(function (v) { return hasNoMatchingOption(v, el.options); })
: hasNoMatchingOption(binding.value, el.options)
if (needReset) {
trigger(el, 'change')
}
}
}
}
function setSelected (el, binding, vm) {
var value = binding.value
var isMultiple = el.multiple
if (isMultiple && !Array.isArray(value)) {
process.env.NODE_ENV !== 'production' && warn(
"<select multiple v-model=\"" + (binding.expression) + "\"> " +
"expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)),
vm
)
return
}
var selected, option
for (var i = 0, l = el.options.length; i < l; i++) {
option = el.options[i]
if (isMultiple) {
selected = looseIndexOf(value, getValue(option)) > -1
if (option.selected !== selected) {
option.selected = selected
}
} else {
if (looseEqual(getValue(option), value)) {
if (el.selectedIndex !== i) {
el.selectedIndex = i
}
return
}
}
}
if (!isMultiple) {
el.selectedIndex = -1
}
}
function hasNoMatchingOption (value, options) {
for (var i = 0, l = options.length; i < l; i++) {
if (looseEqual(getValue(options[i]), value)) {
return false
}
}
return true
}
function getValue (option) {
return '_value' in option
? option._value
: option.value
}
function onCompositionStart (e) {
e.target.composing = true
}
function onCompositionEnd (e) {
e.target.composing = false
trigger(e.target, 'input')
}
function trigger (el, type) {
var e = document.createEvent('HTMLEvents')
e.initEvent(type, true, true)
el.dispatchEvent(e)
}
/* */
// recursively search for possible transition defined inside the component root
function locateNode (vnode) {
return vnode.child && (!vnode.data || !vnode.data.transition)
? locateNode(vnode.child._vnode)
: vnode
}
var show = {
bind: function bind (el, ref, vnode) {
var value = ref.value;
vnode = locateNode(vnode)
var transition = vnode.data && vnode.data.transition
if (value && transition && !isIE9) {
enter(vnode)
}
var originalDisplay = el.style.display === 'none' ? '' : el.style.display
el.style.display = value ? originalDisplay : 'none'
el.__vOriginalDisplay = originalDisplay
},
update: function update (el, ref, vnode) {
var value = ref.value;
var oldValue = ref.oldValue;
/* istanbul ignore if */
if (value === oldValue) { return }
vnode = locateNode(vnode)
var transition = vnode.data && vnode.data.transition
if (transition && !isIE9) {
if (value) {
enter(vnode)
el.style.display = el.__vOriginalDisplay
} else {
leave(vnode, function () {
el.style.display = 'none'
})
}
} else {
el.style.display = value ? el.__vOriginalDisplay : 'none'
}
}
}
var platformDirectives = {
model: model,
show: show
}
/* */
// Provides transition support for a single element/component.
// supports transition mode (out-in / in-out)
var transitionProps = {
name: String,
appear: Boolean,
css: Boolean,
mode: String,
type: String,
enterClass: String,
leaveClass: String,
enterActiveClass: String,
leaveActiveClass: String,
appearClass: String,
appearActiveClass: String
}
// in case the child is also an abstract component, e.g. <keep-alive>
// we want to recrusively retrieve the real component to be rendered
function getRealChild (vnode) {
var compOptions = vnode && vnode.componentOptions
if (compOptions && compOptions.Ctor.options.abstract) {
return getRealChild(getFirstComponentChild(compOptions.children))
} else {
return vnode
}
}
function extractTransitionData (comp) {
var data = {}
var options = comp.$options
// props
for (var key in options.propsData) {
data[key] = comp[key]
}
// events.
// extract listeners and pass them directly to the transition methods
var listeners = options._parentListeners
for (var key$1 in listeners) {
data[camelize(key$1)] = listeners[key$1].fn
}
return data
}
function placeholder (h, rawChild) {
return /\d-keep-alive$/.test(rawChild.tag)
? h('keep-alive')
: null
}
function hasParentTransition (vnode) {
while ((vnode = vnode.parent)) {
if (vnode.data.transition) {
return true
}
}
}
var Transition = {
name: 'transition',
props: transitionProps,
abstract: true,
render: function render (h) {
var this$1 = this;
var children = this.$slots.default
if (!children) {
return
}
// filter out text nodes (possible whitespaces)
children = children.filter(function (c) { return c.tag; })
/* istanbul ignore if */
if (!children.length) {
return
}
// warn multiple elements
if (process.env.NODE_ENV !== 'production' && children.length > 1) {
warn(
'<transition> can only be used on a single element. Use ' +
'<transition-group> for lists.',
this.$parent
)
}
var mode = this.mode
// warn invalid mode
if (process.env.NODE_ENV !== 'production' &&
mode && mode !== 'in-out' && mode !== 'out-in') {
warn(
'invalid <transition> mode: ' + mode,
this.$parent
)
}
var rawChild = children[0]
// if this is a component root node and the component's
// parent container node also has transition, skip.
if (hasParentTransition(this.$vnode)) {
return rawChild
}
// apply transition data to child
// use getRealChild() to ignore abstract components e.g. keep-alive
var child = getRealChild(rawChild)
/* istanbul ignore if */
if (!child) {
return rawChild
}
if (this._leaving) {
return placeholder(h, rawChild)
}
child.key = child.key == null || child.isStatic
? ("__v" + (child.tag + this._uid) + "__")
: child.key
var data = (child.data || (child.data = {})).transition = extractTransitionData(this)
var oldRawChild = this._vnode
var oldChild = getRealChild(oldRawChild)
// mark v-show
// so that the transition module can hand over the control to the directive
if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) {
child.data.show = true
}
if (oldChild && oldChild.data && oldChild.key !== child.key) {
// replace old child transition data with fresh one
// important for dynamic transitions!
var oldData = oldChild.data.transition = extend({}, data)
// handle transition mode
if (mode === 'out-in') {
// return placeholder node and queue update when leave finishes
this._leaving = true
mergeVNodeHook(oldData, 'afterLeave', function () {
this$1._leaving = false
this$1.$forceUpdate()
})
return placeholder(h, rawChild)
} else if (mode === 'in-out') {
var delayedLeave
var performLeave = function () { delayedLeave() }
mergeVNodeHook(data, 'afterEnter', performLeave)
mergeVNodeHook(data, 'enterCancelled', performLeave)
mergeVNodeHook(oldData, 'delayLeave', function (leave) {
delayedLeave = leave
})
}
}
return rawChild
}
}
/* */
// Provides transition support for list items.
// supports move transitions using the FLIP technique.
// Because the vdom's children update algorithm is "unstable" - i.e.
// it doesn't guarantee the relative positioning of removed elements,
// we force transition-group to update its children into two passes:
// in the first pass, we remove all nodes that need to be removed,
// triggering their leaving transition; in the second pass, we insert/move
// into the final disired state. This way in the second pass removed
// nodes will remain where they should be.
var props = extend({
tag: String,
moveClass: String
}, transitionProps)
delete props.mode
var TransitionGroup = {
props: props,
render: function render (h) {
var tag = this.tag || this.$vnode.data.tag || 'span'
var map = Object.create(null)
var prevChildren = this.prevChildren = this.children
var rawChildren = this.$slots.default || []
var children = this.children = []
var transitionData = extractTransitionData(this)
for (var i = 0; i < rawChildren.length; i++) {
var c = rawChildren[i]
if (c.tag) {
if (c.key != null && String(c.key).indexOf('__vlist') !== 0) {
children.push(c)
map[c.key] = c
;(c.data || (c.data = {})).transition = transitionData
} else if (process.env.NODE_ENV !== 'production') {
var opts = c.componentOptions
var name = opts
? (opts.Ctor.options.name || opts.tag)
: c.tag
warn(("<transition-group> children must be keyed: <" + name + ">"))
}
}
}
if (prevChildren) {
var kept = []
var removed = []
for (var i$1 = 0; i$1 < prevChildren.length; i$1++) {
var c$1 = prevChildren[i$1]
c$1.data.transition = transitionData
c$1.data.pos = c$1.elm.getBoundingClientRect()
if (map[c$1.key]) {
kept.push(c$1)
} else {
removed.push(c$1)
}
}
this.kept = h(tag, null, kept)
this.removed = removed
}
return h(tag, null, children)
},
beforeUpdate: function beforeUpdate () {
// force removing pass
this.__patch__(
this._vnode,
this.kept,
false, // hydrating
true // removeOnly (!important, avoids unnecessary moves)
)
this._vnode = this.kept
},
updated: function updated () {
var children = this.prevChildren
var moveClass = this.moveClass || (this.name + '-move')
if (!children.length || !this.hasMove(children[0].elm, moveClass)) {
return
}
// we divide the work into three loops to avoid mixing DOM reads and writes
// in each iteration - which helps prevent layout thrashing.
children.forEach(callPendingCbs)
children.forEach(recordPosition)
children.forEach(applyTranslation)
// force reflow to put everything in position
var f = document.body.offsetHeight // eslint-disable-line
children.forEach(function (c) {
if (c.data.moved) {
var el = c.elm
var s = el.style
addTransitionClass(el, moveClass)
s.transform = s.WebkitTransform = s.transitionDuration = ''
el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) {
if (!e || /transform$/.test(e.propertyName)) {
el.removeEventListener(transitionEndEvent, cb)
el._moveCb = null
removeTransitionClass(el, moveClass)
}
})
}
})
},
methods: {
hasMove: function hasMove (el, moveClass) {
/* istanbul ignore if */
if (!hasTransition) {
return false
}
if (this._hasMove != null) {
return this._hasMove
}
addTransitionClass(el, moveClass)
var info = getTransitionInfo(el)
removeTransitionClass(el, moveClass)
return (this._hasMove = info.hasTransform)
}
}
}
function callPendingCbs (c) {
/* istanbul ignore if */
if (c.elm._moveCb) {
c.elm._moveCb()
}
/* istanbul ignore if */
if (c.elm._enterCb) {
c.elm._enterCb()
}
}
function recordPosition (c) {
c.data.newPos = c.elm.getBoundingClientRect()
}
function applyTranslation (c) {
var oldPos = c.data.pos
var newPos = c.data.newPos
var dx = oldPos.left - newPos.left
var dy = oldPos.top - newPos.top
if (dx || dy) {
c.data.moved = true
var s = c.elm.style
s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)"
s.transitionDuration = '0s'
}
}
var platformComponents = {
Transition: Transition,
TransitionGroup: TransitionGroup
}
/* */
// install platform specific utils
Vue$2.config.isUnknownElement = isUnknownElement
Vue$2.config.isReservedTag = isReservedTag
Vue$2.config.getTagNamespace = getTagNamespace
Vue$2.config.mustUseProp = mustUseProp
// install platform runtime directives & components
extend(Vue$2.options.directives, platformDirectives)
extend(Vue$2.options.components, platformComponents)
// install platform patch function
Vue$2.prototype.__patch__ = config._isServer ? noop : patch$1
// wrap mount
Vue$2.prototype.$mount = function (
el,
hydrating
) {
el = el && !config._isServer ? query(el) : undefined
return this._mount(el, hydrating)
}
// devtools global hook
/* istanbul ignore next */
setTimeout(function () {
if (config.devtools) {
if (devtools) {
devtools.emit('init', Vue$2)
} else if (
process.env.NODE_ENV !== 'production' &&
inBrowser && /Chrome\/\d+/.test(window.navigator.userAgent)
) {
console.log(
'Download the Vue Devtools for a better development experience:\n' +
'https://github.com/vuejs/vue-devtools'
)
}
}
}, 0)
module.exports = Vue$2;
|
src/index.js | zenoamaro/webpage-transcriber | import FastClick from 'fastclick';
import React from 'react';
import ReactDOM from 'react-dom';
import Root from 'views/Root';
import isMobile from 'utils/isMobile';
import scrape from 'scraper';
import spec from 'spec';
/**
* Bootstrap the scraper and the template renderer
* after doing some prep work.
*/
function bootstrap() {
// Scrape the page at this time, and convert it
// to a purer data representation.
const payload = scrape(spec);
// We create a root node for our application,
// so that we aren't influenced by listeners
// or other code that wants to touch <body>.
const rootNode = document.createElement('div');
document.body.innerHTML = '';
document.body.appendChild(rootNode);
// We want at least a viewport meta tag, so that we
// are able to optimize the content for the viewport.
const viewportNode = document.createElement('meta');
viewportNode.setAttribute('name', 'viewport');
viewportNode.setAttribute('content', 'width=device-width, user-scalable=no');
document.head.appendChild(viewportNode);
// Adopt fast-click to remove the annoying
// 300ms wait on clicks on iPhones.
FastClick.attach(document.body);
ReactDOM.render(<Root payload={payload}/>, rootNode);
}
/*
We only want to operate when we have detected
a mobile phone. We wouldn't want a bug ruining
an otherwise working mission-critical app.
*/
if (isMobile()) bootstrap();
|
ajax/libs/react-data-grid/0.14.27/react-data-grid.min.js | tholu/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports.ReactDataGrid=t(require("react"),require("react-dom")):e.ReactDataGrid=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(o){if(r[o])return r[o].exports;var i=r[o]={exports:{},id:o,loaded:!1};return e[o].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";var o=r(1),i=r(24),s=r(25);e.exports=o,e.exports.Row=i,e.exports.Cell=s},function(e,t,r){"use strict";function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},s=r(2),n=r(3),l=r(4),a=(r(24),r(15),r(27)),c=r(36),p=r(34),u=r(37),h=r(39),d=r(10);Object.assign||(Object.assign=r(38));var f=s.createClass({displayName:"ReactDataGrid",mixins:[u,p.MetricsComputatorMixin,a],propTypes:{rowHeight:s.PropTypes.number.isRequired,headerRowHeight:s.PropTypes.number,minHeight:s.PropTypes.number.isRequired,minWidth:s.PropTypes.number,enableRowSelect:s.PropTypes.oneOfType([s.PropTypes.bool,s.PropTypes.string]),onRowUpdated:s.PropTypes.func,rowGetter:s.PropTypes.func.isRequired,rowsCount:s.PropTypes.number.isRequired,toolbar:s.PropTypes.element,enableCellSelect:s.PropTypes.bool,columns:s.PropTypes.oneOfType([s.PropTypes.object,s.PropTypes.array]).isRequired,onFilter:s.PropTypes.func,onCellCopyPaste:s.PropTypes.func,onCellsDragged:s.PropTypes.func,onAddFilter:s.PropTypes.func,onGridSort:s.PropTypes.func,onDragHandleDoubleClick:s.PropTypes.func,onGridRowsUpdated:s.PropTypes.func,onRowSelect:s.PropTypes.func,rowKey:s.PropTypes.string,rowScrollTimeout:s.PropTypes.number,onClearFilters:s.PropTypes.func},getDefaultProps:function(){return{enableCellSelect:!1,tabIndex:-1,rowHeight:35,enableRowSelect:!1,minHeight:350,rowKey:"id",rowScrollTimeout:0}},getInitialState:function(){var e=this.createColumnMetrics(),t={columnMetrics:e,selectedRows:[],copied:null,expandedRows:[],canFilter:!1,columnFilters:{},sortDirection:null,sortColumn:null,dragged:null,scrollOffset:0};return this.props.enableCellSelect?t.selected={rowIdx:0,idx:0}:t.selected={rowIdx:-1,idx:-1},t},onSelect:function(e){if(this.props.enableCellSelect&&(this.state.selected.rowIdx!==e.rowIdx||this.state.selected.idx!==e.idx||this.state.selected.active===!1)){var t=e.idx,r=e.rowIdx;t>=0&&r>=0&&t<d.getSize(this.state.columnMetrics.columns)&&r<this.props.rowsCount&&this.setState({selected:e})}},onCellClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx})},onCellDoubleClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx}),this.setActive("Enter")},onViewportDoubleClick:function(){this.setActive()},onPressArrowUp:function(e){this.moveSelectedCell(e,-1,0)},onPressArrowDown:function(e){this.moveSelectedCell(e,1,0)},onPressArrowLeft:function(e){this.moveSelectedCell(e,0,-1)},onPressArrowRight:function(e){this.moveSelectedCell(e,0,1)},onPressTab:function(e){this.moveSelectedCell(e,0,e.shiftKey?-1:1)},onPressEnter:function(e){this.setActive(e.key)},onPressDelete:function(e){this.setActive(e.key)},onPressEscape:function(e){this.setInactive(e.key)},onPressBackspace:function(e){this.setActive(e.key)},onPressChar:function(e){this.isKeyPrintable(e.keyCode)&&this.setActive(e.keyCode)},onPressKeyWithCtrl:function(e){var t={KeyCode_c:99,KeyCode_C:67,KeyCode_V:86,KeyCode_v:118},r=this.state.selected.idx;if(this.canEdit(r))if(e.keyCode===t.KeyCode_c||e.keyCode===t.KeyCode_C){var o=this.getSelectedValue();this.handleCopy({value:o})}else e.keyCode!==t.KeyCode_v&&e.keyCode!==t.KeyCode_V||this.handlePaste()},onCellCommit:function(e){var t=Object.assign({},this.state.selected);t.active=!1,"Tab"===e.key&&(t.idx+=1);var r=this.state.expandedRows;this.setState({selected:t,expandedRows:r}),this.props.onRowUpdated&&this.props.onRowUpdated(e);var o=e.rowIdx;this.props.onGridRowsUpdated&&this.props.onGridRowsUpdated({cellKey:e.cellKey,fromRow:o,toRow:o,updated:e.updated,action:"cellUpdate"})},onDragStart:function(e){var t=this.getSelectedValue();this.handleDragStart({idx:this.state.selected.idx,rowIdx:this.state.selected.rowIdx,value:t}),e&&e.dataTransfer&&e.dataTransfer.setData&&(e.dataTransfer.dropEffect="move",e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain","dummy"))},onToggleFilter:function(){this.setState({canFilter:!this.state.canFilter}),this.state.canFilter===!1&&this.props.onClearFilters&&this.props.onClearFilters()},onDragHandleDoubleClick:function(e){if(this.props.onDragHandleDoubleClick&&this.props.onDragHandleDoubleClick(e),this.props.onGridRowsUpdated){var t=this.getColumn(e.idx).key,r=o({},t,e.rowData[t]);this.props.onGridRowsUpdated({cellKey:t,fromRow:e.rowIdx,toRow:this.props.rowsCount-1,updated:r,action:"columnFill"})}},handleDragStart:function(e){if(this.dragEnabled()){var t=e.idx,r=e.rowIdx;t>=0&&r>=0&&t<this.getSize()&&r<this.props.rowsCount&&this.setState({dragged:e})}},handleDragEnd:function(){if(this.dragEnabled()){var e=void 0,t=void 0,r=this.state.selected,i=this.state.dragged,s=this.getColumn(this.state.selected.idx).key;if(e=r.rowIdx<i.overRowIdx?r.rowIdx:i.overRowIdx,t=r.rowIdx>i.overRowIdx?r.rowIdx:i.overRowIdx,this.props.onCellsDragged&&this.props.onCellsDragged({cellKey:s,fromRow:e,toRow:t,value:i.value}),this.props.onGridRowsUpdated){var n=o({},s,i.value);this.props.onGridRowsUpdated({cellKey:s,fromRow:e,toRow:t,updated:n,action:"cellDrag"})}this.setState({dragged:{complete:!0}})}},handleDragEnter:function(e){if(this.dragEnabled()){var t=this.state.dragged;t.overRowIdx=e,this.setState({dragged:t})}},handleTerminateDrag:function(){this.dragEnabled()&&this.setState({dragged:null})},handlePaste:function(){if(this.copyPasteEnabled()){var e=this.state.selected,t=this.getColumn(this.state.selected.idx).key,r=this.state.textToCopy,i=e.rowIdx;if(this.props.onCellCopyPaste&&this.props.onCellCopyPaste({cellKey:t,rowIdx:i,value:r,fromRow:this.state.copied.rowIdx,toRow:i}),this.props.onGridRowsUpdated){var s=o({},t,r);this.props.onGridRowsUpdated({cellKey:t,fromRow:i,toRow:i,updated:s,action:"copyPaste"})}this.setState({copied:null})}},handleCopy:function(e){if(this.copyPasteEnabled()){var t=e.value,r=this.state.selected,o={idx:r.idx,rowIdx:r.rowIdx};this.setState({textToCopy:t,copied:o})}},handleSort:function(e,t){this.setState({sortDirection:t,sortColumn:e},function(){this.props.onGridSort(e,t)})},getSelectedRow:function(e,t){var r=this,o=e.filter(function(e){return e[r.props.rowKey]===t});return o.length>0?o[0]:void 0},handleRowSelect:function(e,t,r,o){o.stopPropagation();var i="single"===this.props.enableRowSelect?[]:this.state.selectedRows.slice(0),s=this.getSelectedRow(i,r[this.props.rowKey]);s?s.isSelected=!s.isSelected:(r.isSelected=!0,i.push(r)),this.setState({selectedRows:i,selected:{rowIdx:e,idx:0}}),this.props.onRowSelect&&this.props.onRowSelect(i.filter(function(e){return e.isSelected===!0}))},handleCheckboxChange:function(e){var t=void 0;t=e.currentTarget instanceof HTMLInputElement&&e.currentTarget.checked===!0;for(var r=[],o=0;o<this.props.rowsCount;o++){var i=Object.assign({},this.props.rowGetter(o),{isSelected:t});r.push(i)}this.setState({selectedRows:r}),"function"==typeof this.props.onRowSelect&&this.props.onRowSelect(r.filter(function(e){return e.isSelected===!0}))},getScrollOffSet:function(){var e=0,t=n.findDOMNode(this).querySelector(".react-grid-Canvas");t&&(e=t.offsetWidth-t.clientWidth),this.setState({scrollOffset:e})},getRowOffsetHeight:function(){var e=0;return this.getHeaderRows().forEach(function(t){return e+=parseFloat(t.height,10)}),e},getHeaderRows:function(){var e=[{ref:"row",height:this.props.headerRowHeight||this.props.rowHeight,rowType:"header"}];return this.state.canFilter===!0&&e.push({ref:"filterRow",filterable:!0,onFilterChange:this.props.onAddFilter,height:45,rowType:"filter"}),e},getInitialSelectedRows:function(){for(var e=[],t=0;t<this.props.rowsCount;t++)e.push(!1);return e},getSelectedValue:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx,r=this.getColumn(t).key,o=this.props.rowGetter(e);return h.get(o,r)},moveSelectedCell:function(e,t,r){e.preventDefault();var o=this.state.selected.rowIdx+t,i=this.state.selected.idx+r;this.onSelect({idx:i,rowIdx:o})},setActive:function(e){var t=this.state.selected.rowIdx,r=this.state.selected.idx;if(this.canEdit(r)&&!this.isActive()){var o=Object.assign(this.state.selected,{idx:r,rowIdx:t,active:!0,initialKeyCode:e});this.setState({selected:o})}},setInactive:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx;if(this.canEdit(t)&&this.isActive()){var r=Object.assign(this.state.selected,{idx:t,rowIdx:e,active:!1});this.setState({selected:r})}},canEdit:function(e){var t=this.getColumn(e);return this.props.enableCellSelect===!0&&(null!=t.editor||t.editable)},isActive:function(){return this.state.selected.active===!0},setupGridColumns:function(){var e=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],t=e.columns.slice(0),r={};if(e.enableRowSelect){var o="single"===e.enableRowSelect?null:s.createElement("div",{className:"react-grid-checkbox-container"},s.createElement("input",{className:"react-grid-checkbox",type:"checkbox",name:"select-all-checkbox",onChange:this.handleCheckboxChange}),s.createElement("label",{htmlFor:"select-all-checkbox",className:"react-grid-checkbox-label"})),i={key:"select-row",name:"",formatter:s.createElement(c,null),onCellChange:this.handleRowSelect,filterable:!1,headerRenderer:o,width:60,locked:!0,getRowMetaData:function(e){return e}};r=t.unshift(i),t=r>0?t:r}return t},copyPasteEnabled:function(){return null!==this.props.onCellCopyPaste},dragEnabled:function(){return null!==this.props.onCellsDragged},renderToolbar:function(){var e=this.props.toolbar;return s.isValidElement(e)?s.cloneElement(e,{onToggleFilter:this.onToggleFilter,numberOfRows:this.props.rowsCount}):void 0},render:function(){var e={selected:this.state.selected,dragged:this.state.dragged,onCellClick:this.onCellClick,onCellDoubleClick:this.onCellDoubleClick,onCommit:this.onCellCommit,onCommitCancel:this.setInactive,copied:this.state.copied,handleDragEnterRow:this.handleDragEnter,handleTerminateDrag:this.handleTerminateDrag,onDragHandleDoubleClick:this.onDragHandleDoubleClick},t=this.renderToolbar(),r=this.props.minWidth||this.DOMMetrics.gridWidth(),o=r-this.state.scrollOffset;return("undefined"==typeof r||isNaN(r)||0===r)&&(r="100%"),("undefined"==typeof o||isNaN(o)||0===o)&&(o="100%"),s.createElement("div",{className:"react-grid-Container",style:{width:r}},t,s.createElement("div",{className:"react-grid-Main"},s.createElement(l,i({ref:"base"},this.props,{rowKey:this.props.rowKey,headerRows:this.getHeaderRows(),columnMetrics:this.state.columnMetrics,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,rowHeight:this.props.rowHeight,cellMetaData:e,selectedRows:this.state.selectedRows.filter(function(e){return e.isSelected===!0}),expandedRows:this.state.expandedRows,rowOffsetHeight:this.getRowOffsetHeight(),sortColumn:this.state.sortColumn,sortDirection:this.state.sortDirection,onSort:this.handleSort,minHeight:this.props.minHeight,totalWidth:o,onViewportKeydown:this.onKeyDown,onViewportDragStart:this.onDragStart,onViewportDragEnd:this.handleDragEnd,onViewportDoubleClick:this.onViewportDoubleClick,onColumnResize:this.onColumnResize,rowScrollTimeout:this.props.rowScrollTimeout}))))}});e.exports=f},function(t,r){t.exports=e},function(e,r){e.exports=t},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},i=r(2),s=i.PropTypes,n=r(5),l=r(21),a=r(35),c=r(34),p=r(31),u=i.createClass({displayName:"Grid",propTypes:{rowGetter:s.oneOfType([s.array,s.func]).isRequired,columns:s.oneOfType([s.array,s.object]),columnMetrics:s.object,minHeight:s.number,totalWidth:s.oneOfType([s.number,s.string]),headerRows:s.oneOfType([s.array,s.func]),rowHeight:s.number,rowRenderer:s.func,emptyRowsView:s.func,expandedRows:s.oneOfType([s.array,s.func]),selectedRows:s.oneOfType([s.array,s.func]),rowsCount:s.number,onRows:s.func,sortColumn:i.PropTypes.string,sortDirection:i.PropTypes.oneOf(["ASC","DESC","NONE"]),rowOffsetHeight:s.number.isRequired,onViewportKeydown:s.func.isRequired,onViewportDragStart:s.func.isRequired,onViewportDragEnd:s.func.isRequired,onViewportDoubleClick:s.func.isRequired,onColumnResize:s.func,onSort:s.func,cellMetaData:s.shape(p),rowKey:s.string.isRequired,rowScrollTimeout:s.number},mixins:[a,c.MetricsComputatorMixin],getDefaultProps:function(){return{rowHeight:35,minHeight:350}},getStyle:function(){return{overflow:"hidden",outline:0,position:"relative",minHeight:this.props.minHeight}},render:function(){var e=this.props.headerRows||[{ref:"row"}],t=this.props.emptyRowsView;return i.createElement("div",o({},this.props,{style:this.getStyle(),className:"react-grid-Grid"}),i.createElement(n,{ref:"header",columnMetrics:this.props.columnMetrics,onColumnResize:this.props.onColumnResize,height:this.props.rowHeight,totalWidth:this.props.totalWidth,headerRows:e,sortColumn:this.props.sortColumn,sortDirection:this.props.sortDirection,onSort:this.props.onSort,onScroll:this.onHeaderScroll}),this.props.rowsCount>=1||0===this.props.rowsCount&&!this.props.emptyRowsView?i.createElement("div",{ref:"viewPortContainer",onKeyDown:this.props.onViewportKeydown,onDoubleClick:this.props.onViewportDoubleClick,onDragStart:this.props.onViewportDragStart,onDragEnd:this.props.onViewportDragEnd},i.createElement(l,{ref:"viewport",rowKey:this.props.rowKey,width:this.props.columnMetrics.width,rowHeight:this.props.rowHeight,rowRenderer:this.props.rowRenderer,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columnMetrics:this.props.columnMetrics,totalWidth:this.props.totalWidth,onScroll:this.onScroll,onRows:this.props.onRows,cellMetaData:this.props.cellMetaData,rowOffsetHeight:this.props.rowOffsetHeight||this.props.rowHeight*e.length,minHeight:this.props.minHeight,rowScrollTimeout:this.props.rowScrollTimeout})):i.createElement("div",{ref:"emptyView",className:"react-grid-Empty"},i.createElement(t,null)))}});e.exports=u},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},i=r(2),s=r(3),n=r(6),l=r(7),a=r(8),c=r(10),p=r(12),u=i.PropTypes,h=i.createClass({displayName:"Header",propTypes:{columnMetrics:u.shape({width:u.number.isRequired,columns:u.any}).isRequired,totalWidth:u.oneOfType([u.number,u.string]),height:u.number.isRequired,headerRows:u.array.isRequired,sortColumn:u.string,sortDirection:u.oneOf(["ASC","DESC","NONE"]),onSort:u.func,onColumnResize:u.func,onScroll:u.func},getInitialState:function(){return{resizing:null}},componentWillReceiveProps:function(){this.setState({resizing:null})},shouldComponentUpdate:function(e,t){var r=!a.sameColumns(this.props.columnMetrics.columns,e.columnMetrics.columns,a.sameColumn)||this.props.totalWidth!==e.totalWidth||this.props.headerRows.length!==e.headerRows.length||this.state.resizing!==t.resizing||this.props.sortColumn!==e.sortColumn||this.props.sortDirection!==e.sortDirection;return r},onColumnResize:function(e,t){var r=this.state.resizing||this.props,o=this.getColumnPosition(e);if(null!=o){var i={columnMetrics:l(r.columnMetrics)};i.columnMetrics=a.resizeColumn(i.columnMetrics,o,t),i.columnMetrics.totalWidth<r.columnMetrics.totalWidth&&(i.columnMetrics.totalWidth=r.columnMetrics.totalWidth),i.column=c.getColumn(i.columnMetrics.columns,o),this.setState({resizing:i})}},onColumnResizeEnd:function(e,t){var r=this.getColumnPosition(e);null!==r&&this.props.onColumnResize&&this.props.onColumnResize(r,t||e.width)},getHeaderRows:function(){var e=this,t=this.getColumnMetrics(),r=void 0;this.state.resizing&&(r=this.state.resizing.column);var o=[];return this.props.headerRows.forEach(function(s,n){var l={position:"absolute",top:e.getCombinedHeaderHeights(n),left:0,width:e.props.totalWidth,overflow:"hidden"};o.push(i.createElement(p,{key:s.ref,ref:s.ref,rowType:s.rowType,style:l,onColumnResize:e.onColumnResize,onColumnResizeEnd:e.onColumnResizeEnd,width:t.width,height:s.height||e.props.height,columns:t.columns,resizing:r,filterable:s.filterable,onFilterChange:s.onFilterChange,sortColumn:e.props.sortColumn,sortDirection:e.props.sortDirection,onSort:e.props.onSort,onScroll:e.props.onScroll}))}),o},getColumnMetrics:function(){var e=void 0;return e=this.state.resizing?this.state.resizing.columnMetrics:this.props.columnMetrics},getColumnPosition:function(e){var t=this.getColumnMetrics(),r=-1;return t.columns.forEach(function(t,o){t.key===e.key&&(r=o)}),-1===r?null:r},getCombinedHeaderHeights:function(e){var t=this.props.headerRows.length;"undefined"!=typeof e&&(t=e);for(var r=0,o=0;t>o;o++)r+=this.props.headerRows[o].height||this.props.height;return r},getStyle:function(){return{position:"relative",height:this.getCombinedHeaderHeights(),overflow:"hidden"}},setScrollLeft:function(e){var t=s.findDOMNode(this.refs.row);if(t.scrollLeft=e,this.refs.row.setScrollLeft(e),this.refs.filterRow){var r=s.findDOMNode(this.refs.filterRow);r.scrollLeft=e,this.refs.filterRow.setScrollLeft(e)}},render:function(){var e=n({"react-grid-Header":!0,"react-grid-Header--resizing":!!this.state.resizing}),t=this.getHeaderRows();return i.createElement("div",o({},this.props,{style:this.getStyle(),className:e}),t)}});e.exports=h},function(e,t,r){function o(){for(var e,t="",r=0;r<arguments.length;r++)if(e=arguments[r])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+o.apply(null,e);else if("object"==typeof e)for(var i in e)e.hasOwnProperty(i)&&e[i]&&(t+=" "+i);return t.substr(1)}var i,s;"undefined"!=typeof e&&e.exports&&(e.exports=o),i=[],s=function(){return o}.apply(t,i),!(void 0!==s&&(e.exports=s))},function(e,t){"use strict";function r(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t}e.exports=r},function(e,t,r){"use strict";function o(e,t){return e.map(function(e){var r=Object.assign({},e);return e.width&&/^([0-9]+)%$/.exec(e.width.toString())&&(r.width=Math.floor(e.width/100*t)),r})}function i(e,t,r){var o=e.filter(function(e){return!e.width});return e.map(function(e){return e.width||(0>=t?e.width=r:e.width=Math.floor(t/d.getSize(o))),e})}function s(e){var t=0;return e.map(function(e){return e.left=t,t+=e.width,e})}function n(e){var t=o(e.columns,e.totalWidth),r=t.filter(function(e){return e.width}).reduce(function(e,t){return e-t.width},e.totalWidth);r-=f();var n=t.filter(function(e){return e.width}).reduce(function(e,t){return e+t.width},0);return t=i(t,r,e.minColumnWidth),t=s(t),{columns:t,width:n,totalWidth:e.totalWidth,minColumnWidth:e.minColumnWidth}}function l(e,t,r){var o=d.getColumn(e.columns,t),i=u(e);i.columns=e.columns.slice(0);var s=u(o);return s.width=Math.max(r,i.minColumnWidth),i=d.spliceColumn(i,t,s),n(i)}function a(e,t){return"undefined"!=typeof Immutable&&e instanceof Immutable.List&&t instanceof Immutable.List}function c(e,t,r){var o=void 0,i=void 0,s=void 0,n={},l={};if(d.getSize(e)!==d.getSize(t))return!1;for(o=0,i=d.getSize(e);i>o;o++)s=e[o],n[s.key]=s;for(o=0,i=d.getSize(t);i>o;o++){s=t[o],l[s.key]=s;var a=n[s.key];if(void 0===a||!r(a,s))return!1}for(o=0,i=d.getSize(e);i>o;o++){s=e[o];var c=l[s.key];if(void 0===c)return!1}return!0}function p(e,t,r){return a(e,t)?e===t:c(e,t,r)}var u=r(7),h=r(9),d=r(10),f=r(11);e.exports={recalculate:n,resizeColumn:l,sameColumn:h,sameColumns:p}},function(e,t,r){"use strict";var o=r(2).isValidElement;e.exports=function(e,t){var r=void 0;for(r in e)if(e.hasOwnProperty(r)){if("function"==typeof e[r]&&"function"==typeof t[r]||o(e[r])&&o(t[r]))continue;if(!t.hasOwnProperty(r)||e[r]!==t[r])return!1}for(r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}},function(e,t){"use strict";e.exports={getColumn:function(e,t){return Array.isArray(e)?e[t]:"undefined"!=typeof Immutable?e.get(t):void 0},spliceColumn:function(e,t,r){return Array.isArray(e.columns)?e.columns.splice(t,1,r):"undefined"!=typeof Immutable&&(e.columns=e.columns.splice(t,1,r)),e},getSize:function(e){return Array.isArray(e)?e.length:"undefined"!=typeof Immutable?e.size:void 0}}},function(e,t){"use strict";function r(){if(void 0===o){var e=document.createElement("div");e.style.width="50px",e.style.height="50px",e.style.position="absolute",e.style.top="-200px",e.style.left="-200px";var t=document.createElement("div");t.style.height="100px",t.style.width="100%",e.appendChild(t),document.body.appendChild(e);var r=e.clientWidth;e.style.overflowY="scroll";var i=t.clientWidth;document.body.removeChild(e),o=r-i}return o}var o=void 0;e.exports=r},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},i=r(2),s=r(13),n=r(14),l=r(11),a=(r(15),r(10)),c=r(18),p=r(19),u=r(20),h=i.PropTypes,d={overflow:i.PropTypes.string,width:h.oneOfType([h.number,h.string]),height:i.PropTypes.number,position:i.PropTypes.string},f=["ASC","DESC","NONE"],m=i.createClass({displayName:"HeaderRow",propTypes:{width:h.oneOfType([h.number,h.string]),height:h.number.isRequired,columns:h.oneOfType([h.array,h.object]),onColumnResize:h.func,onSort:h.func.isRequired,onColumnResizeEnd:h.func,style:h.shape(d),sortColumn:h.string,sortDirection:i.PropTypes.oneOf(f),cellRenderer:h.func,headerCellRenderer:h.func,filterable:h.bool,onFilterChange:h.func,resizing:h.func,onScroll:h.func,rowType:h.string},mixins:[a],shouldComponentUpdate:function(e){return e.width!==this.props.width||e.height!==this.props.height||e.columns!==this.props.columns||!s(e.style,this.props.style)||this.props.sortColumn!==e.sortColumn||this.props.sortDirection!==e.sortDirection},getHeaderCellType:function(e){return e.filterable&&this.props.filterable?u.FILTERABLE:e.sortable?u.SORTABLE:u.NONE},getFilterableHeaderCell:function(){return i.createElement(p,{onChange:this.props.onFilterChange})},getSortableHeaderCell:function(e){var t=this.props.sortColumn===e.key?this.props.sortDirection:f.NONE;return i.createElement(c,{columnKey:e.key,onSort:this.props.onSort,sortDirection:t})},getHeaderRenderer:function(e){var t=void 0;if(e.headerRenderer)t=e.headerRenderer;else{var r=this.getHeaderCellType(e);switch(r){case u.SORTABLE:t=this.getSortableHeaderCell(e);break;case u.FILTERABLE:t=this.getFilterableHeaderCell()}}return t},getStyle:function(){return{overflow:"hidden",width:"100%",height:this.props.height,position:"absolute"}},getCells:function(){for(var e=[],t=[],r=0,o=this.getSize(this.props.columns);o>r;r++){var s=this.getColumn(this.props.columns,r),l=this.getHeaderRenderer(s);"select-row"===s.key&&"filter"===this.props.rowType&&(l=i.createElement("div",null));var a=i.createElement(n,{ref:r,key:r,height:this.props.height,column:s,renderer:l,resizing:this.props.resizing===s,onResize:this.props.onColumnResize,onResizeEnd:this.props.onColumnResizeEnd});s.locked?t.push(a):e.push(a)}return e.concat(t)},setScrollLeft:function(e){var t=this;this.props.columns.forEach(function(r,o){r.locked&&t.refs[o].setScrollLeft(e)})},render:function(){var e={width:this.props.width?this.props.width+l():"100%",height:this.props.height,whiteSpace:"nowrap",overflowX:"hidden",overflowY:"hidden"},t=this.getCells();return i.createElement("div",o({},this.props,{className:"react-grid-HeaderRow",onScroll:this.props.onScroll}),i.createElement("div",{style:e},t))}});e.exports=m},function(e,t){"use strict";function r(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(var s=o.bind(t),n=0;n<r.length;n++)if(!s(r[n])||e[r[n]]!==t[r[n]])return!1;return!0}var o=Object.prototype.hasOwnProperty;e.exports=r},function(e,t,r){"use strict";function o(e){return i.createElement("div",{className:"widget-HeaderCell__value"},e.column.name)}var i=r(2),s=r(3),n=r(6),l=r(15),a=r(16),c=i.PropTypes,p=i.createClass({displayName:"HeaderCell",propTypes:{renderer:c.oneOfType([c.func,c.element]).isRequired,column:c.shape(l).isRequired,onResize:c.func.isRequired,height:c.number.isRequired,onResizeEnd:c.func.isRequired,className:c.string},getDefaultProps:function(){return{renderer:o}},getInitialState:function(){return{resizing:!1}},onDragStart:function(e){this.setState({resizing:!0}),e&&e.dataTransfer&&e.dataTransfer.setData&&e.dataTransfer.setData("text/plain","dummy")},onDrag:function(e){var t=this.props.onResize||null;if(t){var r=this.getWidthFromMouseEvent(e);r>0&&t(this.props.column,r)}},onDragEnd:function(e){var t=this.getWidthFromMouseEvent(e);this.props.onResizeEnd(this.props.column,t),this.setState({resizing:!1})},getWidthFromMouseEvent:function(e){var t=e.pageX,r=s.findDOMNode(this).getBoundingClientRect().left;return t-r},getCell:function(){return i.isValidElement(this.props.renderer)?i.cloneElement(this.props.renderer,{column:this.props.column}):this.props.renderer({column:this.props.column})},getStyle:function(){return{width:this.props.column.width,left:this.props.column.left,display:"inline-block",position:"absolute",overflow:"hidden",height:this.props.height,margin:0,textOverflow:"ellipsis",whiteSpace:"nowrap"}},setScrollLeft:function(e){var t=s.findDOMNode(this);t.style.webkitTransform="translate3d("+e+"px, 0px, 0px)",t.style.transform="translate3d("+e+"px, 0px, 0px)"},render:function(){var e=void 0;this.props.column.resizable&&(e=i.createElement(a,{onDrag:this.onDrag,onDragStart:this.onDragStart,onDragEnd:this.onDragEnd}));var t=n({"react-grid-HeaderCell":!0,"react-grid-HeaderCell--resizing":this.state.resizing,"react-grid-HeaderCell--locked":this.props.column.locked});t=n(t,this.props.className,this.props.column.cellClass);var r=this.getCell();return i.createElement("div",{className:t,style:this.getStyle()},r,e)}});e.exports=p},function(e,t,r){"use strict";var o=r(2),i={name:o.PropTypes.node.isRequired,key:o.PropTypes.string.isRequired,width:o.PropTypes.number.isRequired,filterable:o.PropTypes.bool};e.exports=i},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},i=r(2),s=r(17),n=i.createClass({displayName:"ResizeHandle",style:{position:"absolute",top:0,right:0,width:6,height:"100%"},render:function(){return i.createElement(s,o({},this.props,{className:"react-grid-HeaderCell__resizeHandle",style:this.style}))}});e.exports=n},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},i=r(2),s=i.PropTypes,n=i.createClass({displayName:"Draggable",propTypes:{onDragStart:s.func,onDragEnd:s.func,onDrag:s.func,component:s.oneOfType([s.func,s.constructor])},getDefaultProps:function(){return{onDragStart:function(){return!0},onDragEnd:function(){},onDrag:function(){}}},getInitialState:function(){return{drag:null}},componentWillUnmount:function(){this.cleanUp()},onMouseDown:function(e){var t=this.props.onDragStart(e);null===t&&0!==e.button||(window.addEventListener("mouseup",this.onMouseUp),window.addEventListener("mousemove",this.onMouseMove),this.setState({drag:t}))},onMouseMove:function(e){null!==this.state.drag&&(e.preventDefault&&e.preventDefault(),this.props.onDrag(e))},onMouseUp:function(e){this.cleanUp(),this.props.onDragEnd(e,this.state.drag),this.setState({drag:null})},cleanUp:function(){window.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("mousemove",this.onMouseMove)},render:function(){return i.createElement("div",o({},this.props,{onMouseDown:this.onMouseDown,className:"react-grid-HeaderCell__draggable"}))}});e.exports=n},function(e,t,r){"use strict";var o=r(2),i=r(6),s={ASC:"ASC",DESC:"DESC",NONE:"NONE"},n=o.createClass({displayName:"SortableHeaderCell",propTypes:{columnKey:o.PropTypes.string.isRequired,column:o.PropTypes.shape({name:o.PropTypes.node}),onSort:o.PropTypes.func.isRequired,sortDirection:o.PropTypes.oneOf(["ASC","DESC","NONE"])},onClick:function(){var e=void 0;switch(this.props.sortDirection){default:case null:case void 0:case s.NONE:e=s.ASC;break;case s.ASC:e=s.DESC;break;case s.DESC:e=s.NONE}this.props.onSort(this.props.columnKey,e)},getSortByText:function(){var e={ASC:"9650",DESC:"9660",NONE:""};return String.fromCharCode(e[this.props.sortDirection])},render:function(){var e=i({"react-grid-HeaderCell-sortable":!0,"react-grid-HeaderCell-sortable--ascending":"ASC"===this.props.sortDirection,"react-grid-HeaderCell-sortable--descending":"DESC"===this.props.sortDirection});return o.createElement("div",{className:e,onClick:this.onClick,style:{cursor:"pointer"}},this.props.column.name,o.createElement("span",{className:"pull-right"},this.getSortByText()))}});e.exports=n},function(e,t,r){"use strict";var o=r(2),i=r(15),s=o.createClass({displayName:"FilterableHeaderCell",propTypes:{onChange:o.PropTypes.func.isRequired,column:o.PropTypes.shape(i)},getInitialState:function(){return{filterTerm:""}},handleChange:function(e){var t=e.target.value;this.setState({filterTerm:t}),this.props.onChange({filterTerm:t,columnKey:this.props.column.key})},renderInput:function(){if(this.props.column.filterable===!1)return o.createElement("span",null);var e="header-filter-"+this.props.column.key;return o.createElement("input",{key:e,type:"text",className:"form-control input-sm",placeholder:"Search",value:this.state.filterTerm,onChange:this.handleChange})},render:function(){return o.createElement("div",null,o.createElement("div",{className:"form-group"},this.renderInput()))}});e.exports=s},function(e,t){"use strict";var r={SORTABLE:0,FILTERABLE:1,NONE:2,CHECKBOX:3};e.exports=r},function(e,t,r){"use strict";var o=r(2),i=r(22),s=r(33),n=r(31),l=o.PropTypes,a=o.createClass({displayName:"Viewport",mixins:[s],propTypes:{rowOffsetHeight:l.number.isRequired,totalWidth:l.oneOfType([l.number,l.string]).isRequired,columnMetrics:l.object.isRequired,rowGetter:l.oneOfType([l.array,l.func]).isRequired,selectedRows:l.array,expandedRows:l.array,rowRenderer:l.func,rowsCount:l.number.isRequired,rowHeight:l.number.isRequired,onRows:l.func,onScroll:l.func,minHeight:l.number,cellMetaData:l.shape(n),rowKey:l.string.isRequired,rowScrollTimeout:l.number},onScroll:function(e){this.updateScroll(e.scrollTop,e.scrollLeft,this.state.height,this.props.rowHeight,this.props.rowsCount),this.props.onScroll&&this.props.onScroll({scrollTop:e.scrollTop,scrollLeft:e.scrollLeft})},getScroll:function(){return this.refs.canvas.getScroll()},setScrollLeft:function(e){this.refs.canvas.setScrollLeft(e)},render:function(){var e={padding:0,bottom:0,left:0,right:0,overflow:"hidden",position:"absolute",top:this.props.rowOffsetHeight};return o.createElement("div",{className:"react-grid-Viewport",style:e},o.createElement(i,{ref:"canvas",rowKey:this.props.rowKey,totalWidth:this.props.totalWidth,width:this.props.columnMetrics.width,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columns:this.props.columnMetrics.columns,rowRenderer:this.props.rowRenderer,displayStart:this.state.displayStart,displayEnd:this.state.displayEnd,cellMetaData:this.props.cellMetaData,height:this.state.height,rowHeight:this.props.rowHeight,onScroll:this.onScroll,onRows:this.props.onRows,rowScrollTimeout:this.props.rowScrollTimeout}))}});e.exports=a},function(e,t,r){
"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}var i=r(13),s=o(i),n=r(2),l=r(3),a=r(6),c=n.PropTypes,p=r(23),u=r(24),h=r(31),d=n.createClass({displayName:"Canvas",mixins:[p],propTypes:{rowRenderer:c.oneOfType([c.func,c.element]),rowHeight:c.number.isRequired,height:c.number.isRequired,width:c.number,totalWidth:c.oneOfType([c.number,c.string]),style:c.string,className:c.string,displayStart:c.number.isRequired,displayEnd:c.number.isRequired,rowsCount:c.number.isRequired,rowGetter:c.oneOfType([c.func.isRequired,c.array.isRequired]),expandedRows:c.array,onRows:c.func,onScroll:c.func,columns:c.oneOfType([c.object,c.array]).isRequired,cellMetaData:c.shape(h).isRequired,selectedRows:c.array,rowKey:n.PropTypes.string,rowScrollTimeout:n.PropTypes.number},getDefaultProps:function(){return{rowRenderer:u,onRows:function(){},selectedRows:[],rowScrollTimeout:0}},getInitialState:function(){return{displayStart:this.props.displayStart,displayEnd:this.props.displayEnd,scrollingTimeout:null}},componentWillMount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentDidMount:function(){this.onRows()},componentWillReceiveProps:function(e){e.displayStart===this.state.displayStart&&e.displayEnd===this.state.displayEnd||this.setState({displayStart:e.displayStart,displayEnd:e.displayEnd})},shouldComponentUpdate:function(e,t){var r=t.displayStart!==this.state.displayStart||t.displayEnd!==this.state.displayEnd||t.scrollingTimeout!==this.state.scrollingTimeout||e.rowsCount!==this.props.rowsCount||e.rowHeight!==this.props.rowHeight||e.columns!==this.props.columns||e.width!==this.props.width||e.cellMetaData!==this.props.cellMetaData||!(0,s["default"])(e.style,this.props.style);return r},componentWillUnmount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentDidUpdate:function(){0!==this._scroll.scrollTop&&0!==this._scroll.scrollLeft&&this.setScrollLeft(this._scroll.scrollLeft),this.onRows()},onRows:function(){this._currentRowsRange!=={start:0,end:0}&&(this.props.onRows(this._currentRowsRange),this._currentRowsRange={start:0,end:0})},onScroll:function(e){var t=this;if(this.getDOMNode()===e.target){this.appendScrollShim();var r=e.target.scrollLeft,o=e.target.scrollTop||this._scroll.scrollTop,i={scrollTop:o,scrollLeft:r},s=Math.abs(this._scroll.scrollTop-i.scrollTop)/this.props.rowHeight,n=s>this.props.displayEnd-this.props.displayStart;if(this._scroll=i,this.props.onScroll(i),n&&this.props.rowScrollTimeout>0){var l=this.state.scrollingTimeout;l&&clearTimeout(l),l=setTimeout(function(){null!==t.state.scrollingTimeout&&t.setState({scrollingTimeout:null})},this.props.rowScrollTimeout),this.setState({scrollingTimeout:l})}}},getRows:function(e,t){if(this._currentRowsRange={start:e,end:t},Array.isArray(this.props.rowGetter))return this.props.rowGetter.slice(e,t);for(var r=[],o=e;t>o;o++)r.push(this.props.rowGetter(o));return r},getScrollbarWidth:function(){var e=0,t=l.findDOMNode(this);return e=t.offsetWidth-t.clientWidth},getScroll:function(){var e=l.findDOMNode(this),t=e.scrollTop,r=e.scrollLeft;return{scrollTop:t,scrollLeft:r}},isRowSelected:function(e){var t=this,r=this.props.selectedRows.filter(function(r){var o=e.get?e.get(t.props.rowKey):e[t.props.rowKey];return r[t.props.rowKey]===o});return r.length>0&&r[0].isSelected},_currentRowsLength:0,_currentRowsRange:{start:0,end:0},_scroll:{scrollTop:0,scrollLeft:0},setScrollLeft:function(e){if(0!==this._currentRowsLength){if(!this.refs)return;for(var t=0,r=this._currentRowsLength;r>t;t++)this.refs[t]&&this.refs[t].setScrollLeft&&this.refs[t].setScrollLeft(e)}},renderRow:function(e){if(null!==this.state.scrollingTimeout)return this.renderScrollingPlaceholder(e);var t=this.props.rowRenderer;return"function"==typeof t?n.createElement(t,e):n.isValidElement(this.props.rowRenderer)?n.cloneElement(this.props.rowRenderer,e):void 0},renderScrollingPlaceholder:function(e){var t={row:{height:e.height,overflow:"hidden"},cell:{height:e.height,position:"absolute"},placeholder:{backgroundColor:"rgba(211, 211, 211, 0.45)",width:"60%",height:Math.floor(.3*e.height)}};return n.createElement("div",{key:e.key,style:t.row,className:"react-grid-Row"},this.props.columns.map(function(e,r){return n.createElement("div",{style:Object.assign(t.cell,{width:e.width,left:e.left}),key:r,className:"react-grid-Cell"},n.createElement("div",{style:Object.assign(t.placeholder,{width:Math.floor(.6*e.width)})}))}))},renderPlaceholder:function(e,t){return n.createElement("div",{key:e,style:{height:t}},this.props.columns.map(function(e,t){return n.createElement("div",{style:{width:e.width},key:t})}))},render:function(){var e=this,t=this.state.displayStart,r=this.state.displayEnd,o=this.props.rowHeight,i=this.props.rowsCount,s=this.getRows(t,r).map(function(r,i){return e.renderRow({key:t+i,ref:i,idx:t+i,row:r,height:o,columns:e.props.columns,isSelected:e.isRowSelected(r),expandedRows:e.props.expandedRows,cellMetaData:e.props.cellMetaData})});this._currentRowsLength=s.length,t>0&&s.unshift(this.renderPlaceholder("top",t*o)),i-r>0&&s.push(this.renderPlaceholder("bottom",(i-r)*o));var l={position:"absolute",top:0,left:0,overflowX:"auto",overflowY:"scroll",width:this.props.totalWidth,height:this.props.height,transform:"translate3d(0, 0, 0)"};return n.createElement("div",{style:l,onScroll:this.onScroll,className:a("react-grid-Canvas",this.props.className,{opaque:this.props.cellMetaData.selected&&this.props.cellMetaData.selected.active})},n.createElement("div",{style:{width:this.props.width,overflow:"hidden"}},s))}});e.exports=d},function(e,t,r){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}var i=r(3),s=o(i),n={appendScrollShim:function(){if(!this._scrollShim){var e=this._scrollShimSize(),t=document.createElement("div");t.classList?t.classList.add("react-grid-ScrollShim"):t.className+=" react-grid-ScrollShim",t.style.position="absolute",t.style.top=0,t.style.left=0,t.style.width=e.width+"px",t.style.height=e.height+"px",s["default"].findDOMNode(this).appendChild(t),this._scrollShim=t}this._scheduleRemoveScrollShim()},_scrollShimSize:function(){return{width:this.props.width,height:this.props.length*this.props.rowHeight}},_scheduleRemoveScrollShim:function(){this._scheduleRemoveScrollShimTimer&&clearTimeout(this._scheduleRemoveScrollShimTimer),this._scheduleRemoveScrollShimTimer=setTimeout(this._removeScrollShim,200)},_removeScrollShim:function(){this._scrollShim&&(this._scrollShim.parentNode.removeChild(this._scrollShim),this._scrollShim=void 0)}};e.exports=n},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},i=r(2),s=r(6),n=r(25),l=r(8),a=r(10),c=r(31),p=i.PropTypes,u=i.createClass({displayName:"Row",propTypes:{height:p.number.isRequired,columns:p.oneOfType([p.object,p.array]).isRequired,row:p.any.isRequired,cellRenderer:p.func,cellMetaData:p.shape(c),isSelected:p.bool,idx:p.number.isRequired,key:p.string,expandedRows:p.arrayOf(p.object)},mixins:[a],getDefaultProps:function(){return{cellRenderer:n,isSelected:!1,height:35}},shouldComponentUpdate:function(e){return!l.sameColumns(this.props.columns,e.columns,l.sameColumn)||this.doesRowContainSelectedCell(this.props)||this.doesRowContainSelectedCell(e)||this.willRowBeDraggedOver(e)||e.row!==this.props.row||this.hasRowBeenCopied()||this.props.isSelected!==e.isSelected||e.height!==this.props.height},handleDragEnter:function(){var e=this.props.cellMetaData.handleDragEnterRow;e&&e(this.props.idx)},getSelectedColumn:function(){var e=this.props.cellMetaData.selected;return e&&e.idx?this.getColumn(this.props.columns,e.idx):void 0},getCells:function(){var e=this,t=[],r=[],o=this.getSelectedColumn();return this.props.columns.forEach(function(s,n){var l=e.props.cellRenderer,a=i.createElement(l,{ref:n,key:s.key+"-"+n,idx:n,rowIdx:e.props.idx,value:e.getCellValue(s.key||n),column:s,height:e.getRowHeight(),formatter:s.formatter,cellMetaData:e.props.cellMetaData,rowData:e.props.row,selectedColumn:o,isRowSelected:e.props.isSelected});s.locked?r.push(a):t.push(a)}),t.concat(r)},getRowHeight:function(){var e=this.props.expandedRows||null;if(e&&this.props.key){var t=e[this.props.key]||null;if(t)return t.height}return this.props.height},getCellValue:function(e){var t=void 0;return"select-row"===e?this.props.isSelected:t="function"==typeof this.props.row.get?this.props.row.get(e):this.props.row[e]},setScrollLeft:function(e){var t=this;this.props.columns.forEach(function(r,o){if(r.locked){if(!t.refs[o])return;t.refs[o].setScrollLeft(e)}})},doesRowContainSelectedCell:function(e){var t=e.cellMetaData.selected;return!(!t||t.rowIdx!==e.idx)},willRowBeDraggedOver:function(e){var t=e.cellMetaData.dragged;return null!=t&&(t.rowIdx>=0||t.complete===!0)},hasRowBeenCopied:function(){var e=this.props.cellMetaData.copied;return null!=e&&e.rowIdx===this.props.idx},renderCell:function(e){return"function"==typeof this.props.cellRenderer&&this.props.cellRenderer.call(this,e),i.isValidElement(this.props.cellRenderer)?i.cloneElement(this.props.cellRenderer,e):this.props.cellRenderer(e)},render:function(){var e=s("react-grid-Row","react-grid-Row--"+(this.props.idx%2===0?"even":"odd"),{"row-selected":this.props.isSelected}),t={height:this.getRowHeight(this.props),overflow:"hidden"},r=this.getCells();return i.createElement("div",o({},this.props,{className:e,style:t,onDragEnter:this.handleDragEnter}),i.isValidElement(this.props.row)?this.props.row:r)}});e.exports=u},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},i=r(2),s=r(3),n=r(6),l=r(26),a=r(15),c=r(30),p=r(31),u=r(32),h=i.createClass({displayName:"Cell",propTypes:{rowIdx:i.PropTypes.number.isRequired,idx:i.PropTypes.number.isRequired,selected:i.PropTypes.shape({idx:i.PropTypes.number.isRequired}),selectedColumn:i.PropTypes.object,height:i.PropTypes.number,tabIndex:i.PropTypes.number,ref:i.PropTypes.string,column:i.PropTypes.shape(a).isRequired,value:i.PropTypes.oneOfType([i.PropTypes.string,i.PropTypes.number,i.PropTypes.object,i.PropTypes.bool]).isRequired,isExpanded:i.PropTypes.bool,isRowSelected:i.PropTypes.bool,cellMetaData:i.PropTypes.shape(p).isRequired,handleDragStart:i.PropTypes.func,className:i.PropTypes.string,cellControls:i.PropTypes.any,rowData:i.PropTypes.object.isRequired},getDefaultProps:function(){return{tabIndex:-1,ref:"cell",isExpanded:!1}},getInitialState:function(){return{isRowChanging:!1,isCellValueChanging:!1}},componentDidMount:function(){this.checkFocus()},componentWillReceiveProps:function(e){this.setState({isRowChanging:this.props.rowData!==e.rowData,isCellValueChanging:this.props.value!==e.value})},componentDidUpdate:function(){this.checkFocus();var e=this.props.cellMetaData.dragged;e&&e.complete===!0&&this.props.cellMetaData.handleTerminateDrag(),this.state.isRowChanging&&null!=this.props.selectedColumn&&this.applyUpdateClass()},shouldComponentUpdate:function(e){return this.props.column.width!==e.column.width||this.props.column.left!==e.column.left||this.props.rowData!==e.rowData||this.props.height!==e.height||this.props.rowIdx!==e.rowIdx||this.isCellSelectionChanging(e)||this.isDraggedCellChanging(e)||this.isCopyCellChanging(e)||this.props.isRowSelected!==e.isRowSelected||this.isSelected()||this.props.value!==e.value},onCellClick:function(){var e=this.props.cellMetaData;null!=e&&null!=e.onCellClick&&e.onCellClick({rowIdx:this.props.rowIdx,idx:this.props.idx})},onCellDoubleClick:function(){var e=this.props.cellMetaData;null!=e&&null!=e.onCellDoubleClick&&e.onCellDoubleClick({rowIdx:this.props.rowIdx,idx:this.props.idx})},onDragHandleDoubleClick:function(e){e.stopPropagation();var t=this.props.cellMetaData;null!=t&&null!=t.onCellDoubleClick&&t.onDragHandleDoubleClick({rowIdx:this.props.rowIdx,idx:this.props.idx,rowData:this.getRowData()})},onDragOver:function(e){e.preventDefault()},getStyle:function(){var e={position:"absolute",width:this.props.column.width,height:this.props.height,left:this.props.column.left};return e},getFormatter:function(){var e=this.props.column;return this.isActive()?i.createElement(l,{rowData:this.getRowData(),rowIdx:this.props.rowIdx,idx:this.props.idx,cellMetaData:this.props.cellMetaData,column:e,height:this.props.height}):this.props.column.formatter},getRowData:function(){return this.props.rowData.toJSON?this.props.rowData.toJSON():this.props.rowData},getFormatterDependencies:function(){return"function"==typeof this.props.column.getRowMetaData?this.props.column.getRowMetaData(this.getRowData(),this.props.column):void 0},getCellClass:function(){var e=n(this.props.column.cellClass,"react-grid-Cell",this.props.className,this.props.column.locked?"react-grid-Cell--locked":null),t=n({"row-selected":this.props.isRowSelected,selected:this.isSelected()&&!this.isActive(),editing:this.isActive(),copied:this.isCopied()||this.wasDraggedOver()||this.isDraggedOverUpwards()||this.isDraggedOverDownwards(),"active-drag-cell":this.isSelected()||this.isDraggedOver(),"is-dragged-over-up":this.isDraggedOverUpwards(),"is-dragged-over-down":this.isDraggedOverDownwards(),"was-dragged-over":this.wasDraggedOver()});return n(e,t)},getUpdateCellClass:function(){return this.props.column.getUpdateCellClass?this.props.column.getUpdateCellClass(this.props.selectedColumn,this.props.column,this.state.isCellValueChanging):""},isColumnSelected:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:e.selected&&e.selected.idx===this.props.idx},isSelected:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:e.selected&&e.selected.rowIdx===this.props.rowIdx&&e.selected.idx===this.props.idx},isActive:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:this.isSelected()&&e.selected.active===!0},isCellSelectionChanging:function(e){var t=this.props.cellMetaData;if(null==t||null==t.selected)return!1;var r=e.cellMetaData.selected;return t.selected&&r?this.props.idx===r.idx||this.props.idx===t.selected.idx:!0},applyUpdateClass:function(){var e=this.getUpdateCellClass();if(null!=e&&""!==e){var t=s.findDOMNode(this);t.classList?(t.classList.remove(e),t.classList.add(e)):-1===t.className.indexOf(e)&&(t.className=t.className+" "+e)}},setScrollLeft:function(e){var t=this;if(t.isMounted()){var r=s.findDOMNode(this),o="translate3d("+e+"px, 0px, 0px)";r.style.webkitTransform=o,r.style.transform=o}},isCopied:function(){var e=this.props.cellMetaData.copied;return e&&e.rowIdx===this.props.rowIdx&&e.idx===this.props.idx},isDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&e.overRowIdx===this.props.rowIdx&&e.idx===this.props.idx},wasDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&(e.overRowIdx<this.props.rowIdx&&this.props.rowIdx<e.rowIdx||e.overRowIdx>this.props.rowIdx&&this.props.rowIdx>e.rowIdx)&&e.idx===this.props.idx},isDraggedCellChanging:function(e){var t=void 0,r=this.props.cellMetaData.dragged,o=e.cellMetaData.dragged;return r?t=o&&this.props.idx===o.idx||r&&this.props.idx===r.idx:!1},isCopyCellChanging:function(e){var t=void 0,r=this.props.cellMetaData.copied,o=e.cellMetaData.copied;return r?t=o&&this.props.idx===o.idx||r&&this.props.idx===r.idx:!1},isDraggedOverUpwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx<e.rowIdx},isDraggedOverDownwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx>e.rowIdx},checkFocus:function(){if(this.isSelected()&&!this.isActive()){for(var e=s.findDOMNode(this);null!=e&&-1===e.className.indexOf("react-grid-Viewport");)e=e.parentElement;var t=!1;if(null==document.activeElement||document.activeElement.nodeName&&"string"==typeof document.activeElement.nodeName&&"body"===document.activeElement.nodeName.toLowerCase())t=!0;else if(e)for(var r=document.activeElement;null!=r;){if(r===e){t=!0;break}r=r.parentElement}t&&s.findDOMNode(this).focus()}},canEdit:function(){return null!=this.props.column.editor||this.props.column.editable},renderCellContent:function(e){var t=void 0,r=this.getFormatter();return i.isValidElement(r)?(e.dependentValues=this.getFormatterDependencies(),t=i.cloneElement(r,e)):t=c(r)?i.createElement(r,{value:this.props.value,dependentValues:this.getFormatterDependencies()}):i.createElement(u,{value:this.props.value}),i.createElement("div",{ref:"cell",className:"react-grid-Cell__value"},t," ",this.props.cellControls)},render:function(){var e=this.getStyle(),t=this.getCellClass(),r=this.renderCellContent({value:this.props.value,column:this.props.column,rowIdx:this.props.rowIdx,isExpanded:this.props.isExpanded}),s=!this.isActive()&&this.canEdit()?i.createElement("div",{className:"drag-handle",draggable:"true",onDoubleClick:this.onDragHandleDoubleClick},i.createElement("span",{style:{display:"none"}})):null;return i.createElement("div",o({},this.props,{className:t,style:e,onClick:this.onCellClick,onDoubleClick:this.onCellDoubleClick,onDragOver:this.onDragOver}),r,s)}});e.exports=h},function(e,t,r){"use strict";var o=r(2),i=r(6),s=r(27),n=r(28),l=r(30),a=o.createClass({displayName:"EditorContainer",mixins:[s],propTypes:{rowIdx:o.PropTypes.number,rowData:o.PropTypes.object.isRequired,value:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.number,o.PropTypes.object,o.PropTypes.bool]).isRequired,cellMetaData:o.PropTypes.shape({selected:o.PropTypes.object.isRequired,copied:o.PropTypes.object,dragged:o.PropTypes.object,onCellClick:o.PropTypes.func,onCellDoubleClick:o.PropTypes.func,onCommitCancel:o.PropTypes.func,onCommit:o.PropTypes.func}).isRequired,column:o.PropTypes.object.isRequired,height:o.PropTypes.number.isRequired},changeCommitted:!1,getInitialState:function(){return{isInvalid:!1}},componentDidMount:function(){var e=this.getInputNode();void 0!==e&&(this.setTextInputFocus(),this.getEditor().disableContainerStyles||(e.className+=" editor-main",e.style.height=this.props.height-1+"px"))},componentWillUnmount:function(){this.changeCommitted||this.hasEscapeBeenPressed()||this.commit({key:"Enter"})},createEditor:function(){var e=this,t=function(t){return e.editor=t},r={ref:t,column:this.props.column,value:this.getInitialValue(),onCommit:this.commit,rowMetaData:this.getRowMetaData(),height:this.props.height,onBlur:this.commit,onOverrideKeyDown:this.onKeyDown},i=this.props.column.editor;return i&&o.isValidElement(i)?o.cloneElement(i,r):o.createElement(n,{ref:t,column:this.props.column,value:this.getInitialValue(),onBlur:this.commit,rowMetaData:this.getRowMetaData(),onKeyDown:function(){},commit:function(){}})},onPressEnter:function(){this.commit({key:"Enter"})},onPressTab:function(){this.commit({key:"Tab"})},onPressEscape:function(e){this.editorIsSelectOpen()?e.stopPropagation():this.props.cellMetaData.onCommitCancel()},onPressArrowDown:function(e){this.editorHasResults()?e.stopPropagation():this.commit(e)},onPressArrowUp:function(e){this.editorHasResults()?e.stopPropagation():this.commit(e)},onPressArrowLeft:function(e){this.isCaretAtBeginningOfInput()?this.commit(e):e.stopPropagation()},onPressArrowRight:function(e){this.isCaretAtEndOfInput()?this.commit(e):e.stopPropagation()},editorHasResults:function(){return l(this.getEditor().hasResults)?this.getEditor().hasResults():!1},editorIsSelectOpen:function(){return l(this.getEditor().isSelectOpen)?this.getEditor().isSelectOpen():!1},getRowMetaData:function(){return"function"==typeof this.props.column.getRowMetaData?this.props.column.getRowMetaData(this.props.rowData,this.props.column):void 0},getEditor:function(){return this.editor},getInputNode:function(){return this.getEditor().getInputNode()},getInitialValue:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode;if("Delete"===t||"Backspace"===t)return"";if("Enter"===t)return this.props.value;var r=t?String.fromCharCode(t):this.props.value;return r},getContainerClass:function(){return i({"has-error":this.state.isInvalid===!0})},commit:function(e){var t=e||{},r=this.getEditor().getValue();if(this.isNewValueValid(r)){this.changeCommitted=!0;var o=this.props.column.key;this.props.cellMetaData.onCommit({cellKey:o,rowIdx:this.props.rowIdx,updated:r,key:t.key})}},isNewValueValid:function(e){if(l(this.getEditor().validate)){var t=this.getEditor().validate(e);return this.setState({isInvalid:!t}),t}return!0},setCaretAtEndOfInput:function(){var e=this.getInputNode(),t=e.value.length;if(e.setSelectionRange)e.setSelectionRange(t,t);else if(e.createTextRange){var r=e.createTextRange();r.moveStart("character",t),r.collapse(),r.select()}},isCaretAtBeginningOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.selectionEnd&&0===e.selectionStart},isCaretAtEndOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.value.length},setTextInputFocus:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode,r=this.getInputNode();r.focus(),"INPUT"===r.tagName&&(this.isKeyPrintable(t)?r.select():(r.focus(),r.select()))},hasEscapeBeenPressed:function(){var e=!1,t=27;return window.event&&(window.event.keyCode===t?e=!0:window.event.which===t&&(e=!0)),e},renderStatusIcon:function(){return this.state.isInvalid===!0?o.createElement("span",{className:"glyphicon glyphicon-remove form-control-feedback"}):void 0},render:function(){return o.createElement("div",{className:this.getContainerClass(),onKeyDown:this.onKeyDown,commit:this.commit},this.createEditor(),this.renderStatusIcon())}});e.exports=a},function(e,t){"use strict";var r={onKeyDown:function(e){if(this.isCtrlKeyHeldDown(e))this.checkAndCall("onPressKeyWithCtrl",e);else if(this.isKeyExplicitlyHandled(e.key)){var t="onPress"+e.key;this.checkAndCall(t,e)}else this.isKeyPrintable(e.keyCode)&&this.checkAndCall("onPressChar",e)},isKeyPrintable:function(e){var t=e>47&&58>e||32===e||13===e||e>64&&91>e||e>95&&112>e||e>185&&193>e||e>218&&223>e;return t},isKeyExplicitlyHandled:function(e){return"function"==typeof this["onPress"+e]},isCtrlKeyHeldDown:function(e){return e.ctrlKey===!0&&"Control"!==e.key},checkAndCall:function(e,t){"function"==typeof this[e]&&this[e](t)}};e.exports=r},function(e,t,r){"use strict";function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),l=r(2),a=r(29),c=function(e){function t(){return o(this,t),i(this,Object.getPrototypeOf(t).apply(this,arguments))}return s(t,e),n(t,[{key:"render",value:function(){return l.createElement("input",{ref:"input",type:"text",onBlur:this.props.onBlur,className:"form-control",defaultValue:this.props.value})}}]),t}(a);e.exports=c},function(e,t,r){"use strict";function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),l=r(2),a=r(3),c=r(15),p=function(e){function t(){return o(this,t),i(this,Object.getPrototypeOf(t).apply(this,arguments))}return s(t,e),n(t,[{key:"getStyle",value:function(){return{width:"100%"}}},{key:"getValue",value:function(){var e={};return e[this.props.column.key]=this.getInputNode().value,e}},{key:"getInputNode",value:function(){var e=a.findDOMNode(this);return"INPUT"===e.tagName?e:e.querySelector("input:not([type=hidden])")}},{key:"inheritContainerStyles",value:function(){return!0}}]),t}(l.Component);p.propTypes={onKeyDown:l.PropTypes.func.isRequired,value:l.PropTypes.any.isRequired,onBlur:l.PropTypes.func.isRequired,column:l.PropTypes.shape(c).isRequired,commit:l.PropTypes.func.isRequired},e.exports=p},function(e,t){"use strict";var r=function(e){var t={};return e&&"[object Function]"===t.toString.call(e)};e.exports=r},function(e,t,r){"use strict";var o=r(2).PropTypes;e.exports={selected:o.object.isRequired,copied:o.object,dragged:o.object,onCellClick:o.func.isRequired,onCellDoubleClick:o.func.isRequired,onCommit:o.func.isRequired,onCommitCancel:o.func.isRequired,handleDragEnterRow:o.func.isRequired,handleTerminateDrag:o.func.isRequired}},function(e,t,r){"use strict";var o=r(2),i=o.createClass({displayName:"SimpleCellFormatter",propTypes:{value:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.number,o.PropTypes.object,o.PropTypes.bool]).isRequired},shouldComponentUpdate:function(e){return e.value!==this.props.value},render:function(){return o.createElement("div",{title:this.props.value},this.props.value)}});e.exports=i},function(e,t,r){"use strict";var o=r(2),i=r(3),s=r(34),n=Math.min,l=Math.max,a=Math.floor,c=Math.ceil;e.exports={mixins:[s.MetricsMixin],DOMMetrics:{viewportHeight:function(){return i.findDOMNode(this).offsetHeight}},propTypes:{rowHeight:o.PropTypes.number,rowsCount:o.PropTypes.number.isRequired},getDefaultProps:function(){return{rowHeight:30}},getInitialState:function(){return this.getGridState(this.props)},getGridState:function(e){var t=c((e.minHeight-e.rowHeight)/e.rowHeight),r=n(2*t,e.rowsCount);return{displayStart:0,displayEnd:r,height:e.minHeight,scrollTop:0,scrollLeft:0}},updateScroll:function(e,t,r,o,i){var s=c(r/o),p=a(e/o),u=n(p+s,i),h=l(0,p-2*s),d=n(p+2*s,i),f={visibleStart:p,visibleEnd:u,displayStart:h,displayEnd:d,height:r,scrollTop:e,scrollLeft:t};this.setState(f)},metricsUpdated:function(){var e=this.DOMMetrics.viewportHeight();e&&this.updateScroll(this.state.scrollTop,this.state.scrollLeft,e,this.props.rowHeight,this.props.rowsCount)},componentWillReceiveProps:function(e){if(this.props.rowHeight!==e.rowHeight||this.props.minHeight!==e.minHeight)this.setState(this.getGridState(e));else if(this.props.rowsCount!==e.rowsCount)this.updateScroll(this.state.scrollTop,this.state.scrollLeft,this.state.height,e.rowHeight,e.rowsCount);else if(this.props.rowOffsetHeight!==e.rowOffsetHeight){var t=this.props.rowOffsetHeight-e.rowOffsetHeight;this.updateScroll(this.state.scrollTop,this.state.scrollLeft,this.state.height+t,e.rowHeight,e.rowsCount)}}}},function(e,t,r){"use strict";var o=r(2),i=r(7),s={metricsComputator:o.PropTypes.object},n={childContextTypes:s,getChildContext:function(){return{metricsComputator:this}},getMetricImpl:function(e){return this._DOMMetrics.metrics[e].value},registerMetricsImpl:function(e,t){var r={},o=this._DOMMetrics;for(var i in t){if(void 0!==o.metrics[i])throw new Error("DOM metric "+i+" is already defined");o.metrics[i]={component:e,computator:t[i].bind(e)},r[i]=this.getMetricImpl.bind(null,i)}return-1===o.components.indexOf(e)&&o.components.push(e),r},unregisterMetricsFor:function(e){var t=this._DOMMetrics,r=t.components.indexOf(e);if(r>-1){t.components.splice(r,1);var o=void 0,i={};for(o in t.metrics)t.metrics[o].component===e&&(i[o]=!0);for(o in i)i.hasOwnProperty(o)&&delete t.metrics[o]}},updateMetrics:function(){var e=this._DOMMetrics,t=!1;for(var r in e.metrics)if(e.metrics.hasOwnProperty(r)){var o=e.metrics[r].computator();o!==e.metrics[r].value&&(t=!0),e.metrics[r].value=o}if(t)for(var i=0,s=e.components.length;s>i;i++)e.components[i].metricsUpdated&&e.components[i].metricsUpdated()},componentWillMount:function(){this._DOMMetrics={metrics:{},components:[]}},componentDidMount:function(){window.addEventListener?window.addEventListener("resize",this.updateMetrics):window.attachEvent("resize",this.updateMetrics),this.updateMetrics()},componentWillUnmount:function(){window.removeEventListener("resize",this.updateMetrics)}},l={contextTypes:s,componentWillMount:function(){if(this.DOMMetrics){this._DOMMetricsDefs=i(this.DOMMetrics),this.DOMMetrics={};for(var e in this._DOMMetricsDefs)this._DOMMetricsDefs.hasOwnProperty(e)&&(this.DOMMetrics[e]=function(){})}},componentDidMount:function(){this.DOMMetrics&&(this.DOMMetrics=this.registerMetrics(this._DOMMetricsDefs))},componentWillUnmount:function(){return this.registerMetricsImpl?void(this.hasOwnProperty("DOMMetrics")&&delete this.DOMMetrics):this.context.metricsComputator.unregisterMetricsFor(this)},registerMetrics:function(e){return this.registerMetricsImpl?this.registerMetricsImpl(this,e):this.context.metricsComputator.registerMetricsImpl(this,e)},getMetric:function(e){return this.getMetricImpl?this.getMetricImpl(e):this.context.metricsComputator.getMetricImpl(e)}};e.exports={MetricsComputatorMixin:n,MetricsMixin:l}},function(e,t){"use strict";e.exports={componentDidMount:function(){this._scrollLeft=this.refs.viewport?this.refs.viewport.getScroll().scrollLeft:0,this._onScroll()},componentDidUpdate:function(){this._onScroll()},componentWillMount:function(){this._scrollLeft=void 0},componentWillUnmount:function(){this._scrollLeft=void 0},onScroll:function(e){this._scrollLeft!==e.scrollLeft&&(this._scrollLeft=e.scrollLeft,this._onScroll())},onHeaderScroll:function(e){var t=e.target.scrollLeft;if(this._scrollLeft!==t){this._scrollLeft=t,this.refs.header.setScrollLeft(t);var r=ReactDOM.findDOMNode(this.refs.viewport.refs.canvas);r.scrollLeft=t,this.refs.viewport.refs.canvas.setScrollLeft(t)}},_onScroll:function(){void 0!==this._scrollLeft&&(this.refs.header.setScrollLeft(this._scrollLeft),this.refs.viewport&&this.refs.viewport.setScrollLeft(this._scrollLeft))}}},function(e,t,r){"use strict";var o=r(2),i=o.createClass({displayName:"CheckboxEditor",propTypes:{value:o.PropTypes.bool,rowIdx:o.PropTypes.number,column:o.PropTypes.shape({key:o.PropTypes.string,onCellChange:o.PropTypes.func}),dependentValues:o.PropTypes.object},handleChange:function(e){this.props.column.onCellChange(this.props.rowIdx,this.props.column.key,this.props.dependentValues,e)},render:function(){var e=null!=this.props.value?this.props.value:!1,t="checkbox"+this.props.rowIdx;return o.createElement("div",{className:"react-grid-checkbox-container",onClick:this.handleChange},o.createElement("input",{className:"react-grid-checkbox",type:"checkbox",name:t,checked:e}),o.createElement("label",{htmlFor:t,className:"react-grid-checkbox-label"}))}});e.exports=i},function(e,t,r){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var s=r(3),n=o(s),l=r(8),a=r(34);Object.assign=r(38);var c=r(2).PropTypes,p=r(10),u=function h(){i(this,h)};e.exports={mixins:[a.MetricsMixin],propTypes:{columns:c.arrayOf(u),minColumnWidth:c.number,columnEquality:c.func,onColumnResize:c.func},DOMMetrics:{gridWidth:function(){return n["default"].findDOMNode(this).parentElement.offsetWidth}},getDefaultProps:function(){return{minColumnWidth:80,columnEquality:l.sameColumn}},componentWillMount:function(){this._mounted=!0;
},componentWillReceiveProps:function(e){if(e.columns&&(!l.sameColumns(this.props.columns,e.columns,this.props.columnEquality)||e.minWidth!==this.props.minWidth)){var t=this.createColumnMetrics(e);this.setState({columnMetrics:t})}},getTotalWidth:function(){var e=0;return e=this._mounted?this.DOMMetrics.gridWidth():p.getSize(this.props.columns)*this.props.minColumnWidth},getColumnMetricsType:function(e){var t=e.totalWidth||this.getTotalWidth(),r={columns:e.columns,totalWidth:t,minColumnWidth:e.minColumnWidth},o=l.recalculate(r);return o},getColumn:function(e){var t=this.state.columnMetrics.columns;return Array.isArray(t)?t[e]:"undefined"!=typeof Immutable?t.get(e):void 0},getSize:function(){var e=this.state.columnMetrics.columns;return Array.isArray(e)?e.length:"undefined"!=typeof Immutable?e.size:void 0},metricsUpdated:function(){var e=this.createColumnMetrics();this.setState({columnMetrics:e})},createColumnMetrics:function(){var e=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],t=this.setupGridColumns(e);return this.getColumnMetricsType({columns:t,minColumnWidth:this.props.minColumnWidth,totalWidth:e.minWidth})},onColumnResize:function(e,t){var r=l.resizeColumn(this.state.columnMetrics,e,t);this.setState({columnMetrics:r}),this.props.onColumnResize&&this.props.onColumnResize(e,t)}}},function(e,t){"use strict";function r(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=Object.assign||function(e,t){for(var o,i,s=r(e),n=1;n<arguments.length;n++){o=arguments[n],i=Object.keys(Object(o));for(var l=0;l<i.length;l++)s[i[l]]=o[i[l]]}return s}},function(e,t){"use strict";var r={get:function(e,t){return"function"==typeof e.get?e.get(t):e[t]}};e.exports=r}])}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.